@juspay/neurolink 6.1.0 → 6.2.1

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 (303) hide show
  1. package/CHANGELOG.md +16 -6
  2. package/dist/agent/direct-tools.js +6 -5
  3. package/dist/cli/commands/config.d.ts +13 -13
  4. package/dist/cli/index.js +3 -9
  5. package/dist/config/configManager.js +11 -10
  6. package/dist/core/analytics.d.ts +11 -1
  7. package/dist/core/analytics.js +2 -2
  8. package/dist/core/base-provider.js +4 -18
  9. package/dist/core/dynamic-models.d.ts +8 -8
  10. package/dist/core/factory.js +3 -11
  11. package/dist/index.d.ts +2 -4
  12. package/dist/index.js +2 -11
  13. package/dist/lib/agent/direct-tools.js +6 -5
  14. package/dist/lib/config/configManager.js +11 -10
  15. package/dist/lib/core/analytics.d.ts +11 -1
  16. package/dist/lib/core/analytics.js +2 -2
  17. package/dist/lib/core/base-provider.js +4 -18
  18. package/dist/lib/core/dynamic-models.d.ts +8 -8
  19. package/dist/lib/core/factory.js +3 -11
  20. package/dist/lib/index.d.ts +2 -4
  21. package/dist/lib/index.js +2 -11
  22. package/dist/lib/mcp/factory.d.ts +1 -1
  23. package/dist/lib/mcp/index.d.ts +9 -21
  24. package/dist/lib/mcp/index.js +16 -57
  25. package/dist/lib/mcp/registry.js +1 -1
  26. package/dist/lib/mcp/servers/ai-providers/ai-analysis-tools.js +2 -1
  27. package/dist/lib/mcp/tool-registry.js +1 -1
  28. package/dist/lib/neurolink.d.ts +1 -9
  29. package/dist/lib/neurolink.js +22 -71
  30. package/dist/lib/providers/amazon-bedrock.js +5 -16
  31. package/dist/lib/providers/anthropic-baseprovider.js +3 -21
  32. package/dist/lib/providers/anthropic.js +4 -7
  33. package/dist/lib/providers/azure-openai.js +6 -3
  34. package/dist/lib/providers/google-vertex.js +5 -9
  35. package/dist/lib/providers/huggingFace.js +5 -10
  36. package/dist/lib/providers/mistral.js +5 -8
  37. package/dist/lib/providers/openAI.js +4 -7
  38. package/dist/lib/telemetry/index.js +2 -1
  39. package/dist/lib/utils/logger.d.ts +62 -2
  40. package/dist/lib/utils/logger.js +174 -9
  41. package/dist/lib/utils/providerConfig.d.ts +117 -0
  42. package/dist/lib/utils/providerConfig.js +353 -0
  43. package/dist/lib/utils/providerUtils.d.ts +2 -1
  44. package/dist/lib/utils/providerUtils.js +53 -36
  45. package/dist/lib/utils/timeout.d.ts +72 -1
  46. package/dist/lib/utils/timeout.js +203 -2
  47. package/dist/mcp/factory.d.ts +1 -1
  48. package/dist/mcp/index.d.ts +9 -21
  49. package/dist/mcp/index.js +16 -57
  50. package/dist/mcp/registry.js +1 -1
  51. package/dist/mcp/servers/ai-providers/ai-analysis-tools.js +2 -1
  52. package/dist/mcp/tool-registry.js +1 -1
  53. package/dist/neurolink.d.ts +1 -9
  54. package/dist/neurolink.js +22 -71
  55. package/dist/providers/amazon-bedrock.js +5 -16
  56. package/dist/providers/anthropic-baseprovider.js +3 -21
  57. package/dist/providers/anthropic.js +4 -7
  58. package/dist/providers/azure-openai.js +6 -3
  59. package/dist/providers/google-vertex.js +5 -9
  60. package/dist/providers/huggingFace.js +5 -10
  61. package/dist/providers/mistral.js +5 -8
  62. package/dist/providers/openAI.js +4 -7
  63. package/dist/telemetry/index.js +2 -1
  64. package/dist/utils/logger.d.ts +62 -2
  65. package/dist/utils/logger.js +174 -9
  66. package/dist/utils/providerConfig.d.ts +117 -0
  67. package/dist/utils/providerConfig.js +353 -0
  68. package/dist/utils/providerUtils.d.ts +2 -1
  69. package/dist/utils/providerUtils.js +53 -36
  70. package/dist/utils/timeout.d.ts +72 -1
  71. package/dist/utils/timeout.js +203 -2
  72. package/package.json +1 -1
  73. package/dist/chat/client-utils.d.ts +0 -95
  74. package/dist/chat/client-utils.js +0 -315
  75. package/dist/chat/index.d.ts +0 -24
  76. package/dist/chat/index.js +0 -33
  77. package/dist/chat/session-storage.d.ts +0 -77
  78. package/dist/chat/session-storage.js +0 -233
  79. package/dist/chat/session.d.ts +0 -96
  80. package/dist/chat/session.js +0 -257
  81. package/dist/chat/sse-handler.d.ts +0 -49
  82. package/dist/chat/sse-handler.js +0 -259
  83. package/dist/chat/types.d.ts +0 -74
  84. package/dist/chat/types.js +0 -5
  85. package/dist/chat/websocket-chat-handler.d.ts +0 -37
  86. package/dist/chat/websocket-chat-handler.js +0 -262
  87. package/dist/cli/commands/mcp.d.ts +0 -20
  88. package/dist/cli/commands/mcp.js +0 -1272
  89. package/dist/core/defaults.d.ts +0 -19
  90. package/dist/core/defaults.js +0 -29
  91. package/dist/core/evaluation-config.d.ts +0 -29
  92. package/dist/core/evaluation-config.js +0 -144
  93. package/dist/factories/compatibility-factory.d.ts +0 -35
  94. package/dist/factories/compatibility-factory.js +0 -71
  95. package/dist/factories/provider-generate-factory.d.ts +0 -20
  96. package/dist/factories/provider-generate-factory.js +0 -93
  97. package/dist/lib/chat/client-utils.d.ts +0 -95
  98. package/dist/lib/chat/client-utils.js +0 -315
  99. package/dist/lib/chat/index.d.ts +0 -24
  100. package/dist/lib/chat/index.js +0 -33
  101. package/dist/lib/chat/session-storage.d.ts +0 -77
  102. package/dist/lib/chat/session-storage.js +0 -233
  103. package/dist/lib/chat/session.d.ts +0 -96
  104. package/dist/lib/chat/session.js +0 -257
  105. package/dist/lib/chat/sse-handler.d.ts +0 -49
  106. package/dist/lib/chat/sse-handler.js +0 -259
  107. package/dist/lib/chat/types.d.ts +0 -74
  108. package/dist/lib/chat/types.js +0 -5
  109. package/dist/lib/chat/websocket-chat-handler.d.ts +0 -37
  110. package/dist/lib/chat/websocket-chat-handler.js +0 -262
  111. package/dist/lib/core/defaults.d.ts +0 -19
  112. package/dist/lib/core/defaults.js +0 -29
  113. package/dist/lib/core/evaluation-config.d.ts +0 -29
  114. package/dist/lib/core/evaluation-config.js +0 -144
  115. package/dist/lib/factories/compatibility-factory.d.ts +0 -35
  116. package/dist/lib/factories/compatibility-factory.js +0 -71
  117. package/dist/lib/factories/provider-generate-factory.d.ts +0 -20
  118. package/dist/lib/factories/provider-generate-factory.js +0 -93
  119. package/dist/lib/mcp/adapters/plugin-bridge.d.ts +0 -40
  120. package/dist/lib/mcp/adapters/plugin-bridge.js +0 -89
  121. package/dist/lib/mcp/auto-discovery.d.ts +0 -62
  122. package/dist/lib/mcp/auto-discovery.js +0 -149
  123. package/dist/lib/mcp/client.d.ts +0 -68
  124. package/dist/lib/mcp/client.js +0 -248
  125. package/dist/lib/mcp/config.d.ts +0 -31
  126. package/dist/lib/mcp/config.js +0 -99
  127. package/dist/lib/mcp/context-manager.d.ts +0 -171
  128. package/dist/lib/mcp/context-manager.js +0 -362
  129. package/dist/lib/mcp/contracts/mcp-contract.d.ts +0 -169
  130. package/dist/lib/mcp/contracts/mcp-contract.js +0 -58
  131. package/dist/lib/mcp/core/plugin-manager.d.ts +0 -46
  132. package/dist/lib/mcp/core/plugin-manager.js +0 -110
  133. package/dist/lib/mcp/demo/plugin-demo.d.ts +0 -20
  134. package/dist/lib/mcp/demo/plugin-demo.js +0 -118
  135. package/dist/lib/mcp/dynamic-chain-executor.d.ts +0 -225
  136. package/dist/lib/mcp/dynamic-chain-executor.js +0 -489
  137. package/dist/lib/mcp/dynamic-orchestrator.d.ts +0 -115
  138. package/dist/lib/mcp/dynamic-orchestrator.js +0 -351
  139. package/dist/lib/mcp/ecosystem.d.ts +0 -75
  140. package/dist/lib/mcp/ecosystem.js +0 -161
  141. package/dist/lib/mcp/error-manager.d.ts +0 -254
  142. package/dist/lib/mcp/error-manager.js +0 -501
  143. package/dist/lib/mcp/error-recovery.d.ts +0 -159
  144. package/dist/lib/mcp/error-recovery.js +0 -405
  145. package/dist/lib/mcp/external-client.d.ts +0 -88
  146. package/dist/lib/mcp/external-client.js +0 -331
  147. package/dist/lib/mcp/external-manager.d.ts +0 -112
  148. package/dist/lib/mcp/external-manager.js +0 -308
  149. package/dist/lib/mcp/function-calling.d.ts +0 -65
  150. package/dist/lib/mcp/function-calling.js +0 -642
  151. package/dist/lib/mcp/health-monitor.d.ts +0 -257
  152. package/dist/lib/mcp/health-monitor.js +0 -630
  153. package/dist/lib/mcp/initialize-tools.d.ts +0 -29
  154. package/dist/lib/mcp/initialize-tools.js +0 -261
  155. package/dist/lib/mcp/initialize.d.ts +0 -18
  156. package/dist/lib/mcp/initialize.js +0 -62
  157. package/dist/lib/mcp/logging.d.ts +0 -38
  158. package/dist/lib/mcp/logging.js +0 -100
  159. package/dist/lib/mcp/manager.d.ts +0 -68
  160. package/dist/lib/mcp/manager.js +0 -176
  161. package/dist/lib/mcp/neurolink-mcp-client.d.ts +0 -97
  162. package/dist/lib/mcp/neurolink-mcp-client.js +0 -462
  163. package/dist/lib/mcp/orchestrator.d.ts +0 -302
  164. package/dist/lib/mcp/orchestrator.js +0 -703
  165. package/dist/lib/mcp/plugin-manager.d.ts +0 -98
  166. package/dist/lib/mcp/plugin-manager.js +0 -296
  167. package/dist/lib/mcp/plugins/core/filesystem-mcp.d.ts +0 -36
  168. package/dist/lib/mcp/plugins/core/filesystem-mcp.js +0 -142
  169. package/dist/lib/mcp/plugins/filesystem-mcp.d.ts +0 -37
  170. package/dist/lib/mcp/plugins/filesystem-mcp.js +0 -54
  171. package/dist/lib/mcp/security-manager.d.ts +0 -87
  172. package/dist/lib/mcp/security-manager.js +0 -344
  173. package/dist/lib/mcp/semaphore-manager.d.ts +0 -137
  174. package/dist/lib/mcp/semaphore-manager.js +0 -329
  175. package/dist/lib/mcp/session-manager.d.ts +0 -187
  176. package/dist/lib/mcp/session-manager.js +0 -400
  177. package/dist/lib/mcp/session-persistence.d.ts +0 -93
  178. package/dist/lib/mcp/session-persistence.js +0 -301
  179. package/dist/lib/mcp/tool-integration.d.ts +0 -58
  180. package/dist/lib/mcp/tool-integration.js +0 -203
  181. package/dist/lib/mcp/transport-manager.d.ts +0 -154
  182. package/dist/lib/mcp/transport-manager.js +0 -334
  183. package/dist/lib/mcp/unified-mcp.d.ts +0 -133
  184. package/dist/lib/mcp/unified-mcp.js +0 -251
  185. package/dist/lib/mcp/unified-registry.d.ts +0 -165
  186. package/dist/lib/mcp/unified-registry.js +0 -538
  187. package/dist/lib/providers/analytics-helper.d.ts +0 -38
  188. package/dist/lib/providers/analytics-helper.js +0 -216
  189. package/dist/lib/providers/function-calling-provider.d.ts +0 -142
  190. package/dist/lib/providers/function-calling-provider.js +0 -630
  191. package/dist/lib/providers/mcp-provider.d.ts +0 -75
  192. package/dist/lib/providers/mcp-provider.js +0 -283
  193. package/dist/lib/providers/timeout-wrapper.d.ts +0 -40
  194. package/dist/lib/providers/timeout-wrapper.js +0 -100
  195. package/dist/lib/sdk/tool-extension.d.ts +0 -181
  196. package/dist/lib/sdk/tool-extension.js +0 -284
  197. package/dist/lib/services/streaming/streaming-manager.d.ts +0 -29
  198. package/dist/lib/services/streaming/streaming-manager.js +0 -245
  199. package/dist/lib/services/types.d.ts +0 -156
  200. package/dist/lib/services/types.js +0 -2
  201. package/dist/lib/services/websocket/websocket-server.d.ts +0 -34
  202. package/dist/lib/services/websocket/websocket-server.js +0 -305
  203. package/dist/lib/utils/provider-validation.d.ts +0 -36
  204. package/dist/lib/utils/provider-validation.js +0 -625
  205. package/dist/lib/utils/providerUtils-fixed.d.ts +0 -8
  206. package/dist/lib/utils/providerUtils-fixed.js +0 -94
  207. package/dist/lib/utils/streaming-utils.d.ts +0 -79
  208. package/dist/lib/utils/streaming-utils.js +0 -198
  209. package/dist/lib/utils/timeout-manager.d.ts +0 -75
  210. package/dist/lib/utils/timeout-manager.js +0 -244
  211. package/dist/mcp/adapters/plugin-bridge.d.ts +0 -40
  212. package/dist/mcp/adapters/plugin-bridge.js +0 -89
  213. package/dist/mcp/auto-discovery.d.ts +0 -62
  214. package/dist/mcp/auto-discovery.js +0 -149
  215. package/dist/mcp/client.d.ts +0 -68
  216. package/dist/mcp/client.js +0 -248
  217. package/dist/mcp/config.d.ts +0 -31
  218. package/dist/mcp/config.js +0 -99
  219. package/dist/mcp/context-manager.d.ts +0 -171
  220. package/dist/mcp/context-manager.js +0 -362
  221. package/dist/mcp/contracts/mcp-contract.d.ts +0 -169
  222. package/dist/mcp/contracts/mcp-contract.js +0 -58
  223. package/dist/mcp/core/plugin-manager.d.ts +0 -46
  224. package/dist/mcp/core/plugin-manager.js +0 -110
  225. package/dist/mcp/demo/plugin-demo.d.ts +0 -20
  226. package/dist/mcp/demo/plugin-demo.js +0 -118
  227. package/dist/mcp/dynamic-chain-executor.d.ts +0 -225
  228. package/dist/mcp/dynamic-chain-executor.js +0 -489
  229. package/dist/mcp/dynamic-orchestrator.d.ts +0 -115
  230. package/dist/mcp/dynamic-orchestrator.js +0 -351
  231. package/dist/mcp/ecosystem.d.ts +0 -75
  232. package/dist/mcp/ecosystem.js +0 -162
  233. package/dist/mcp/error-manager.d.ts +0 -254
  234. package/dist/mcp/error-manager.js +0 -501
  235. package/dist/mcp/error-recovery.d.ts +0 -159
  236. package/dist/mcp/error-recovery.js +0 -405
  237. package/dist/mcp/external-client.d.ts +0 -88
  238. package/dist/mcp/external-client.js +0 -331
  239. package/dist/mcp/external-manager.d.ts +0 -112
  240. package/dist/mcp/external-manager.js +0 -308
  241. package/dist/mcp/function-calling.d.ts +0 -65
  242. package/dist/mcp/function-calling.js +0 -642
  243. package/dist/mcp/health-monitor.d.ts +0 -257
  244. package/dist/mcp/health-monitor.js +0 -630
  245. package/dist/mcp/initialize-tools.d.ts +0 -29
  246. package/dist/mcp/initialize-tools.js +0 -262
  247. package/dist/mcp/initialize.d.ts +0 -18
  248. package/dist/mcp/initialize.js +0 -62
  249. package/dist/mcp/logging.d.ts +0 -38
  250. package/dist/mcp/logging.js +0 -100
  251. package/dist/mcp/manager.d.ts +0 -68
  252. package/dist/mcp/manager.js +0 -176
  253. package/dist/mcp/neurolink-mcp-client.d.ts +0 -97
  254. package/dist/mcp/neurolink-mcp-client.js +0 -462
  255. package/dist/mcp/orchestrator.d.ts +0 -302
  256. package/dist/mcp/orchestrator.js +0 -703
  257. package/dist/mcp/plugin-manager.d.ts +0 -98
  258. package/dist/mcp/plugin-manager.js +0 -297
  259. package/dist/mcp/plugins/core/filesystem-mcp.d.ts +0 -36
  260. package/dist/mcp/plugins/core/filesystem-mcp.js +0 -142
  261. package/dist/mcp/plugins/core/neurolink-mcp.json +0 -17
  262. package/dist/mcp/plugins/filesystem-mcp.d.ts +0 -37
  263. package/dist/mcp/plugins/filesystem-mcp.js +0 -54
  264. package/dist/mcp/security-manager.d.ts +0 -87
  265. package/dist/mcp/security-manager.js +0 -344
  266. package/dist/mcp/semaphore-manager.d.ts +0 -137
  267. package/dist/mcp/semaphore-manager.js +0 -329
  268. package/dist/mcp/session-manager.d.ts +0 -187
  269. package/dist/mcp/session-manager.js +0 -400
  270. package/dist/mcp/session-persistence.d.ts +0 -93
  271. package/dist/mcp/session-persistence.js +0 -302
  272. package/dist/mcp/tool-integration.d.ts +0 -58
  273. package/dist/mcp/tool-integration.js +0 -203
  274. package/dist/mcp/transport-manager.d.ts +0 -154
  275. package/dist/mcp/transport-manager.js +0 -335
  276. package/dist/mcp/unified-mcp.d.ts +0 -133
  277. package/dist/mcp/unified-mcp.js +0 -251
  278. package/dist/mcp/unified-registry.d.ts +0 -165
  279. package/dist/mcp/unified-registry.js +0 -539
  280. package/dist/providers/analytics-helper.d.ts +0 -38
  281. package/dist/providers/analytics-helper.js +0 -216
  282. package/dist/providers/function-calling-provider.d.ts +0 -142
  283. package/dist/providers/function-calling-provider.js +0 -630
  284. package/dist/providers/mcp-provider.d.ts +0 -75
  285. package/dist/providers/mcp-provider.js +0 -283
  286. package/dist/providers/timeout-wrapper.d.ts +0 -40
  287. package/dist/providers/timeout-wrapper.js +0 -100
  288. package/dist/sdk/tool-extension.d.ts +0 -181
  289. package/dist/sdk/tool-extension.js +0 -284
  290. package/dist/services/streaming/streaming-manager.d.ts +0 -29
  291. package/dist/services/streaming/streaming-manager.js +0 -245
  292. package/dist/services/types.d.ts +0 -156
  293. package/dist/services/types.js +0 -2
  294. package/dist/services/websocket/websocket-server.d.ts +0 -34
  295. package/dist/services/websocket/websocket-server.js +0 -306
  296. package/dist/utils/provider-validation.d.ts +0 -36
  297. package/dist/utils/provider-validation.js +0 -625
  298. package/dist/utils/providerUtils-fixed.d.ts +0 -8
  299. package/dist/utils/providerUtils-fixed.js +0 -94
  300. package/dist/utils/streaming-utils.d.ts +0 -79
  301. package/dist/utils/streaming-utils.js +0 -198
  302. package/dist/utils/timeout-manager.d.ts +0 -75
  303. package/dist/utils/timeout-manager.js +0 -244
@@ -1,94 +0,0 @@
1
- import { AIProviderFactory } from "../core/factory.js";
2
- import { logger } from "./logger.js";
3
- import { hasProviderEnvVars } from "./providerUtils.js";
4
- /**
5
- * Asynchronously get the best available provider based on real-time checks.
6
- * This function performs actual authentication and availability tests.
7
- *
8
- * @param requestedProvider - Optional preferred provider name
9
- * @returns The best provider name to use
10
- */
11
- export async function getBestProvider(requestedProvider) {
12
- // 🔧 FIX: Check for explicit default provider in env
13
- if (process.env.DEFAULT_PROVIDER &&
14
- (await isProviderAvailable(process.env.DEFAULT_PROVIDER))) {
15
- logger.debug(`[getBestProvider] Using DEFAULT_PROVIDER: ${process.env.DEFAULT_PROVIDER}`);
16
- return process.env.DEFAULT_PROVIDER;
17
- }
18
- // 🔧 FIX: Special case for Ollama when explicitly configured
19
- if (process.env.OLLAMA_BASE_URL && process.env.OLLAMA_MODEL) {
20
- // Quick connectivity check for Ollama
21
- try {
22
- if (await isProviderAvailable("ollama")) {
23
- logger.debug(`[getBestProvider] Prioritizing working local Ollama`);
24
- return "ollama"; // Prioritize working local AI
25
- }
26
- }
27
- catch {
28
- // Fall through to cloud providers
29
- }
30
- }
31
- const providers = [
32
- "google-ai",
33
- "anthropic",
34
- "openai",
35
- "mistral",
36
- "vertex",
37
- "azure",
38
- "huggingface",
39
- "bedrock",
40
- "ollama", // Keep as fallback
41
- ];
42
- if (requestedProvider && requestedProvider !== "auto") {
43
- if (await isProviderAvailable(requestedProvider)) {
44
- logger.debug(`[getBestProvider] Using requested provider: ${requestedProvider}`);
45
- return requestedProvider;
46
- }
47
- else {
48
- logger.warn(`[getBestProvider] Requested provider '${requestedProvider}' is not available. Falling back to auto-selection.`);
49
- }
50
- }
51
- for (const provider of providers) {
52
- if (await isProviderAvailable(provider)) {
53
- logger.debug(`[getBestProvider] Selected provider: ${provider}`);
54
- return provider;
55
- }
56
- }
57
- throw new Error("No available AI providers. Please check your configurations.");
58
- }
59
- /**
60
- * Check if a provider is truly available by performing a quick authentication test.
61
- *
62
- * @param providerName - The name of the provider to check.
63
- * @returns True if the provider is available and authenticated.
64
- */
65
- async function isProviderAvailable(providerName) {
66
- if (!hasProviderEnvVars(providerName) && providerName !== "ollama") {
67
- return false;
68
- }
69
- if (providerName === "ollama") {
70
- try {
71
- const response = await fetch("http://localhost:11434/api/tags", {
72
- method: "GET",
73
- signal: AbortSignal.timeout(2000),
74
- });
75
- if (response.ok) {
76
- const { models } = await response.json();
77
- const defaultOllamaModel = "llama3.2:latest";
78
- return models.some((m) => m.name === defaultOllamaModel);
79
- }
80
- return false;
81
- }
82
- catch (error) {
83
- return false;
84
- }
85
- }
86
- try {
87
- const provider = await AIProviderFactory.createProvider(providerName);
88
- await provider.generate({ prompt: "test", maxTokens: 1 });
89
- return true;
90
- }
91
- catch (error) {
92
- return false;
93
- }
94
- }
@@ -1,79 +0,0 @@
1
- /**
2
- * Phase 2: Enhanced Streaming Infrastructure
3
- * Streaming utilities for progress tracking and metadata enhancement
4
- */
5
- import type { StreamingProgressData, StreamingMetadata, ProgressCallback } from "../core/types.js";
6
- export interface UIProgressHandler {
7
- onProgress: (progress: StreamingProgressData) => void;
8
- onComplete: (metadata: StreamingMetadata) => void;
9
- onError: (error: Error) => void;
10
- }
11
- export interface StreamingStats {
12
- totalChunks: number;
13
- totalBytes: number;
14
- duration: number;
15
- averageChunkSize: number;
16
- provider: string;
17
- model: string;
18
- }
19
- /**
20
- * Enhanced streaming utilities for progress tracking and metadata
21
- */
22
- export interface StreamingConfigOptions {
23
- enableProgressTracking?: boolean;
24
- progressCallback?: ProgressCallback;
25
- includeStreamingMetadata?: boolean;
26
- streamingBufferSize?: number;
27
- enableStreamingHeaders?: boolean;
28
- }
29
- /**
30
- * Legacy interface for backward compatibility
31
- */
32
- export interface EnhancedStreamTextOptions extends StreamingConfigOptions {
33
- }
34
- export declare class StreamingEnhancer {
35
- /**
36
- * Add progress tracking to a readable stream
37
- */
38
- static addProgressTracking(stream: ReadableStream, callback?: ProgressCallback, options?: {
39
- streamId?: string;
40
- bufferSize?: number;
41
- }): ReadableStream;
42
- /**
43
- * Add metadata headers to streaming response
44
- */
45
- static addMetadataHeaders(response: Response, stats: StreamingStats): Response;
46
- /**
47
- * Create progress callback for UI integration
48
- */
49
- static createProgressCallback(ui: UIProgressHandler): ProgressCallback;
50
- /**
51
- * Estimate remaining time based on current progress
52
- */
53
- static estimateRemainingTime(totalBytes: number, elapsedTime: number, chunkCount: number): number | undefined;
54
- /**
55
- * Create enhanced streaming configuration
56
- */
57
- static createStreamingConfig(options: StreamingConfigOptions | EnhancedStreamTextOptions): {
58
- progressTracking: boolean;
59
- callback?: ProgressCallback;
60
- metadata: boolean;
61
- bufferSize: number;
62
- headers: boolean;
63
- };
64
- }
65
- /**
66
- * Streaming performance monitor for debugging and optimization
67
- */
68
- export declare class StreamingMonitor {
69
- private static activeStreams;
70
- static registerStream(streamId: string): void;
71
- static updateStream(streamId: string, progress: StreamingProgressData): void;
72
- static completeStream(streamId: string): void;
73
- static getActiveStreams(): StreamingProgressData[];
74
- static getStreamStats(): {
75
- activeCount: number;
76
- totalBytesActive: number;
77
- averageProgress: number;
78
- };
79
- }
@@ -1,198 +0,0 @@
1
- /**
2
- * Phase 2: Enhanced Streaming Infrastructure
3
- * Streaming utilities for progress tracking and metadata enhancement
4
- */
5
- export class StreamingEnhancer {
6
- /**
7
- * Add progress tracking to a readable stream
8
- */
9
- static addProgressTracking(stream, callback, options) {
10
- const streamId = options?.streamId || `stream_${Date.now()}`;
11
- const startTime = Date.now();
12
- let chunkCount = 0;
13
- let totalBytes = 0;
14
- let lastProgressTime = startTime;
15
- return new ReadableStream({
16
- start(controller) {
17
- if (callback) {
18
- callback({
19
- chunkCount: 0,
20
- totalBytes: 0,
21
- chunkSize: 0,
22
- elapsedTime: 0,
23
- streamId,
24
- phase: "initializing",
25
- });
26
- }
27
- },
28
- async pull(controller) {
29
- const reader = stream.getReader();
30
- try {
31
- const { done, value } = await reader.read();
32
- if (done) {
33
- controller.close();
34
- if (callback) {
35
- const elapsedTime = Date.now() - startTime;
36
- callback({
37
- chunkCount,
38
- totalBytes,
39
- chunkSize: totalBytes > 0 ? Math.round(totalBytes / chunkCount) : 0,
40
- elapsedTime,
41
- streamId,
42
- phase: "complete",
43
- });
44
- }
45
- return;
46
- }
47
- // Track progress
48
- chunkCount++;
49
- const chunkSize = value
50
- ? new TextEncoder().encode(value.toString()).length
51
- : 0;
52
- totalBytes += chunkSize;
53
- const currentTime = Date.now();
54
- const elapsedTime = currentTime - startTime;
55
- const timeSinceLastProgress = currentTime - lastProgressTime;
56
- // Call progress callback
57
- if (callback && (timeSinceLastProgress > 100 || chunkCount === 1)) {
58
- // Throttle to max 10 calls/second
59
- const estimatedRemaining = StreamingEnhancer.estimateRemainingTime(totalBytes, elapsedTime, chunkCount);
60
- callback({
61
- chunkCount,
62
- totalBytes,
63
- chunkSize,
64
- elapsedTime,
65
- estimatedRemaining,
66
- streamId,
67
- phase: "streaming",
68
- });
69
- lastProgressTime = currentTime;
70
- }
71
- controller.enqueue(value);
72
- }
73
- catch (error) {
74
- controller.error(error);
75
- if (callback) {
76
- callback({
77
- chunkCount,
78
- totalBytes,
79
- chunkSize: 0,
80
- elapsedTime: Date.now() - startTime,
81
- streamId,
82
- phase: "error",
83
- });
84
- }
85
- }
86
- finally {
87
- reader.releaseLock();
88
- }
89
- },
90
- });
91
- }
92
- /**
93
- * Add metadata headers to streaming response
94
- */
95
- static addMetadataHeaders(response, stats) {
96
- const headers = new Headers(response.headers);
97
- headers.set("X-Streaming-Chunks", stats.totalChunks.toString());
98
- headers.set("X-Streaming-Bytes", stats.totalBytes.toString());
99
- headers.set("X-Streaming-Duration", stats.duration.toString());
100
- headers.set("X-Streaming-Avg-Chunk-Size", stats.averageChunkSize.toString());
101
- headers.set("X-Streaming-Provider", stats.provider);
102
- headers.set("X-Streaming-Model", stats.model);
103
- headers.set("X-Streaming-Throughput", Math.round(stats.totalBytes / (stats.duration / 1000)).toString());
104
- return new Response(response.body, {
105
- status: response.status,
106
- statusText: response.statusText,
107
- headers,
108
- });
109
- }
110
- /**
111
- * Create progress callback for UI integration
112
- */
113
- static createProgressCallback(ui) {
114
- return (progress) => {
115
- try {
116
- ui.onProgress(progress);
117
- if (progress.phase === "complete") {
118
- ui.onComplete({
119
- startTime: Date.now() - progress.elapsedTime,
120
- endTime: Date.now(),
121
- totalDuration: progress.elapsedTime,
122
- averageChunkSize: Math.round(progress.totalBytes / progress.chunkCount),
123
- maxChunkSize: progress.chunkSize, // This would need to be tracked better in real implementation
124
- minChunkSize: progress.chunkSize, // This would need to be tracked better in real implementation
125
- throughputBytesPerSecond: Math.round(progress.totalBytes / (progress.elapsedTime / 1000)),
126
- streamingProvider: "unknown", // Would be passed from provider
127
- modelUsed: "unknown", // Would be passed from provider
128
- });
129
- }
130
- }
131
- catch (error) {
132
- ui.onError(error);
133
- }
134
- };
135
- }
136
- /**
137
- * Estimate remaining time based on current progress
138
- */
139
- static estimateRemainingTime(totalBytes, elapsedTime, chunkCount) {
140
- if (elapsedTime < 1000 || chunkCount < 3) {
141
- return undefined; // Not enough data for estimation
142
- }
143
- const bytesPerMs = totalBytes / elapsedTime;
144
- const avgChunkSize = totalBytes / chunkCount;
145
- // Rough estimation assuming similar chunk sizes going forward
146
- // This is a simple heuristic - real implementation might be more sophisticated
147
- const estimatedTotalBytes = avgChunkSize * (chunkCount + 10); // Assume 10 more chunks
148
- const remainingBytes = estimatedTotalBytes - totalBytes;
149
- return Math.max(0, remainingBytes / bytesPerMs);
150
- }
151
- /**
152
- * Create enhanced streaming configuration
153
- */
154
- static createStreamingConfig(options) {
155
- return {
156
- progressTracking: options.enableProgressTracking ?? false,
157
- callback: options.progressCallback,
158
- metadata: options.includeStreamingMetadata ?? false,
159
- bufferSize: options.streamingBufferSize ?? 8192,
160
- headers: options.enableStreamingHeaders ?? false,
161
- };
162
- }
163
- }
164
- /**
165
- * Streaming performance monitor for debugging and optimization
166
- */
167
- export class StreamingMonitor {
168
- static activeStreams = new Map();
169
- static registerStream(streamId) {
170
- this.activeStreams.set(streamId, {
171
- chunkCount: 0,
172
- totalBytes: 0,
173
- chunkSize: 0,
174
- elapsedTime: 0,
175
- streamId,
176
- phase: "initializing",
177
- });
178
- }
179
- static updateStream(streamId, progress) {
180
- this.activeStreams.set(streamId, progress);
181
- }
182
- static completeStream(streamId) {
183
- this.activeStreams.delete(streamId);
184
- }
185
- static getActiveStreams() {
186
- return Array.from(this.activeStreams.values());
187
- }
188
- static getStreamStats() {
189
- const streams = this.getActiveStreams();
190
- return {
191
- activeCount: streams.length,
192
- totalBytesActive: streams.reduce((sum, s) => sum + s.totalBytes, 0),
193
- averageProgress: streams.length > 0
194
- ? streams.reduce((sum, s) => sum + s.elapsedTime, 0) / streams.length
195
- : 0,
196
- };
197
- }
198
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * Centralized Timeout Manager for NeuroLink
3
- *
4
- * Provides consistent timeout handling across all operations with proper cleanup,
5
- * abort controller integration, and graceful degradation.
6
- */
7
- export interface TimeoutConfig {
8
- operation: string;
9
- timeout?: number | string;
10
- gracefulShutdown?: boolean;
11
- retryOnTimeout?: boolean;
12
- maxRetries?: number;
13
- abortSignal?: AbortSignal;
14
- }
15
- export interface TimeoutResult<T> {
16
- success: boolean;
17
- data?: T;
18
- error?: Error;
19
- timedOut: boolean;
20
- executionTime: number;
21
- retriesUsed: number;
22
- }
23
- /**
24
- * Enhanced timeout manager with proper cleanup and abort controller integration
25
- */
26
- export declare class TimeoutManager {
27
- private activeTimeouts;
28
- /**
29
- * Execute operation with timeout and proper cleanup
30
- */
31
- executeWithTimeout<T>(operation: () => Promise<T>, config: TimeoutConfig): Promise<TimeoutResult<T>>;
32
- /**
33
- * Execute single operation with timeout
34
- */
35
- private performSingleOperation;
36
- /**
37
- * Execute operation with abort signal support
38
- */
39
- private executeWithAbortSignal;
40
- /**
41
- * Get timeout in milliseconds from config
42
- */
43
- private getTimeoutMs;
44
- /**
45
- * Generate unique operation ID
46
- */
47
- private generateOperationId;
48
- /**
49
- * Cleanup specific operation
50
- */
51
- cleanup(operationId: string): void;
52
- /**
53
- * Cleanup all active timeouts (call on shutdown)
54
- */
55
- cleanupAll(): void;
56
- /**
57
- * Get current active timeout count (for debugging)
58
- */
59
- getActiveTimeoutCount(): number;
60
- /**
61
- * Create a timeout wrapper for child process operations
62
- */
63
- wrapChildProcess<T>(processFactory: () => Promise<T>, config: TimeoutConfig): Promise<TimeoutResult<T>>;
64
- /**
65
- * Create a timeout wrapper for MCP server operations
66
- */
67
- wrapMCPOperation<T>(operation: () => Promise<T>, operationName: string, timeoutMs?: number): Promise<TimeoutResult<T>>;
68
- /**
69
- * Create a timeout wrapper for CLI operations
70
- */
71
- wrapCLIOperation<T>(operation: () => Promise<T>, operationName: string, timeoutMs?: number): Promise<TimeoutResult<T>>;
72
- }
73
- export declare function createTimeoutManager(): TimeoutManager;
74
- export declare function getDefaultTimeoutManager(): TimeoutManager;
75
- export declare const defaultTimeoutManager: TimeoutManager;
@@ -1,244 +0,0 @@
1
- /**
2
- * Centralized Timeout Manager for NeuroLink
3
- *
4
- * Provides consistent timeout handling across all operations with proper cleanup,
5
- * abort controller integration, and graceful degradation.
6
- */
7
- import { parseTimeout, TimeoutError, DEFAULT_TIMEOUTS } from "./timeout.js";
8
- /**
9
- * Enhanced timeout manager with proper cleanup and abort controller integration
10
- */
11
- export class TimeoutManager {
12
- activeTimeouts = new Map();
13
- /**
14
- * Execute operation with timeout and proper cleanup
15
- */
16
- async executeWithTimeout(operation, config) {
17
- const startTime = Date.now();
18
- const operationId = this.generateOperationId(config.operation);
19
- let retriesUsed = 0;
20
- const maxRetries = config.retryOnTimeout ? (config.maxRetries ?? 1) : 0;
21
- while (retriesUsed <= maxRetries) {
22
- try {
23
- const result = await this.performSingleOperation(operation, config, operationId);
24
- return {
25
- success: true,
26
- data: result,
27
- timedOut: false,
28
- executionTime: Date.now() - startTime,
29
- retriesUsed,
30
- };
31
- }
32
- catch (error) {
33
- // Clean up any active timeouts for this operation
34
- this.cleanup(operationId);
35
- if (error instanceof TimeoutError && retriesUsed < maxRetries) {
36
- retriesUsed++;
37
- continue;
38
- }
39
- return {
40
- success: false,
41
- error: error instanceof Error ? error : new Error(String(error)),
42
- timedOut: error instanceof TimeoutError,
43
- executionTime: Date.now() - startTime,
44
- retriesUsed,
45
- };
46
- }
47
- }
48
- // This should never be reached, but TypeScript needs it
49
- return {
50
- success: false,
51
- error: new Error("Maximum retries exceeded"),
52
- timedOut: true,
53
- executionTime: Date.now() - startTime,
54
- retriesUsed,
55
- };
56
- }
57
- /**
58
- * Execute single operation with timeout
59
- */
60
- async performSingleOperation(operation, config, operationId) {
61
- const timeoutMs = this.getTimeoutMs(config);
62
- if (!timeoutMs) {
63
- // No timeout specified, execute directly
64
- return await operation();
65
- }
66
- // Create abort controller for this operation
67
- const controller = new AbortController();
68
- const existingSignal = config.abortSignal;
69
- // Merge with existing abort signal if provided
70
- if (existingSignal) {
71
- existingSignal.addEventListener("abort", () => {
72
- controller.abort(existingSignal.reason);
73
- });
74
- if (existingSignal.aborted) {
75
- throw new Error("Operation aborted before execution");
76
- }
77
- }
78
- // Set up timeout
79
- const timer = setTimeout(() => {
80
- controller.abort(new TimeoutError(`Operation '${config.operation}' timed out after ${timeoutMs}ms`, timeoutMs, "timeout-manager", "generate"));
81
- }, timeoutMs);
82
- // Cleanup function
83
- const cleanup = () => {
84
- clearTimeout(timer);
85
- this.activeTimeouts.delete(operationId);
86
- };
87
- // Store active timeout for potential cleanup
88
- this.activeTimeouts.set(operationId, {
89
- timer,
90
- controller,
91
- cleanup,
92
- });
93
- try {
94
- // Execute operation with abort signal
95
- const result = await this.executeWithAbortSignal(operation, controller.signal);
96
- cleanup();
97
- return result;
98
- }
99
- catch (error) {
100
- cleanup();
101
- // Convert abort errors to timeout errors if appropriate
102
- if (error instanceof Error && error.name === "AbortError") {
103
- throw new TimeoutError(`Operation '${config.operation}' was aborted`, timeoutMs, "timeout-manager", "generate");
104
- }
105
- throw error;
106
- }
107
- }
108
- /**
109
- * Execute operation with abort signal support
110
- */
111
- async executeWithAbortSignal(operation, signal) {
112
- // Check if already aborted
113
- if (signal.aborted) {
114
- throw new Error("Operation aborted");
115
- }
116
- // Race between operation and abort signal
117
- return new Promise((resolve, reject) => {
118
- // Listen for abort
119
- signal.addEventListener("abort", () => {
120
- reject(signal.reason || new Error("Operation aborted"));
121
- });
122
- // Execute operation
123
- operation().then(resolve).catch(reject);
124
- });
125
- }
126
- /**
127
- * Get timeout in milliseconds from config
128
- */
129
- getTimeoutMs(config) {
130
- if (config.timeout !== undefined) {
131
- return parseTimeout(config.timeout);
132
- }
133
- // Use default timeout based on operation type
134
- const operation = config.operation.toLowerCase();
135
- // MCP operations
136
- if (operation.includes("mcp") || operation.includes("server")) {
137
- return parseTimeout(DEFAULT_TIMEOUTS.tools.network);
138
- }
139
- // File operations
140
- if (operation.includes("file") ||
141
- operation.includes("read") ||
142
- operation.includes("write")) {
143
- return parseTimeout(DEFAULT_TIMEOUTS.tools.filesystem);
144
- }
145
- // Network operations
146
- if (operation.includes("network") ||
147
- operation.includes("http") ||
148
- operation.includes("fetch")) {
149
- return parseTimeout(DEFAULT_TIMEOUTS.tools.network);
150
- }
151
- // Default
152
- return parseTimeout(DEFAULT_TIMEOUTS.tools.default);
153
- }
154
- /**
155
- * Generate unique operation ID
156
- */
157
- generateOperationId(operation) {
158
- return `${operation}-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
159
- }
160
- /**
161
- * Cleanup specific operation
162
- */
163
- cleanup(operationId) {
164
- const timeout = this.activeTimeouts.get(operationId);
165
- if (timeout) {
166
- timeout.cleanup();
167
- }
168
- }
169
- /**
170
- * Cleanup all active timeouts (call on shutdown)
171
- */
172
- cleanupAll() {
173
- for (const [id, timeout] of this.activeTimeouts) {
174
- timeout.cleanup();
175
- }
176
- this.activeTimeouts.clear();
177
- }
178
- /**
179
- * Get current active timeout count (for debugging)
180
- */
181
- getActiveTimeoutCount() {
182
- return this.activeTimeouts.size;
183
- }
184
- /**
185
- * Create a timeout wrapper for child process operations
186
- */
187
- wrapChildProcess(processFactory, config) {
188
- return this.executeWithTimeout(processFactory, {
189
- ...config,
190
- gracefulShutdown: true,
191
- timeout: config.timeout || DEFAULT_TIMEOUTS.tools.network,
192
- });
193
- }
194
- /**
195
- * Create a timeout wrapper for MCP server operations
196
- */
197
- wrapMCPOperation(operation, operationName, timeoutMs) {
198
- return this.executeWithTimeout(operation, {
199
- operation: `mcp-${operationName}`,
200
- timeout: timeoutMs || parseTimeout(DEFAULT_TIMEOUTS.tools.network),
201
- retryOnTimeout: false,
202
- gracefulShutdown: true,
203
- });
204
- }
205
- /**
206
- * Create a timeout wrapper for CLI operations
207
- */
208
- wrapCLIOperation(operation, operationName, timeoutMs) {
209
- return this.executeWithTimeout(operation, {
210
- operation: `cli-${operationName}`,
211
- timeout: timeoutMs || 120000, // 2 minutes default for CLI
212
- retryOnTimeout: false,
213
- gracefulShutdown: true,
214
- });
215
- }
216
- }
217
- // Factory function to create a new TimeoutManager instance
218
- export function createTimeoutManager() {
219
- return new TimeoutManager();
220
- }
221
- // Lazy-loaded default timeout manager instance
222
- let _defaultTimeoutManager = null;
223
- export function getDefaultTimeoutManager() {
224
- if (!_defaultTimeoutManager) {
225
- _defaultTimeoutManager = createTimeoutManager();
226
- }
227
- return _defaultTimeoutManager;
228
- }
229
- // Export default instance for backwards compatibility
230
- export const defaultTimeoutManager = getDefaultTimeoutManager();
231
- // Cleanup on process exit
232
- if (typeof process !== "undefined") {
233
- process.once("exit", () => {
234
- getDefaultTimeoutManager().cleanupAll();
235
- });
236
- process.once("SIGINT", () => {
237
- getDefaultTimeoutManager().cleanupAll();
238
- process.exit(0);
239
- });
240
- process.once("SIGTERM", () => {
241
- getDefaultTimeoutManager().cleanupAll();
242
- process.exit(0);
243
- });
244
- }