@juspay/neurolink 9.32.0 → 9.32.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 (467) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/auth/anthropicOAuth.js +1 -1
  3. package/dist/cli/commands/proxy.js +18 -5
  4. package/dist/client/aiSdkAdapter.js +1 -1
  5. package/dist/client/index.js +137 -501
  6. package/dist/core/factory.js +0 -1
  7. package/dist/core/redisConversationMemoryManager.js +1 -1
  8. package/dist/features/ppt/slideGenerator.js +0 -1
  9. package/dist/features/ppt/utils.js +0 -1
  10. package/dist/lib/server/routes/claudeProxyRoutes.js +45 -9
  11. package/dist/mcp/elicitationProtocol.js +1 -1
  12. package/dist/mcp/servers/agent/directToolsServer.js +0 -1
  13. package/dist/providers/azureOpenai.js +1 -1
  14. package/dist/providers/huggingFace.js +0 -1
  15. package/dist/providers/openaiCompatible.js +0 -1
  16. package/dist/sdk/toolRegistration.js +0 -1
  17. package/dist/server/openapi/generator.js +1 -1
  18. package/dist/server/routes/claudeProxyRoutes.js +45 -9
  19. package/dist/types/configTypes.js +0 -5
  20. package/dist/types/modelTypes.js +0 -1
  21. package/dist/types/tools.js +0 -1
  22. package/dist/types/typeAliases.js +0 -1
  23. package/dist/types/utilities.js +1 -1
  24. package/dist/types/workflowTypes.js +0 -1
  25. package/dist/utils/providerRetry.js +0 -1
  26. package/dist/utils/providerUtils.js +0 -1
  27. package/package.json +2 -2
  28. package/dist/client/adapters/providerImageAdapter.js +0 -588
  29. package/dist/client/adapters/tts/googleTTSHandler.js +0 -344
  30. package/dist/client/adapters/video/directorPipeline.js +0 -516
  31. package/dist/client/adapters/video/ffmpegAdapter.js +0 -206
  32. package/dist/client/adapters/video/frameExtractor.js +0 -143
  33. package/dist/client/adapters/video/vertexVideoHandler.js +0 -763
  34. package/dist/client/adapters/video/videoAnalyzer.js +0 -238
  35. package/dist/client/adapters/video/videoMerger.js +0 -171
  36. package/dist/client/agent/directTools.js +0 -840
  37. package/dist/client/auth/AuthProviderFactory.js +0 -111
  38. package/dist/client/auth/AuthProviderRegistry.js +0 -190
  39. package/dist/client/auth/RequestContext.js +0 -78
  40. package/dist/client/auth/accountPool.js +0 -178
  41. package/dist/client/auth/anthropicOAuth.js +0 -974
  42. package/dist/client/auth/authContext.js +0 -314
  43. package/dist/client/auth/errors.js +0 -39
  44. package/dist/client/auth/index.js +0 -61
  45. package/dist/client/auth/middleware/AuthMiddleware.js +0 -519
  46. package/dist/client/auth/middleware/rateLimitByUser.js +0 -554
  47. package/dist/client/auth/providers/BaseAuthProvider.js +0 -723
  48. package/dist/client/auth/providers/CognitoProvider.js +0 -304
  49. package/dist/client/auth/providers/KeycloakProvider.js +0 -393
  50. package/dist/client/auth/providers/auth0.js +0 -274
  51. package/dist/client/auth/providers/betterAuth.js +0 -182
  52. package/dist/client/auth/providers/clerk.js +0 -317
  53. package/dist/client/auth/providers/custom.js +0 -112
  54. package/dist/client/auth/providers/firebase.js +0 -226
  55. package/dist/client/auth/providers/jwt.js +0 -212
  56. package/dist/client/auth/providers/oauth2.js +0 -303
  57. package/dist/client/auth/providers/supabase.js +0 -259
  58. package/dist/client/auth/providers/workos.js +0 -284
  59. package/dist/client/auth/serverBridge.js +0 -25
  60. package/dist/client/auth/sessionManager.js +0 -437
  61. package/dist/client/auth/tokenStore.js +0 -799
  62. package/dist/client/client/aiSdkAdapter.js +0 -487
  63. package/dist/client/client/auth.js +0 -473
  64. package/dist/client/client/errors.js +0 -552
  65. package/dist/client/client/httpClient.js +0 -837
  66. package/dist/client/client/index.js +0 -172
  67. package/dist/client/client/interceptors.js +0 -601
  68. package/dist/client/client/sseClient.js +0 -545
  69. package/dist/client/client/streamingClient.js +0 -917
  70. package/dist/client/client/wsClient.js +0 -369
  71. package/dist/client/config/configManager.js +0 -303
  72. package/dist/client/config/conversationMemory.js +0 -86
  73. package/dist/client/config/taskClassificationConfig.js +0 -148
  74. package/dist/client/constants/contextWindows.js +0 -295
  75. package/dist/client/constants/enums.js +0 -853
  76. package/dist/client/constants/index.js +0 -207
  77. package/dist/client/constants/performance.js +0 -389
  78. package/dist/client/constants/retry.js +0 -266
  79. package/dist/client/constants/timeouts.js +0 -182
  80. package/dist/client/constants/tokens.js +0 -380
  81. package/dist/client/constants/videoErrors.js +0 -46
  82. package/dist/client/context/budgetChecker.js +0 -98
  83. package/dist/client/context/contextCompactor.js +0 -205
  84. package/dist/client/context/emergencyTruncation.js +0 -88
  85. package/dist/client/context/errorDetection.js +0 -171
  86. package/dist/client/context/errors.js +0 -21
  87. package/dist/client/context/fileTokenBudget.js +0 -127
  88. package/dist/client/context/prompts/summarizationPrompt.js +0 -117
  89. package/dist/client/context/stages/fileReadDeduplicator.js +0 -66
  90. package/dist/client/context/stages/slidingWindowTruncator.js +0 -190
  91. package/dist/client/context/stages/structuredSummarizer.js +0 -99
  92. package/dist/client/context/stages/toolOutputPruner.js +0 -52
  93. package/dist/client/context/summarizationEngine.js +0 -136
  94. package/dist/client/context/toolOutputLimits.js +0 -78
  95. package/dist/client/context/toolPairRepair.js +0 -66
  96. package/dist/client/core/analytics.js +0 -88
  97. package/dist/client/core/baseProvider.js +0 -1385
  98. package/dist/client/core/constants.js +0 -140
  99. package/dist/client/core/conversationMemoryFactory.js +0 -141
  100. package/dist/client/core/conversationMemoryInitializer.js +0 -128
  101. package/dist/client/core/conversationMemoryManager.js +0 -344
  102. package/dist/client/core/dynamicModels.js +0 -358
  103. package/dist/client/core/evaluation.js +0 -309
  104. package/dist/client/core/evaluationProviders.js +0 -248
  105. package/dist/client/core/factory.js +0 -412
  106. package/dist/client/core/infrastructure/baseError.js +0 -22
  107. package/dist/client/core/infrastructure/baseFactory.js +0 -54
  108. package/dist/client/core/infrastructure/baseRegistry.js +0 -53
  109. package/dist/client/core/infrastructure/index.js +0 -5
  110. package/dist/client/core/infrastructure/retry.js +0 -20
  111. package/dist/client/core/infrastructure/typedEventEmitter.js +0 -23
  112. package/dist/client/core/modelConfiguration.js +0 -851
  113. package/dist/client/core/modules/GenerationHandler.js +0 -588
  114. package/dist/client/core/modules/MessageBuilder.js +0 -273
  115. package/dist/client/core/modules/StreamHandler.js +0 -185
  116. package/dist/client/core/modules/TelemetryHandler.js +0 -203
  117. package/dist/client/core/modules/ToolsManager.js +0 -499
  118. package/dist/client/core/modules/Utilities.js +0 -331
  119. package/dist/client/core/redisConversationMemoryManager.js +0 -1435
  120. package/dist/client/core/streamAnalytics.js +0 -131
  121. package/dist/client/evaluation/contextBuilder.js +0 -134
  122. package/dist/client/evaluation/index.js +0 -61
  123. package/dist/client/evaluation/prompts.js +0 -73
  124. package/dist/client/evaluation/ragasEvaluator.js +0 -110
  125. package/dist/client/evaluation/retryManager.js +0 -78
  126. package/dist/client/evaluation/scoring.js +0 -61
  127. package/dist/client/factories/providerFactory.js +0 -166
  128. package/dist/client/factories/providerRegistry.js +0 -166
  129. package/dist/client/features/ppt/constants.js +0 -896
  130. package/dist/client/features/ppt/contentPlanner.js +0 -529
  131. package/dist/client/features/ppt/presentationOrchestrator.js +0 -236
  132. package/dist/client/features/ppt/slideGenerator.js +0 -532
  133. package/dist/client/features/ppt/slideRenderers.js +0 -2383
  134. package/dist/client/features/ppt/slideTypeInference.js +0 -405
  135. package/dist/client/features/ppt/types.js +0 -13
  136. package/dist/client/features/ppt/utils.js +0 -443
  137. package/dist/client/files/fileReferenceRegistry.js +0 -1543
  138. package/dist/client/files/fileTools.js +0 -450
  139. package/dist/client/files/streamingReader.js +0 -321
  140. package/dist/client/files/types.js +0 -23
  141. package/dist/client/hitl/hitlErrors.js +0 -54
  142. package/dist/client/hitl/hitlManager.js +0 -460
  143. package/dist/client/mcp/agentExposure.js +0 -356
  144. package/dist/client/mcp/auth/index.js +0 -11
  145. package/dist/client/mcp/auth/oauthClientProvider.js +0 -325
  146. package/dist/client/mcp/auth/tokenStorage.js +0 -134
  147. package/dist/client/mcp/batching/index.js +0 -10
  148. package/dist/client/mcp/batching/requestBatcher.js +0 -441
  149. package/dist/client/mcp/caching/index.js +0 -10
  150. package/dist/client/mcp/caching/toolCache.js +0 -433
  151. package/dist/client/mcp/elicitation/elicitationManager.js +0 -376
  152. package/dist/client/mcp/elicitation/index.js +0 -11
  153. package/dist/client/mcp/elicitation/types.js +0 -10
  154. package/dist/client/mcp/elicitationProtocol.js +0 -375
  155. package/dist/client/mcp/enhancedToolDiscovery.js +0 -481
  156. package/dist/client/mcp/externalServerManager.js +0 -1478
  157. package/dist/client/mcp/factory.js +0 -161
  158. package/dist/client/mcp/flexibleToolValidator.js +0 -161
  159. package/dist/client/mcp/httpRateLimiter.js +0 -391
  160. package/dist/client/mcp/httpRetryHandler.js +0 -178
  161. package/dist/client/mcp/index.js +0 -74
  162. package/dist/client/mcp/mcpCircuitBreaker.js +0 -427
  163. package/dist/client/mcp/mcpClientFactory.js +0 -708
  164. package/dist/client/mcp/mcpRegistryClient.js +0 -488
  165. package/dist/client/mcp/mcpServerBase.js +0 -373
  166. package/dist/client/mcp/multiServerManager.js +0 -579
  167. package/dist/client/mcp/registry.js +0 -158
  168. package/dist/client/mcp/routing/index.js +0 -10
  169. package/dist/client/mcp/routing/toolRouter.js +0 -416
  170. package/dist/client/mcp/serverCapabilities.js +0 -502
  171. package/dist/client/mcp/servers/agent/directToolsServer.js +0 -150
  172. package/dist/client/mcp/toolAnnotations.js +0 -239
  173. package/dist/client/mcp/toolConverter.js +0 -258
  174. package/dist/client/mcp/toolDiscoveryService.js +0 -798
  175. package/dist/client/mcp/toolIntegration.js +0 -334
  176. package/dist/client/mcp/toolRegistry.js +0 -729
  177. package/dist/client/memory/hippocampusInitializer.js +0 -19
  178. package/dist/client/memory/memoryRetrievalTools.js +0 -166
  179. package/dist/client/middleware/builtin/analytics.js +0 -132
  180. package/dist/client/middleware/builtin/autoEvaluation.js +0 -203
  181. package/dist/client/middleware/builtin/guardrails.js +0 -109
  182. package/dist/client/middleware/builtin/lifecycle.js +0 -168
  183. package/dist/client/middleware/factory.js +0 -327
  184. package/dist/client/middleware/registry.js +0 -295
  185. package/dist/client/middleware/utils/guardrailsUtils.js +0 -396
  186. package/dist/client/models/anthropicModels.js +0 -527
  187. package/dist/client/neurolink.js +0 -8233
  188. package/dist/client/observability/exporterRegistry.js +0 -413
  189. package/dist/client/observability/exporters/arizeExporter.js +0 -138
  190. package/dist/client/observability/exporters/baseExporter.js +0 -190
  191. package/dist/client/observability/exporters/braintrustExporter.js +0 -154
  192. package/dist/client/observability/exporters/datadogExporter.js +0 -196
  193. package/dist/client/observability/exporters/laminarExporter.js +0 -302
  194. package/dist/client/observability/exporters/langfuseExporter.js +0 -209
  195. package/dist/client/observability/exporters/langsmithExporter.js +0 -143
  196. package/dist/client/observability/exporters/otelExporter.js +0 -164
  197. package/dist/client/observability/exporters/posthogExporter.js +0 -287
  198. package/dist/client/observability/exporters/sentryExporter.js +0 -165
  199. package/dist/client/observability/index.js +0 -31
  200. package/dist/client/observability/metricsAggregator.js +0 -556
  201. package/dist/client/observability/otelBridge.js +0 -131
  202. package/dist/client/observability/retryPolicy.js +0 -383
  203. package/dist/client/observability/sampling/samplers.js +0 -216
  204. package/dist/client/observability/spanProcessor.js +0 -303
  205. package/dist/client/observability/tokenTracker.js +0 -413
  206. package/dist/client/observability/types/exporterTypes.js +0 -5
  207. package/dist/client/observability/types/index.js +0 -4
  208. package/dist/client/observability/types/spanTypes.js +0 -92
  209. package/dist/client/observability/utils/safeMetadata.js +0 -25
  210. package/dist/client/observability/utils/spanSerializer.js +0 -292
  211. package/dist/client/processors/archive/ArchiveProcessor.js +0 -1308
  212. package/dist/client/processors/base/BaseFileProcessor.js +0 -614
  213. package/dist/client/processors/base/types.js +0 -82
  214. package/dist/client/processors/config/fileTypes.js +0 -520
  215. package/dist/client/processors/config/index.js +0 -92
  216. package/dist/client/processors/config/languageMap.js +0 -410
  217. package/dist/client/processors/config/mimeTypes.js +0 -363
  218. package/dist/client/processors/config/sizeLimits.js +0 -258
  219. package/dist/client/processors/document/ExcelProcessor.js +0 -590
  220. package/dist/client/processors/document/OpenDocumentProcessor.js +0 -212
  221. package/dist/client/processors/document/PptxProcessor.js +0 -157
  222. package/dist/client/processors/document/RtfProcessor.js +0 -361
  223. package/dist/client/processors/document/WordProcessor.js +0 -353
  224. package/dist/client/processors/errors/FileErrorCode.js +0 -255
  225. package/dist/client/processors/errors/errorHelpers.js +0 -386
  226. package/dist/client/processors/errors/errorSerializer.js +0 -507
  227. package/dist/client/processors/errors/index.js +0 -49
  228. package/dist/client/processors/markup/SvgProcessor.js +0 -240
  229. package/dist/client/processors/media/AudioProcessor.js +0 -707
  230. package/dist/client/processors/media/VideoProcessor.js +0 -1045
  231. package/dist/client/providers/amazonBedrock.js +0 -1512
  232. package/dist/client/providers/amazonSagemaker.js +0 -162
  233. package/dist/client/providers/anthropic.js +0 -831
  234. package/dist/client/providers/azureOpenai.js +0 -143
  235. package/dist/client/providers/googleAiStudio.js +0 -1200
  236. package/dist/client/providers/googleNativeGemini3.js +0 -543
  237. package/dist/client/providers/googleVertex.js +0 -2936
  238. package/dist/client/providers/huggingFace.js +0 -315
  239. package/dist/client/providers/litellm.js +0 -488
  240. package/dist/client/providers/mistral.js +0 -157
  241. package/dist/client/providers/ollama.js +0 -1579
  242. package/dist/client/providers/openAI.js +0 -627
  243. package/dist/client/providers/openRouter.js +0 -543
  244. package/dist/client/providers/openaiCompatible.js +0 -290
  245. package/dist/client/providers/providerTypeUtils.js +0 -46
  246. package/dist/client/providers/sagemaker/adaptive-semaphore.js +0 -215
  247. package/dist/client/providers/sagemaker/client.js +0 -472
  248. package/dist/client/providers/sagemaker/config.js +0 -317
  249. package/dist/client/providers/sagemaker/detection.js +0 -606
  250. package/dist/client/providers/sagemaker/error-constants.js +0 -227
  251. package/dist/client/providers/sagemaker/errors.js +0 -299
  252. package/dist/client/providers/sagemaker/language-model.js +0 -775
  253. package/dist/client/providers/sagemaker/parsers.js +0 -634
  254. package/dist/client/providers/sagemaker/streaming.js +0 -331
  255. package/dist/client/providers/sagemaker/structured-parser.js +0 -625
  256. package/dist/client/proxy/accountQuota.js +0 -162
  257. package/dist/client/proxy/claudeFormat.js +0 -595
  258. package/dist/client/proxy/modelRouter.js +0 -29
  259. package/dist/client/proxy/oauthFetch.js +0 -367
  260. package/dist/client/proxy/proxyFetch.js +0 -586
  261. package/dist/client/proxy/requestLogger.js +0 -207
  262. package/dist/client/proxy/tokenRefresh.js +0 -124
  263. package/dist/client/proxy/usageStats.js +0 -74
  264. package/dist/client/proxy/utils/noProxyUtils.js +0 -149
  265. package/dist/client/rag/ChunkerFactory.js +0 -320
  266. package/dist/client/rag/ChunkerRegistry.js +0 -421
  267. package/dist/client/rag/chunkers/BaseChunker.js +0 -143
  268. package/dist/client/rag/chunkers/CharacterChunker.js +0 -28
  269. package/dist/client/rag/chunkers/HTMLChunker.js +0 -38
  270. package/dist/client/rag/chunkers/JSONChunker.js +0 -68
  271. package/dist/client/rag/chunkers/LaTeXChunker.js +0 -63
  272. package/dist/client/rag/chunkers/MarkdownChunker.js +0 -306
  273. package/dist/client/rag/chunkers/RecursiveChunker.js +0 -139
  274. package/dist/client/rag/chunkers/SemanticMarkdownChunker.js +0 -138
  275. package/dist/client/rag/chunkers/SentenceChunker.js +0 -66
  276. package/dist/client/rag/chunkers/TokenChunker.js +0 -61
  277. package/dist/client/rag/chunkers/index.js +0 -15
  278. package/dist/client/rag/chunking/characterChunker.js +0 -142
  279. package/dist/client/rag/chunking/chunkerRegistry.js +0 -194
  280. package/dist/client/rag/chunking/htmlChunker.js +0 -247
  281. package/dist/client/rag/chunking/index.js +0 -17
  282. package/dist/client/rag/chunking/jsonChunker.js +0 -281
  283. package/dist/client/rag/chunking/latexChunker.js +0 -251
  284. package/dist/client/rag/chunking/markdownChunker.js +0 -373
  285. package/dist/client/rag/chunking/recursiveChunker.js +0 -148
  286. package/dist/client/rag/chunking/semanticChunker.js +0 -306
  287. package/dist/client/rag/chunking/sentenceChunker.js +0 -230
  288. package/dist/client/rag/chunking/tokenChunker.js +0 -183
  289. package/dist/client/rag/document/MDocument.js +0 -392
  290. package/dist/client/rag/document/index.js +0 -5
  291. package/dist/client/rag/document/loaders.js +0 -500
  292. package/dist/client/rag/errors/RAGError.js +0 -274
  293. package/dist/client/rag/errors/index.js +0 -6
  294. package/dist/client/rag/graphRag/graphRAG.js +0 -401
  295. package/dist/client/rag/graphRag/index.js +0 -4
  296. package/dist/client/rag/index.js +0 -141
  297. package/dist/client/rag/metadata/MetadataExtractorFactory.js +0 -418
  298. package/dist/client/rag/metadata/MetadataExtractorRegistry.js +0 -362
  299. package/dist/client/rag/metadata/index.js +0 -9
  300. package/dist/client/rag/metadata/metadataExtractor.js +0 -280
  301. package/dist/client/rag/pipeline/RAGPipeline.js +0 -436
  302. package/dist/client/rag/pipeline/contextAssembly.js +0 -341
  303. package/dist/client/rag/pipeline/index.js +0 -5
  304. package/dist/client/rag/ragIntegration.js +0 -321
  305. package/dist/client/rag/reranker/RerankerFactory.js +0 -430
  306. package/dist/client/rag/reranker/RerankerRegistry.js +0 -402
  307. package/dist/client/rag/reranker/index.js +0 -9
  308. package/dist/client/rag/reranker/reranker.js +0 -277
  309. package/dist/client/rag/resilience/CircuitBreaker.js +0 -431
  310. package/dist/client/rag/resilience/RetryHandler.js +0 -304
  311. package/dist/client/rag/resilience/index.js +0 -7
  312. package/dist/client/rag/retrieval/hybridSearch.js +0 -335
  313. package/dist/client/rag/retrieval/index.js +0 -5
  314. package/dist/client/rag/retrieval/vectorQueryTool.js +0 -307
  315. package/dist/client/rag/types.js +0 -8
  316. package/dist/client/sdk/toolRegistration.js +0 -377
  317. package/dist/client/server/abstract/baseServerAdapter.js +0 -575
  318. package/dist/client/server/adapters/expressAdapter.js +0 -486
  319. package/dist/client/server/adapters/fastifyAdapter.js +0 -472
  320. package/dist/client/server/adapters/honoAdapter.js +0 -632
  321. package/dist/client/server/adapters/koaAdapter.js +0 -510
  322. package/dist/client/server/errors.js +0 -486
  323. package/dist/client/server/factory/serverAdapterFactory.js +0 -160
  324. package/dist/client/server/index.js +0 -108
  325. package/dist/client/server/middleware/abortSignal.js +0 -111
  326. package/dist/client/server/middleware/auth.js +0 -388
  327. package/dist/client/server/middleware/cache.js +0 -359
  328. package/dist/client/server/middleware/common.js +0 -281
  329. package/dist/client/server/middleware/deprecation.js +0 -190
  330. package/dist/client/server/middleware/mcpBodyAttachment.js +0 -63
  331. package/dist/client/server/middleware/rateLimit.js +0 -227
  332. package/dist/client/server/middleware/validation.js +0 -388
  333. package/dist/client/server/openapi/generator.js +0 -398
  334. package/dist/client/server/openapi/index.js +0 -36
  335. package/dist/client/server/openapi/schemas.js +0 -695
  336. package/dist/client/server/openapi/templates.js +0 -374
  337. package/dist/client/server/routes/agentRoutes.js +0 -189
  338. package/dist/client/server/routes/claudeProxyRoutes.js +0 -1600
  339. package/dist/client/server/routes/healthRoutes.js +0 -187
  340. package/dist/client/server/routes/index.js +0 -57
  341. package/dist/client/server/routes/mcpRoutes.js +0 -342
  342. package/dist/client/server/routes/memoryRoutes.js +0 -350
  343. package/dist/client/server/routes/openApiRoutes.js +0 -126
  344. package/dist/client/server/routes/toolRoutes.js +0 -199
  345. package/dist/client/server/streaming/dataStream.js +0 -486
  346. package/dist/client/server/streaming/index.js +0 -11
  347. package/dist/client/server/types.js +0 -67
  348. package/dist/client/server/utils/redaction.js +0 -334
  349. package/dist/client/server/utils/validation.js +0 -243
  350. package/dist/client/server/websocket/WebSocketHandler.js +0 -383
  351. package/dist/client/server/websocket/index.js +0 -4
  352. package/dist/client/services/server/ai/observability/instrumentation.js +0 -808
  353. package/dist/client/telemetry/attributes.js +0 -100
  354. package/dist/client/telemetry/index.js +0 -26
  355. package/dist/client/telemetry/telemetryService.js +0 -308
  356. package/dist/client/telemetry/tracers.js +0 -17
  357. package/dist/client/telemetry/withSpan.js +0 -34
  358. package/dist/client/types/actionTypes.js +0 -6
  359. package/dist/client/types/analytics.js +0 -5
  360. package/dist/client/types/authTypes.js +0 -9
  361. package/dist/client/types/circuitBreakerErrors.js +0 -34
  362. package/dist/client/types/cli.js +0 -21
  363. package/dist/client/types/clientTypes.js +0 -10
  364. package/dist/client/types/common.js +0 -51
  365. package/dist/client/types/configTypes.js +0 -49
  366. package/dist/client/types/content.js +0 -19
  367. package/dist/client/types/contextTypes.js +0 -400
  368. package/dist/client/types/conversation.js +0 -47
  369. package/dist/client/types/conversationMemoryInterface.js +0 -6
  370. package/dist/client/types/domainTypes.js +0 -5
  371. package/dist/client/types/errors.js +0 -167
  372. package/dist/client/types/evaluation.js +0 -5
  373. package/dist/client/types/evaluationProviders.js +0 -5
  374. package/dist/client/types/evaluationTypes.js +0 -1
  375. package/dist/client/types/externalMcp.js +0 -6
  376. package/dist/client/types/fileReferenceTypes.js +0 -8
  377. package/dist/client/types/fileTypes.js +0 -4
  378. package/dist/client/types/generateTypes.js +0 -1
  379. package/dist/client/types/guardrails.js +0 -1
  380. package/dist/client/types/hitlTypes.js +0 -8
  381. package/dist/client/types/index.js +0 -57
  382. package/dist/client/types/mcpTypes.js +0 -5
  383. package/dist/client/types/middlewareTypes.js +0 -1
  384. package/dist/client/types/modelTypes.js +0 -30
  385. package/dist/client/types/multimodal.js +0 -135
  386. package/dist/client/types/observability.js +0 -6
  387. package/dist/client/types/pptTypes.js +0 -82
  388. package/dist/client/types/providers.js +0 -111
  389. package/dist/client/types/proxyTypes.js +0 -16
  390. package/dist/client/types/ragTypes.js +0 -7
  391. package/dist/client/types/sdkTypes.js +0 -8
  392. package/dist/client/types/serviceTypes.js +0 -5
  393. package/dist/client/types/streamTypes.js +0 -1
  394. package/dist/client/types/subscriptionTypes.js +0 -9
  395. package/dist/client/types/taskClassificationTypes.js +0 -5
  396. package/dist/client/types/tools.js +0 -24
  397. package/dist/client/types/ttsTypes.js +0 -57
  398. package/dist/client/types/typeAliases.js +0 -48
  399. package/dist/client/types/utilities.js +0 -4
  400. package/dist/client/types/workflowTypes.js +0 -30
  401. package/dist/client/utils/async/withTimeout.js +0 -98
  402. package/dist/client/utils/asyncMutex.js +0 -60
  403. package/dist/client/utils/conversationMemory.js +0 -431
  404. package/dist/client/utils/csvProcessor.js +0 -846
  405. package/dist/client/utils/errorHandling.js +0 -936
  406. package/dist/client/utils/evaluationUtils.js +0 -131
  407. package/dist/client/utils/factoryProcessing.js +0 -589
  408. package/dist/client/utils/fileDetector.js +0 -2161
  409. package/dist/client/utils/imageCache.js +0 -376
  410. package/dist/client/utils/imageProcessor.js +0 -704
  411. package/dist/client/utils/logger.js +0 -491
  412. package/dist/client/utils/mcpDefaults.js +0 -134
  413. package/dist/client/utils/messageBuilder.js +0 -1653
  414. package/dist/client/utils/modelAliasResolver.js +0 -54
  415. package/dist/client/utils/modelDetection.js +0 -80
  416. package/dist/client/utils/modelRouter.js +0 -292
  417. package/dist/client/utils/multimodalOptionsBuilder.js +0 -65
  418. package/dist/client/utils/observabilityHelpers.js +0 -47
  419. package/dist/client/utils/parameterValidation.js +0 -966
  420. package/dist/client/utils/pdfProcessor.js +0 -410
  421. package/dist/client/utils/performance.js +0 -222
  422. package/dist/client/utils/pricing.js +0 -340
  423. package/dist/client/utils/promptRedaction.js +0 -62
  424. package/dist/client/utils/providerConfig.js +0 -1009
  425. package/dist/client/utils/providerHealth.js +0 -1237
  426. package/dist/client/utils/providerRetry.js +0 -112
  427. package/dist/client/utils/providerUtils.js +0 -434
  428. package/dist/client/utils/rateLimiter.js +0 -200
  429. package/dist/client/utils/redis.js +0 -368
  430. package/dist/client/utils/retryHandler.js +0 -269
  431. package/dist/client/utils/retryability.js +0 -22
  432. package/dist/client/utils/sanitizers/svg.js +0 -481
  433. package/dist/client/utils/schemaConversion.js +0 -255
  434. package/dist/client/utils/taskClassificationUtils.js +0 -149
  435. package/dist/client/utils/taskClassifier.js +0 -94
  436. package/dist/client/utils/thinkingConfig.js +0 -104
  437. package/dist/client/utils/timeout.js +0 -359
  438. package/dist/client/utils/tokenEstimation.js +0 -142
  439. package/dist/client/utils/tokenLimits.js +0 -125
  440. package/dist/client/utils/tokenUtils.js +0 -239
  441. package/dist/client/utils/toolUtils.js +0 -75
  442. package/dist/client/utils/transformationUtils.js +0 -554
  443. package/dist/client/utils/ttsProcessor.js +0 -286
  444. package/dist/client/utils/typeUtils.js +0 -97
  445. package/dist/client/utils/videoAnalysisProcessor.js +0 -67
  446. package/dist/client/workflow/config.js +0 -398
  447. package/dist/client/workflow/core/ensembleExecutor.js +0 -407
  448. package/dist/client/workflow/core/judgeScorer.js +0 -544
  449. package/dist/client/workflow/core/responseConditioner.js +0 -225
  450. package/dist/client/workflow/core/types/conditionerTypes.js +0 -7
  451. package/dist/client/workflow/core/types/ensembleTypes.js +0 -7
  452. package/dist/client/workflow/core/types/index.js +0 -7
  453. package/dist/client/workflow/core/types/judgeTypes.js +0 -7
  454. package/dist/client/workflow/core/types/layerTypes.js +0 -7
  455. package/dist/client/workflow/core/types/registryTypes.js +0 -7
  456. package/dist/client/workflow/core/workflowRegistry.js +0 -304
  457. package/dist/client/workflow/core/workflowRunner.js +0 -586
  458. package/dist/client/workflow/index.js +0 -50
  459. package/dist/client/workflow/types.js +0 -9
  460. package/dist/client/workflow/utils/types/index.js +0 -7
  461. package/dist/client/workflow/utils/workflowMetrics.js +0 -311
  462. package/dist/client/workflow/utils/workflowValidation.js +0 -420
  463. package/dist/client/workflow/workflows/adaptiveWorkflow.js +0 -366
  464. package/dist/client/workflow/workflows/consensusWorkflow.js +0 -192
  465. package/dist/client/workflow/workflows/fallbackWorkflow.js +0 -225
  466. package/dist/client/workflow/workflows/multiJudgeWorkflow.js +0 -351
  467. /package/dist/client/{client/reactHooks.js → reactHooks.js} +0 -0
@@ -1,1237 +0,0 @@
1
- /**
2
- * Provider Health Checking System
3
- * Prevents 500 errors by validating provider availability and configuration
4
- */
5
- import { logger } from "./logger.js";
6
- import { AIProviderName, OpenAIModels, GoogleAIModels, AnthropicModels, BedrockModels, } from "../constants/enums.js";
7
- import { API_KEY_LENGTHS, PROJECT_ID_FORMAT } from "./providerConfig.js";
8
- import { basename } from "path";
9
- import { createProxyFetch } from "../proxy/proxyFetch.js";
10
- export class ProviderHealthChecker {
11
- static healthCache = new Map();
12
- static DEFAULT_TIMEOUT = 5000; // 5 seconds
13
- static DEFAULT_CACHE_AGE = 300000; // 5 minutes
14
- static CONSECUTIVE_FAILURE_THRESHOLD = ProviderHealthChecker.getValidatedFailureThreshold();
15
- static consecutiveFailures = new Map();
16
- /**
17
- * Validate and return a safe failure threshold value
18
- */
19
- static getValidatedFailureThreshold() {
20
- const envValue = process.env.PROVIDER_FAILURE_THRESHOLD;
21
- if (!envValue) {
22
- return 3; // default
23
- }
24
- const parsed = Number(envValue);
25
- if (isNaN(parsed) || parsed <= 0 || parsed > 10) {
26
- logger.warn(`Invalid PROVIDER_FAILURE_THRESHOLD: ${envValue} (must be between 1 and 10), using default: 3`);
27
- return 3;
28
- }
29
- return parsed;
30
- }
31
- /**
32
- * Comprehensive health check for a provider
33
- */
34
- static async checkProviderHealth(providerName, options = {}) {
35
- const { timeout = this.DEFAULT_TIMEOUT, includeConnectivityTest = false, includeModelValidation = false, cacheResults = true, maxCacheAge = this.DEFAULT_CACHE_AGE, } = options;
36
- // Check cache first
37
- if (cacheResults) {
38
- const cached = this.getCachedHealth(providerName, maxCacheAge);
39
- if (cached) {
40
- logger.debug(`Using cached health status for ${providerName}`);
41
- return cached;
42
- }
43
- }
44
- // Check if provider has consecutive failures (blacklisting)
45
- const failureCount = this.consecutiveFailures.get(providerName) || 0;
46
- if (failureCount >= this.CONSECUTIVE_FAILURE_THRESHOLD) {
47
- const healthStatus = {
48
- provider: providerName,
49
- isHealthy: false,
50
- isConfigured: false,
51
- hasApiKey: false,
52
- lastChecked: new Date(),
53
- error: `Provider blacklisted after ${failureCount} consecutive failures`,
54
- warning: "Provider will be retried after cache TTL expires",
55
- configurationIssues: [
56
- `Blacklisted due to ${failureCount} consecutive failures`,
57
- ],
58
- recommendations: ["Check provider status and configuration"],
59
- };
60
- logger.warn(`Provider ${providerName} blacklisted due to consecutive failures`, { failureCount });
61
- return healthStatus;
62
- }
63
- const startTime = Date.now();
64
- const healthStatus = {
65
- provider: providerName,
66
- isHealthy: false,
67
- isConfigured: false,
68
- hasApiKey: false,
69
- lastChecked: new Date(),
70
- configurationIssues: [],
71
- recommendations: [],
72
- };
73
- try {
74
- // 1. Check environment configuration
75
- await this.checkEnvironmentConfiguration(providerName, healthStatus);
76
- // 2. Check API key validity (basic format validation)
77
- await this.checkApiKeyValidity(providerName, healthStatus);
78
- // 3. Optional: Connectivity test
79
- if (includeConnectivityTest) {
80
- await this.checkConnectivity(providerName, healthStatus, timeout);
81
- }
82
- // 4. Optional: Model validation
83
- if (includeModelValidation) {
84
- await this.checkModelAvailability(providerName, healthStatus);
85
- }
86
- // 5. Determine overall health
87
- healthStatus.isHealthy =
88
- healthStatus.isConfigured &&
89
- healthStatus.hasApiKey &&
90
- healthStatus.configurationIssues.length === 0;
91
- healthStatus.responseTime = Date.now() - startTime;
92
- // Cache results
93
- if (cacheResults) {
94
- this.healthCache.set(providerName, {
95
- status: healthStatus,
96
- timestamp: Date.now(),
97
- });
98
- }
99
- // Reset failure count on success
100
- if (healthStatus.isHealthy) {
101
- this.consecutiveFailures.delete(providerName);
102
- }
103
- else {
104
- // Track consecutive failures
105
- const currentFailures = this.consecutiveFailures.get(providerName) || 0;
106
- this.consecutiveFailures.set(providerName, currentFailures + 1);
107
- }
108
- logger.debug(`Health check completed for ${providerName}`, {
109
- isHealthy: healthStatus.isHealthy,
110
- responseTime: healthStatus.responseTime,
111
- issues: healthStatus.configurationIssues.length,
112
- });
113
- }
114
- catch (error) {
115
- const errorMessage = error instanceof Error ? error.message : String(error);
116
- healthStatus.error = errorMessage;
117
- healthStatus.configurationIssues.push(`Health check failed: ${errorMessage}`);
118
- healthStatus.responseTime = Date.now() - startTime;
119
- // Track consecutive failures
120
- const currentFailures = this.consecutiveFailures.get(providerName) || 0;
121
- this.consecutiveFailures.set(providerName, currentFailures + 1);
122
- logger.warn(`Health check failed for ${providerName}`, {
123
- error: errorMessage,
124
- consecutiveFailures: currentFailures + 1,
125
- });
126
- }
127
- return healthStatus;
128
- }
129
- /**
130
- * Check environment configuration for a provider
131
- */
132
- static async checkEnvironmentConfiguration(providerName, healthStatus) {
133
- const requiredEnvVars = this.getRequiredEnvironmentVariables(providerName);
134
- logger.debug(`[ProviderHealthChecker] Checking environment configuration for ${providerName}`, {
135
- requiredEnvVars,
136
- presentEnvVars: requiredEnvVars.map((envVar) => ({
137
- name: envVar,
138
- present: !!process.env[envVar],
139
- hasValue: !!(process.env[envVar] && process.env[envVar].trim() !== ""),
140
- })),
141
- });
142
- let allConfigured = true;
143
- const missingVars = [];
144
- for (const envVar of requiredEnvVars) {
145
- const value = process.env[envVar];
146
- if (!value || value.trim() === "") {
147
- allConfigured = false;
148
- missingVars.push(envVar);
149
- }
150
- }
151
- healthStatus.isConfigured = allConfigured;
152
- logger.debug(`[ProviderHealthChecker] Environment configuration result for ${providerName}`, {
153
- isConfigured: allConfigured,
154
- missingVars,
155
- totalRequired: requiredEnvVars.length,
156
- totalMissing: missingVars.length,
157
- });
158
- if (!allConfigured) {
159
- healthStatus.configurationIssues.push(`Missing required environment variables: ${missingVars.join(", ")}`);
160
- healthStatus.recommendations.push(`Set the following environment variables: ${missingVars.join(", ")}`);
161
- }
162
- // Provider-specific configuration checks
163
- await this.checkProviderSpecificConfig(providerName, healthStatus);
164
- }
165
- /**
166
- * Check API key validity (format validation)
167
- */
168
- static async checkApiKeyValidity(providerName, healthStatus) {
169
- // 🎯 SPECIAL HANDLING FOR VERTEX AI: Check both auth methods
170
- if (providerName === AIProviderName.VERTEX) {
171
- logger.debug("Vertex AI authentication check starting", {
172
- providerName,
173
- });
174
- // Method 1: Check GOOGLE_APPLICATION_CREDENTIALS (file-based)
175
- const credentialsFile = process.env.GOOGLE_APPLICATION_CREDENTIALS;
176
- let fileBasedAuthValid = false;
177
- if (credentialsFile) {
178
- logger.debug("Checking GOOGLE_APPLICATION_CREDENTIALS file");
179
- try {
180
- const { promises: fs } = await import("fs");
181
- try {
182
- await fs.access(credentialsFile);
183
- fileBasedAuthValid = true;
184
- }
185
- catch {
186
- fileBasedAuthValid = false;
187
- }
188
- logger.debug("File auth check result", {
189
- fileExists: fileBasedAuthValid,
190
- });
191
- }
192
- catch (error) {
193
- logger.debug("File auth check error", {
194
- error: String(error),
195
- });
196
- fileBasedAuthValid = false;
197
- }
198
- }
199
- // Method 2: Check individual environment variables
200
- const hasIndividualAuth = !!(process.env.GOOGLE_AUTH_CLIENT_EMAIL &&
201
- process.env.GOOGLE_AUTH_PRIVATE_KEY);
202
- logger.debug("Individual auth check", {
203
- hasClientEmail: !!process.env.GOOGLE_AUTH_CLIENT_EMAIL,
204
- hasPrivateKey: !!process.env.GOOGLE_AUTH_PRIVATE_KEY,
205
- hasIndividualAuth,
206
- });
207
- // Vertex is valid if EITHER auth method works
208
- const hasValidAuth = fileBasedAuthValid || hasIndividualAuth;
209
- logger.debug("Vertex auth final result", {
210
- fileBasedAuthValid,
211
- hasIndividualAuth,
212
- hasValidAuth,
213
- });
214
- if (hasValidAuth) {
215
- healthStatus.hasApiKey = true;
216
- logger.debug("Vertex auth SUCCESS", {
217
- authMethod: fileBasedAuthValid ? "file-based" : "individual-env-vars",
218
- });
219
- }
220
- else {
221
- healthStatus.hasApiKey = false;
222
- healthStatus.configurationIssues.push(`Vertex AI authentication not found: neither GOOGLE_APPLICATION_CREDENTIALS file nor individual credentials (GOOGLE_AUTH_CLIENT_EMAIL + GOOGLE_AUTH_PRIVATE_KEY) are properly configured`);
223
- logger.debug("Vertex auth FAILED", {
224
- reason: "No valid auth method found",
225
- });
226
- }
227
- return;
228
- }
229
- // Providers that don't use API keys directly
230
- if (providerName === AIProviderName.OLLAMA ||
231
- providerName === AIProviderName.BEDROCK) {
232
- healthStatus.hasApiKey = true;
233
- return;
234
- }
235
- // 🔧 STANDARD HANDLING FOR OTHER PROVIDERS
236
- const apiKeyVar = this.getApiKeyEnvironmentVariable(providerName);
237
- const apiKey = process.env[apiKeyVar];
238
- if (!apiKey) {
239
- healthStatus.hasApiKey = false;
240
- healthStatus.configurationIssues.push(`API key not found in ${apiKeyVar}`);
241
- return;
242
- }
243
- // Basic format validation
244
- const isValidFormat = this.validateApiKeyFormat(providerName, apiKey);
245
- if (!isValidFormat) {
246
- healthStatus.hasApiKey = false;
247
- healthStatus.configurationIssues.push(`API key format appears invalid for ${providerName}`);
248
- healthStatus.recommendations.push(`Verify the API key format for ${providerName}`);
249
- }
250
- else {
251
- healthStatus.hasApiKey = true;
252
- }
253
- }
254
- /**
255
- * Check connectivity to provider endpoints
256
- */
257
- static async checkConnectivity(providerName, healthStatus, timeout) {
258
- const endpoint = this.getProviderHealthEndpoint(providerName);
259
- if (!endpoint) {
260
- healthStatus.warning = "No connectivity test available for this provider";
261
- return;
262
- }
263
- try {
264
- const controller = new AbortController();
265
- const timeoutId = setTimeout(() => controller.abort(), timeout);
266
- const proxyFetch = createProxyFetch();
267
- let response = await proxyFetch(endpoint, {
268
- method: "HEAD",
269
- signal: controller.signal,
270
- headers: {
271
- "User-Agent": "NeuroLink-HealthCheck/1.0",
272
- },
273
- });
274
- // Fallback to GET if HEAD returns 405 (Method Not Allowed) for restrictive gateways
275
- if (response.status === 405) {
276
- response = await proxyFetch(endpoint, {
277
- method: "GET",
278
- signal: controller.signal,
279
- headers: {
280
- "User-Agent": "NeuroLink-HealthCheck/1.0",
281
- },
282
- });
283
- }
284
- clearTimeout(timeoutId);
285
- if (!response.ok) {
286
- healthStatus.configurationIssues.push(`Connectivity test failed: HTTP ${response.status}`);
287
- }
288
- }
289
- catch (error) {
290
- const errorMessage = error instanceof Error ? error.message : String(error);
291
- // Provide specific error messages for common network issues
292
- if (errorMessage.includes("abort")) {
293
- healthStatus.configurationIssues.push(`Connectivity test timed out after ${timeout}ms`);
294
- }
295
- else if (errorMessage.includes("ENOTFOUND") ||
296
- errorMessage.includes("getaddrinfo")) {
297
- healthStatus.configurationIssues.push(`DNS resolution failed: Cannot resolve hostname for ${providerName}`);
298
- }
299
- else if (errorMessage.includes("ECONNREFUSED")) {
300
- healthStatus.configurationIssues.push(`Connection refused: ${providerName} service is not accepting connections`);
301
- }
302
- else if (errorMessage.includes("ETIMEDOUT")) {
303
- healthStatus.configurationIssues.push(`Connection timeout: ${providerName} service did not respond`);
304
- }
305
- else if (errorMessage.includes("certificate") ||
306
- errorMessage.includes("SSL") ||
307
- errorMessage.includes("TLS")) {
308
- healthStatus.configurationIssues.push(`SSL/TLS certificate error: ${providerName} has certificate issues`);
309
- }
310
- else if (errorMessage.includes("ECONNRESET")) {
311
- healthStatus.configurationIssues.push(`Connection reset: ${providerName} terminated the connection`);
312
- }
313
- else if (errorMessage.includes("network") ||
314
- errorMessage.includes("offline")) {
315
- healthStatus.configurationIssues.push(`Network error: Check internet connectivity and firewall settings`);
316
- }
317
- else {
318
- healthStatus.configurationIssues.push(`Connectivity test failed: ${errorMessage}`);
319
- }
320
- }
321
- }
322
- /**
323
- * Check model availability (if possible without making API calls)
324
- */
325
- static async checkModelAvailability(providerName, healthStatus) {
326
- // Basic model name validation and recommendations
327
- const commonModels = this.getCommonModelsForProvider(providerName);
328
- if (commonModels.length > 0) {
329
- if (providerName === AIProviderName.VERTEX) {
330
- // Provide detailed information about dual provider architecture
331
- healthStatus.recommendations.push(`Available models for ${providerName} (using dual provider architecture):\n` +
332
- ` Google Models (via vertex provider):\n` +
333
- ` • gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite\n` +
334
- ` • gemini-2.0-flash-001, gemini-1.5-pro, gemini-1.5-flash\n` +
335
- ` Anthropic Models (via vertexAnthropic provider):\n` +
336
- ` • claude-sonnet-4@20250514, claude-opus-4@20250514\n` +
337
- ` • claude-3-5-sonnet-20241022, claude-3-5-haiku-20241022\n` +
338
- ` • claude-3-sonnet-20240229, claude-3-haiku-20240307, claude-3-opus-20240229\n` +
339
- ` Implementation: Uses @ai-sdk/google-vertex with dual provider setup\n` +
340
- ` Authentication: Requires Google Cloud project with Vertex AI API enabled\n` +
341
- ` Note: Anthropic models require Anthropic integration in your Google Cloud project`);
342
- }
343
- else {
344
- healthStatus.recommendations.push(`Common models for ${providerName}: ${commonModels.slice(0, 3).join(", ")}`);
345
- }
346
- }
347
- }
348
- /**
349
- * Get required environment variables for a provider
350
- */
351
- static getRequiredEnvironmentVariables(providerName) {
352
- switch (providerName) {
353
- case AIProviderName.ANTHROPIC:
354
- return ["ANTHROPIC_API_KEY"];
355
- case AIProviderName.OPENAI:
356
- return ["OPENAI_API_KEY"];
357
- case AIProviderName.VERTEX:
358
- // Vertex AI requires authentication, but not via a single environment variable.
359
- // Authentication can be provided via a credential file or individual credentials + project.
360
- // The required authentication is checked in checkProviderSpecificConfig instead of here.
361
- // Returning an empty array here does NOT mean authentication is not required.
362
- return [];
363
- case AIProviderName.GOOGLE_AI:
364
- return ["GOOGLE_AI_API_KEY"];
365
- case AIProviderName.BEDROCK:
366
- // Bedrock credentials are resolved via AWS SDK default provider chain.
367
- // Region/auth validated in provider-specific checks.
368
- return [];
369
- case AIProviderName.AZURE:
370
- return ["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"];
371
- case AIProviderName.OLLAMA:
372
- return []; // Ollama typically doesn't require API keys
373
- default:
374
- return [];
375
- }
376
- }
377
- /**
378
- * Get API key environment variable for a provider
379
- */
380
- static getApiKeyEnvironmentVariable(providerName) {
381
- switch (providerName) {
382
- case AIProviderName.ANTHROPIC:
383
- return "ANTHROPIC_API_KEY";
384
- case AIProviderName.OPENAI:
385
- return "OPENAI_API_KEY";
386
- case AIProviderName.VERTEX:
387
- return "GOOGLE_APPLICATION_CREDENTIALS";
388
- case AIProviderName.GOOGLE_AI:
389
- return "GOOGLE_AI_API_KEY";
390
- case AIProviderName.BEDROCK:
391
- return "AWS_ACCESS_KEY_ID";
392
- case AIProviderName.AZURE:
393
- return "AZURE_OPENAI_API_KEY";
394
- case AIProviderName.OLLAMA:
395
- return "OLLAMA_API_BASE";
396
- default:
397
- return "";
398
- }
399
- }
400
- /**
401
- * Validate API key format for a provider
402
- */
403
- static validateApiKeyFormat(providerName, apiKey) {
404
- switch (providerName) {
405
- case AIProviderName.ANTHROPIC:
406
- return (apiKey.startsWith("sk-ant-") &&
407
- apiKey.length >= API_KEY_LENGTHS.ANTHROPIC_MIN);
408
- case AIProviderName.OPENAI:
409
- return (apiKey.startsWith("sk-") &&
410
- apiKey.length >= API_KEY_LENGTHS.OPENAI_MIN);
411
- case AIProviderName.GOOGLE_AI:
412
- return apiKey.length >= API_KEY_LENGTHS.GOOGLE_AI_EXACT; // Basic length check
413
- case AIProviderName.VERTEX:
414
- return apiKey.endsWith(".json") || apiKey.includes("type"); // JSON key format
415
- case AIProviderName.BEDROCK:
416
- return apiKey.length >= API_KEY_LENGTHS.AWS_ACCESS_KEY; // AWS access key length
417
- case AIProviderName.AZURE:
418
- return apiKey.length >= API_KEY_LENGTHS.AZURE_MIN; // Azure OpenAI API key length
419
- case AIProviderName.OLLAMA:
420
- return true; // Ollama usually doesn't require specific format
421
- default:
422
- return true; // Default to true for unknown providers
423
- }
424
- }
425
- /**
426
- * Get health check endpoint for connectivity testing
427
- */
428
- static getProviderHealthEndpoint(providerName) {
429
- switch (providerName) {
430
- case AIProviderName.ANTHROPIC:
431
- return null; // Anthropic doesn't have a public health endpoint
432
- case AIProviderName.OPENAI:
433
- return "https://api.openai.com/v1/models";
434
- case AIProviderName.GOOGLE_AI:
435
- return null; // No public health endpoint
436
- case AIProviderName.VERTEX:
437
- return null; // Complex authentication required
438
- case AIProviderName.BEDROCK:
439
- return null; // AWS endpoints vary by region
440
- case AIProviderName.OLLAMA:
441
- return "http://localhost:11434/api/version";
442
- default:
443
- return null;
444
- }
445
- }
446
- /**
447
- * Provider-specific configuration checks
448
- */
449
- static async checkProviderSpecificConfig(providerName, healthStatus) {
450
- switch (providerName) {
451
- case AIProviderName.VERTEX:
452
- await this.checkVertexAIConfig(healthStatus);
453
- break;
454
- case AIProviderName.BEDROCK:
455
- await this.checkBedrockConfig(healthStatus);
456
- break;
457
- case AIProviderName.AZURE:
458
- await this.checkAzureConfig(healthStatus);
459
- break;
460
- case AIProviderName.OLLAMA:
461
- await this.checkOllamaConfig(healthStatus);
462
- break;
463
- }
464
- }
465
- /**
466
- * Check Vertex AI configuration
467
- */
468
- static async checkVertexAIConfig(healthStatus) {
469
- logger.debug("Starting Vertex AI health check");
470
- const projectId = this.getVertexProjectId();
471
- if (!projectId) {
472
- healthStatus.configurationIssues.push("Google Cloud project ID not set");
473
- healthStatus.recommendations.push("Set one of: GOOGLE_VERTEX_PROJECT, GOOGLE_CLOUD_PROJECT_ID, GOOGLE_PROJECT_ID, or GOOGLE_CLOUD_PROJECT");
474
- }
475
- const hasValidAuth = await this.checkVertexAuthentication(healthStatus);
476
- if (projectId && hasValidAuth) {
477
- healthStatus.isConfigured = true;
478
- logger.debug("Vertex AI health check PASSED");
479
- }
480
- else {
481
- logger.debug("Vertex AI health check FAILED");
482
- }
483
- }
484
- /**
485
- * Get Vertex AI project ID from environment variables
486
- */
487
- static getVertexProjectId() {
488
- return (process.env.GOOGLE_PROJECT_ID ||
489
- process.env.GOOGLE_CLOUD_PROJECT_ID ||
490
- process.env.GOOGLE_VERTEX_PROJECT ||
491
- process.env.GOOGLE_CLOUD_PROJECT ||
492
- process.env.VERTEX_PROJECT_ID);
493
- }
494
- /**
495
- * Check Vertex AI authentication
496
- */
497
- static async checkVertexAuthentication(healthStatus) {
498
- let hasValidAuth = false;
499
- if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
500
- hasValidAuth = await this.checkGoogleApplicationCredentials(healthStatus);
501
- }
502
- if (!hasValidAuth) {
503
- hasValidAuth = this.checkIndividualGoogleCredentials(healthStatus);
504
- }
505
- if (!hasValidAuth) {
506
- healthStatus.configurationIssues.push("Google Cloud authentication not configured or credentials file missing");
507
- healthStatus.recommendations.push("Set either GOOGLE_APPLICATION_CREDENTIALS (valid file path), GOOGLE_SERVICE_ACCOUNT_KEY (base64), or both GOOGLE_AUTH_CLIENT_EMAIL and GOOGLE_AUTH_PRIVATE_KEY");
508
- }
509
- return hasValidAuth;
510
- }
511
- /**
512
- * Check Google Application Credentials file
513
- */
514
- static async checkGoogleApplicationCredentials(healthStatus) {
515
- const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
516
- if (!credentialsPath) {
517
- healthStatus.warning =
518
- "GOOGLE_APPLICATION_CREDENTIALS environment variable not set";
519
- return false;
520
- }
521
- try {
522
- const { promises: fs } = await import("fs");
523
- await fs.access(credentialsPath);
524
- const fileName = basename(credentialsPath);
525
- const jsonFilePattern = /\.json(\.\w+)?$/;
526
- if (!jsonFilePattern.test(fileName)) {
527
- healthStatus.warning =
528
- "GOOGLE_APPLICATION_CREDENTIALS should point to a JSON file";
529
- }
530
- healthStatus.hasApiKey = true;
531
- return true;
532
- }
533
- catch {
534
- healthStatus.warning = `GOOGLE_APPLICATION_CREDENTIALS file does not exist: ${credentialsPath}`;
535
- return false;
536
- }
537
- }
538
- /**
539
- * Check individual Google credentials
540
- */
541
- static checkIndividualGoogleCredentials(healthStatus) {
542
- const hasServiceAccountKey = !!process.env.GOOGLE_SERVICE_ACCOUNT_KEY;
543
- const hasIndividualCredentials = !!(process.env.GOOGLE_AUTH_CLIENT_EMAIL &&
544
- process.env.GOOGLE_AUTH_PRIVATE_KEY);
545
- if (hasServiceAccountKey || hasIndividualCredentials) {
546
- healthStatus.hasApiKey = true;
547
- return true;
548
- }
549
- return false;
550
- }
551
- /**
552
- * Check AWS Bedrock configuration
553
- */
554
- static async checkBedrockConfig(healthStatus) {
555
- logger.debug("Starting AWS Bedrock comprehensive health check");
556
- this.checkAWSRegion(healthStatus);
557
- this.checkAWSCredentials(healthStatus);
558
- this.checkBedrockModels(healthStatus);
559
- this.checkBedrockEndpoint(healthStatus);
560
- if (healthStatus.configurationIssues.length === 0) {
561
- healthStatus.hasApiKey = true;
562
- logger.debug("AWS Bedrock configuration appears valid");
563
- }
564
- }
565
- /**
566
- * Check AWS region configuration
567
- */
568
- static checkAWSRegion(healthStatus) {
569
- const awsRegion = process.env.AWS_REGION;
570
- const validBedrockRegions = [
571
- "us-east-1",
572
- "us-west-2",
573
- "ap-southeast-1",
574
- "ap-northeast-1",
575
- "eu-central-1",
576
- "eu-west-1",
577
- "ap-south-1",
578
- ];
579
- if (!awsRegion) {
580
- healthStatus.configurationIssues.push("AWS_REGION not set");
581
- healthStatus.recommendations.push(`Set AWS_REGION to a Bedrock-supported region: ${validBedrockRegions.join(", ")}`);
582
- }
583
- else if (!validBedrockRegions.includes(awsRegion)) {
584
- healthStatus.configurationIssues.push(`AWS_REGION '${awsRegion}' may not support all Bedrock models`);
585
- healthStatus.recommendations.push(`Consider using a primary Bedrock region: ${validBedrockRegions.slice(0, 3).join(", ")}`);
586
- }
587
- }
588
- /**
589
- * Check AWS credentials
590
- */
591
- static checkAWSCredentials(healthStatus) {
592
- const awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
593
- const awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
594
- const awsProfile = process.env.AWS_PROFILE;
595
- if (!awsAccessKeyId && !awsProfile) {
596
- healthStatus.configurationIssues.push("No AWS credentials found");
597
- healthStatus.recommendations.push("Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or configure AWS_PROFILE");
598
- }
599
- else if (awsAccessKeyId && !awsSecretAccessKey) {
600
- healthStatus.configurationIssues.push("AWS_ACCESS_KEY_ID set but AWS_SECRET_ACCESS_KEY missing");
601
- healthStatus.recommendations.push("Set AWS_SECRET_ACCESS_KEY to match your AWS_ACCESS_KEY_ID");
602
- }
603
- }
604
- /**
605
- * Check Bedrock models
606
- */
607
- static checkBedrockModels(healthStatus) {
608
- const bedrockModel = process.env.BEDROCK_MODEL || process.env.BEDROCK_MODEL_ID;
609
- const supportedModels = [
610
- BedrockModels.CLAUDE_3_SONNET,
611
- BedrockModels.CLAUDE_3_HAIKU,
612
- BedrockModels.CLAUDE_3_5_SONNET,
613
- "anthropic.claude-v2:1",
614
- "amazon.titan-text-express-v1",
615
- ];
616
- if (!bedrockModel) {
617
- healthStatus.recommendations.push(`Set BEDROCK_MODEL or BEDROCK_MODEL_ID for faster startup (e.g., ${BedrockModels.CLAUDE_3_SONNET})`);
618
- }
619
- else if (!supportedModels.includes(bedrockModel)) {
620
- healthStatus.recommendations.push(`Consider using a popular Bedrock model: ${supportedModels.slice(0, 3).join(", ")}`);
621
- }
622
- }
623
- /**
624
- * Check Bedrock endpoint
625
- */
626
- static checkBedrockEndpoint(healthStatus) {
627
- const bedrockEndpoint = process.env.BEDROCK_ENDPOINT_URL;
628
- if (bedrockEndpoint && !bedrockEndpoint.startsWith("https://")) {
629
- healthStatus.configurationIssues.push("BEDROCK_ENDPOINT_URL should use HTTPS");
630
- healthStatus.recommendations.push("Update BEDROCK_ENDPOINT_URL to use HTTPS protocol");
631
- }
632
- }
633
- /**
634
- * Check Azure OpenAI configuration
635
- */
636
- static async checkAzureConfig(healthStatus) {
637
- const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT;
638
- if (azureEndpoint && !azureEndpoint.startsWith("https://")) {
639
- healthStatus.configurationIssues.push("Invalid AZURE_OPENAI_ENDPOINT format");
640
- healthStatus.recommendations.push("Set AZURE_OPENAI_ENDPOINT to a valid URL (e.g., https://your-resource.openai.azure.com/)");
641
- }
642
- // Check for deployment name using the SAME logic as the Azure provider
643
- const deploymentName = process.env.AZURE_OPENAI_MODEL ||
644
- process.env.AZURE_OPENAI_DEPLOYMENT ||
645
- process.env.AZURE_OPENAI_DEPLOYMENT_ID;
646
- if (!deploymentName) {
647
- healthStatus.configurationIssues.push("No Azure deployment specified");
648
- healthStatus.recommendations.push("Set one of: AZURE_OPENAI_MODEL, AZURE_OPENAI_DEPLOYMENT, or AZURE_OPENAI_DEPLOYMENT_ID");
649
- }
650
- }
651
- /**
652
- * Check Ollama configuration
653
- */
654
- static async checkOllamaConfig(healthStatus) {
655
- const ollamaBase = process.env.OLLAMA_API_BASE || "http://localhost:11434";
656
- if (!ollamaBase.startsWith("http")) {
657
- healthStatus.configurationIssues.push("Invalid OLLAMA_API_BASE format");
658
- healthStatus.recommendations.push("Set OLLAMA_API_BASE to a valid URL (e.g., http://localhost:11434)");
659
- }
660
- }
661
- /**
662
- * Get common models for a provider
663
- */
664
- static getCommonModelsForProvider(providerName) {
665
- switch (providerName) {
666
- case AIProviderName.ANTHROPIC:
667
- return [
668
- AnthropicModels.CLAUDE_3_5_SONNET,
669
- AnthropicModels.CLAUDE_3_HAIKU,
670
- AnthropicModels.CLAUDE_3_OPUS,
671
- ];
672
- case AIProviderName.OPENAI:
673
- return [
674
- OpenAIModels.GPT_4O,
675
- OpenAIModels.GPT_4O_MINI,
676
- OpenAIModels.GPT_3_5_TURBO,
677
- ];
678
- case AIProviderName.GOOGLE_AI:
679
- return [
680
- GoogleAIModels.GEMINI_1_5_PRO,
681
- GoogleAIModels.GEMINI_1_5_FLASH,
682
- GoogleAIModels.GEMINI_2_5_PRO,
683
- ];
684
- case AIProviderName.VERTEX:
685
- return [
686
- // Google models (via vertex provider)
687
- GoogleAIModels.GEMINI_2_5_PRO,
688
- GoogleAIModels.GEMINI_2_5_FLASH,
689
- GoogleAIModels.GEMINI_2_5_FLASH_LITE,
690
- GoogleAIModels.GEMINI_2_0_FLASH_001,
691
- GoogleAIModels.GEMINI_1_5_PRO,
692
- GoogleAIModels.GEMINI_1_5_FLASH,
693
- // Anthropic models (via vertexAnthropic provider)
694
- "claude-sonnet-4@20250514",
695
- "claude-opus-4@20250514",
696
- AnthropicModels.CLAUDE_3_5_SONNET,
697
- AnthropicModels.CLAUDE_3_5_HAIKU,
698
- AnthropicModels.CLAUDE_3_SONNET,
699
- AnthropicModels.CLAUDE_3_HAIKU,
700
- AnthropicModels.CLAUDE_3_OPUS,
701
- ];
702
- case AIProviderName.BEDROCK:
703
- return [BedrockModels.CLAUDE_3_SONNET, BedrockModels.CLAUDE_3_HAIKU];
704
- case AIProviderName.AZURE:
705
- return [OpenAIModels.GPT_4O, OpenAIModels.GPT_4O_MINI, "gpt-35-turbo"];
706
- case AIProviderName.OLLAMA:
707
- return ["llama3.2:latest", "llama3.1:latest", "mistral:latest"];
708
- default:
709
- return [];
710
- }
711
- }
712
- /**
713
- * Get cached health status if still valid
714
- */
715
- static getCachedHealth(providerName, maxAge) {
716
- const cached = this.healthCache.get(providerName);
717
- if (!cached) {
718
- return null;
719
- }
720
- const age = Date.now() - cached.timestamp;
721
- if (age > maxAge) {
722
- this.healthCache.delete(providerName);
723
- return null;
724
- }
725
- return cached.status;
726
- }
727
- /**
728
- * Check if Vertex AI supports Anthropic models (dual provider architecture)
729
- */
730
- static async checkVertexAnthropicSupport() {
731
- const result = {
732
- isSupported: false,
733
- hasCreateVertexAnthropic: false,
734
- hasCorrectTypes: false,
735
- hasValidProject: false,
736
- hasRegionalSupport: false,
737
- hasNetworkAccess: false,
738
- hasAnthropicModels: false,
739
- authentication: {
740
- isValid: false,
741
- method: "none",
742
- issues: [],
743
- },
744
- projectConfiguration: {
745
- isValid: false,
746
- projectId: undefined,
747
- region: undefined,
748
- issues: [],
749
- },
750
- modelSupport: {
751
- availableModels: [],
752
- recommendedModels: [
753
- "claude-sonnet-4@20250514",
754
- "claude-opus-4@20250514",
755
- "claude-3-5-sonnet-20241022",
756
- "claude-3-5-haiku-20241022",
757
- "claude-3-sonnet-20240229",
758
- "claude-3-haiku-20240307",
759
- ],
760
- deprecatedModels: [
761
- "claude-3-opus-20240229", // Still available but newer versions preferred
762
- ],
763
- },
764
- recommendations: [],
765
- troubleshooting: [],
766
- };
767
- logger.debug("Starting comprehensive Vertex Anthropic support verification");
768
- try {
769
- // 1. Check SDK module availability
770
- logger.debug("Checking @ai-sdk/google-vertex/anthropic module availability");
771
- const anthropicModule = await import("@ai-sdk/google-vertex/anthropic");
772
- result.hasCreateVertexAnthropic =
773
- typeof anthropicModule.createVertexAnthropic === "function";
774
- result.hasCorrectTypes = true; // Types are bundled with the function
775
- if (!result.hasCreateVertexAnthropic) {
776
- result.troubleshooting.push("📦 Update @ai-sdk/google-vertex to latest version with Anthropic support", "🔄 Run: npm install @ai-sdk/google-vertex@latest", "📖 See: https://sdk.vercel.ai/providers/ai-sdk-providers/google-vertex#anthropic-models");
777
- return result;
778
- }
779
- logger.debug("SDK module verified successfully");
780
- // 2. Comprehensive Authentication Validation
781
- logger.debug("Starting authentication validation");
782
- result.authentication = await this.validateVertexAuthentication();
783
- if (!result.authentication.isValid) {
784
- result.troubleshooting.push("🔐 Fix authentication configuration:", " Option 1: Set GOOGLE_APPLICATION_CREDENTIALS to valid service account file", " Option 2: Set individual env vars: GOOGLE_AUTH_CLIENT_EMAIL, GOOGLE_AUTH_PRIVATE_KEY", "📖 See: https://cloud.google.com/docs/authentication/provide-credentials-adc");
785
- }
786
- // 3. Project Configuration Validation
787
- logger.debug("Starting project configuration validation");
788
- result.projectConfiguration =
789
- await this.validateVertexProjectConfiguration();
790
- result.hasValidProject = result.projectConfiguration.isValid;
791
- if (!result.hasValidProject) {
792
- result.troubleshooting.push("🏗️ Fix project configuration:", " Set GOOGLE_VERTEX_PROJECT or GOOGLE_CLOUD_PROJECT environment variable", " Ensure project exists and has Vertex AI API enabled", "📖 See: https://console.cloud.google.com/apis/library/aiplatform.googleapis.com");
793
- }
794
- // 4. Regional Support Validation
795
- logger.debug("Starting regional support validation");
796
- result.hasRegionalSupport = await this.checkVertexRegionalSupport(result.projectConfiguration.region);
797
- if (!result.hasRegionalSupport) {
798
- result.troubleshooting.push("🌍 Regional support issues:", " Anthropic models may not be available in your region", " Try regions: us-central1, us-east4, europe-west1, asia-southeast1", " Set GOOGLE_CLOUD_LOCATION environment variable");
799
- }
800
- // 5. Network Connectivity Check (non-blocking)
801
- logger.debug("Starting network connectivity check");
802
- result.hasNetworkAccess = await this.checkVertexNetworkConnectivity(result.projectConfiguration.region || "us-central1");
803
- if (!result.hasNetworkAccess) {
804
- result.troubleshooting.push("🌐 Network connectivity issues:", " Check proxy configuration if behind corporate firewall", " Verify DNS resolution for *.googleapis.com", " Ensure firewall allows HTTPS to Google Cloud endpoints");
805
- }
806
- // 6. Anthropic Model Integration Check
807
- logger.debug("Starting Anthropic model integration check");
808
- result.hasAnthropicModels = await this.checkAnthropicModelIntegration(result.projectConfiguration.projectId, result.projectConfiguration.region);
809
- if (!result.hasAnthropicModels) {
810
- result.troubleshooting.push("🤖 Anthropic model integration issues:", " Enable Anthropic integration in Google Cloud Console", " Navigate to: Vertex AI > Model Garden > Anthropic", " Accept terms and enable Claude model access", "📖 See: https://console.cloud.google.com/vertex-ai/publishers/anthropic");
811
- }
812
- // Calculate overall support status
813
- result.isSupported =
814
- result.hasCreateVertexAnthropic &&
815
- result.authentication.isValid &&
816
- result.hasValidProject &&
817
- result.hasRegionalSupport;
818
- // Note: Network and model integration are nice-to-have but not blocking
819
- // Generate comprehensive recommendations
820
- if (result.isSupported) {
821
- result.recommendations.push("✅ Vertex Anthropic support is fully configured", "✅ Claude models are available via vertexAnthropic provider", `✅ Authentication: ${result.authentication.method}`, `✅ Project: ${result.projectConfiguration.projectId}`, `✅ Region: ${result.projectConfiguration.region}`);
822
- if (result.hasNetworkAccess) {
823
- result.recommendations.push("✅ Network connectivity verified");
824
- }
825
- else {
826
- result.recommendations.push("⚠️ Network connectivity not verified (may still work)");
827
- }
828
- if (result.hasAnthropicModels) {
829
- result.recommendations.push("✅ Anthropic model integration verified");
830
- }
831
- else {
832
- result.recommendations.push("⚠️ Anthropic model integration not verified");
833
- }
834
- result.recommendations.push("", "🎯 Recommended Claude models:", ...result.modelSupport.recommendedModels.map((model) => ` • ${model}`), "", "📚 Usage example:", ' const vertex = new GoogleVertexProvider("claude-3-5-sonnet-20241022")', ' const result = await vertex.generate("Hello, Claude!")');
835
- logger.info("Vertex Anthropic support verification: FULLY_SUPPORTED");
836
- }
837
- else {
838
- const missingComponents = [];
839
- if (!result.hasCreateVertexAnthropic) {
840
- missingComponents.push("SDK module");
841
- }
842
- if (!result.authentication.isValid) {
843
- missingComponents.push("authentication");
844
- }
845
- if (!result.hasValidProject) {
846
- missingComponents.push("project configuration");
847
- }
848
- if (!result.hasRegionalSupport) {
849
- missingComponents.push("regional support");
850
- }
851
- result.recommendations.push(`⚠️ Vertex Anthropic support partially available`, `❌ Missing: ${missingComponents.join(", ")}`, "", "🔧 Quick fixes needed:");
852
- result.recommendations.push(...result.troubleshooting);
853
- logger.warn("Vertex Anthropic support verification: PARTIALLY_SUPPORTED", {
854
- missingComponents,
855
- hasBasicSupport: result.hasCreateVertexAnthropic,
856
- authenticationValid: result.authentication.isValid,
857
- projectValid: result.hasValidProject,
858
- });
859
- }
860
- }
861
- catch (error) {
862
- logger.error("Vertex Anthropic support check failed", {
863
- error: error instanceof Error ? error.message : String(error),
864
- stack: error instanceof Error ? error.stack : undefined,
865
- });
866
- result.recommendations.push("❌ Comprehensive Anthropic support check failed", `🐛 Error: ${error instanceof Error ? error.message : String(error)}`, "", "🔧 Troubleshooting steps:", "1. Update @ai-sdk/google-vertex to latest version", "2. Verify Google Cloud authentication setup", "3. Check project ID and region configuration", "4. Enable Vertex AI API in Google Cloud Console", "5. Enable Anthropic integration in Vertex AI Model Garden");
867
- }
868
- return result;
869
- }
870
- /**
871
- * Validate Vertex AI authentication configuration
872
- */
873
- static async validateVertexAuthentication() {
874
- const result = {
875
- isValid: false,
876
- method: "none",
877
- issues: [],
878
- };
879
- try {
880
- // Check for service account file authentication (preferred)
881
- if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
882
- const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
883
- try {
884
- const { promises: fs } = await import("fs");
885
- try {
886
- await fs.access(credentialsPath);
887
- // Validate JSON structure
888
- const credentialsContent = await fs.readFile(credentialsPath, "utf8");
889
- const credentials = JSON.parse(credentialsContent);
890
- if (credentials.type === "service_account" &&
891
- credentials.project_id &&
892
- credentials.client_email &&
893
- credentials.private_key) {
894
- result.isValid = true;
895
- result.method = "service_account_file";
896
- return result;
897
- }
898
- else {
899
- result.issues.push("Service account file missing required fields");
900
- }
901
- }
902
- catch {
903
- result.issues.push(`Service account file not found: ${credentialsPath}`);
904
- }
905
- }
906
- catch (fileError) {
907
- result.issues.push(`Service account file validation failed: ${fileError}`);
908
- }
909
- }
910
- // Check for individual environment variables
911
- if (process.env.GOOGLE_AUTH_CLIENT_EMAIL &&
912
- process.env.GOOGLE_AUTH_PRIVATE_KEY) {
913
- const email = process.env.GOOGLE_AUTH_CLIENT_EMAIL;
914
- const privateKey = process.env.GOOGLE_AUTH_PRIVATE_KEY;
915
- if (email.includes("@") && privateKey.includes("BEGIN PRIVATE KEY")) {
916
- result.isValid = true;
917
- result.method = "environment_variables";
918
- return result;
919
- }
920
- else {
921
- result.issues.push("Individual credentials format validation failed");
922
- }
923
- }
924
- else {
925
- result.issues.push("Missing individual credential environment variables");
926
- }
927
- // Check for Application Default Credentials (ADC)
928
- try {
929
- // This is a simple heuristic - in real implementation you'd use Google Auth library
930
- if (process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT) {
931
- result.method = "application_default_credentials";
932
- result.isValid = true; // Assume valid if environment suggests ADC
933
- return result;
934
- }
935
- }
936
- catch (adcError) {
937
- result.issues.push(`ADC check failed: ${adcError}`);
938
- }
939
- if (!result.isValid) {
940
- result.issues.push("No valid authentication method found");
941
- }
942
- }
943
- catch (error) {
944
- result.issues.push(`Authentication validation error: ${error}`);
945
- }
946
- return result;
947
- }
948
- /**
949
- * Validate Vertex AI project configuration
950
- */
951
- static async validateVertexProjectConfiguration() {
952
- const result = {
953
- isValid: false,
954
- projectId: undefined,
955
- region: undefined,
956
- issues: [],
957
- };
958
- // Check project ID
959
- const projectId = process.env.GOOGLE_VERTEX_PROJECT ||
960
- process.env.GOOGLE_CLOUD_PROJECT_ID ||
961
- process.env.GOOGLE_PROJECT_ID ||
962
- process.env.GOOGLE_CLOUD_PROJECT;
963
- if (projectId) {
964
- result.projectId = projectId;
965
- // Validate project ID format
966
- if (PROJECT_ID_FORMAT.PATTERN.test(projectId)) {
967
- result.isValid = true;
968
- }
969
- else {
970
- result.issues.push(`Invalid project ID format: ${projectId}`);
971
- }
972
- }
973
- else {
974
- result.issues.push("No project ID configured");
975
- }
976
- // Check region/location
977
- const region = process.env.GOOGLE_CLOUD_LOCATION ||
978
- process.env.VERTEX_LOCATION ||
979
- process.env.GOOGLE_VERTEX_LOCATION ||
980
- "us-central1";
981
- result.region = region;
982
- // Validate region format
983
- const regionPattern = /^[a-z]+-[a-z]+\d+$/;
984
- if (!regionPattern.test(region)) {
985
- result.issues.push(`Invalid region format: ${region}`);
986
- result.isValid = false;
987
- }
988
- return result;
989
- }
990
- /**
991
- * Check if the specified region supports Anthropic models
992
- */
993
- static async checkVertexRegionalSupport(region = "us-central1") {
994
- // Based on Google Cloud documentation, these regions support Anthropic models
995
- const supportedRegions = [
996
- "us-central1",
997
- "us-east4",
998
- "us-west1",
999
- "us-west4",
1000
- "europe-west1",
1001
- "europe-west4",
1002
- "asia-southeast1",
1003
- "asia-northeast1",
1004
- ];
1005
- const isSupported = supportedRegions.includes(region);
1006
- logger.debug("Regional support check", {
1007
- region,
1008
- isSupported,
1009
- supportedRegions,
1010
- });
1011
- return isSupported;
1012
- }
1013
- /**
1014
- * Check network connectivity to Vertex AI endpoints
1015
- */
1016
- static async checkVertexNetworkConnectivity(region = "us-central1") {
1017
- try {
1018
- const endpoint = `https://${region}-aiplatform.googleapis.com`;
1019
- // Simple connectivity check with timeout
1020
- const controller = new AbortController();
1021
- const timeoutId = setTimeout(() => controller.abort(), 5000);
1022
- const proxyFetch = createProxyFetch();
1023
- let response = await proxyFetch(endpoint, {
1024
- method: "HEAD",
1025
- signal: controller.signal,
1026
- });
1027
- // Fallback to GET if HEAD returns 405 (Method Not Allowed) for restrictive gateways
1028
- if (response.status === 405) {
1029
- response = await proxyFetch(endpoint, {
1030
- method: "GET",
1031
- signal: controller.signal,
1032
- });
1033
- }
1034
- clearTimeout(timeoutId);
1035
- // Any response (even 401/403) indicates network connectivity
1036
- const isConnected = response.status !== undefined;
1037
- logger.debug("Network connectivity check", {
1038
- endpoint,
1039
- status: response.status,
1040
- isConnected,
1041
- });
1042
- return isConnected;
1043
- }
1044
- catch (error) {
1045
- logger.debug("Network connectivity check failed", {
1046
- region,
1047
- error: error instanceof Error ? error.message : String(error),
1048
- });
1049
- return false;
1050
- }
1051
- }
1052
- /**
1053
- * Check if Anthropic model integration is enabled in the project
1054
- */
1055
- static async checkAnthropicModelIntegration(projectId, region = "us-central1") {
1056
- if (!projectId) {
1057
- logger.debug("Cannot check Anthropic integration without project ID");
1058
- return false;
1059
- }
1060
- try {
1061
- // This is a simplified check - in a real implementation, you would:
1062
- // 1. Use Google Cloud APIs to check model availability
1063
- // 2. Verify Anthropic integration status
1064
- // 3. Check model access permissions
1065
- // For now, we'll do a basic endpoint check
1066
- const modelEndpoint = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/anthropic/models`;
1067
- const controller = new AbortController();
1068
- const timeoutId = setTimeout(() => controller.abort(), 3000);
1069
- const proxyFetch = createProxyFetch();
1070
- let response = await proxyFetch(modelEndpoint, {
1071
- method: "HEAD",
1072
- signal: controller.signal,
1073
- });
1074
- // Fallback to GET if HEAD returns 405 (Method Not Allowed) for restrictive gateways
1075
- if (response.status === 405) {
1076
- response = await proxyFetch(modelEndpoint, {
1077
- method: "GET",
1078
- signal: controller.signal,
1079
- });
1080
- }
1081
- clearTimeout(timeoutId);
1082
- // Status 200 or 401/403 suggests the endpoint exists (integration enabled)
1083
- // Status 404 suggests integration not enabled
1084
- const integrationEnabled = response.status !== 404;
1085
- logger.debug("Anthropic integration check", {
1086
- projectId,
1087
- region,
1088
- endpoint: modelEndpoint,
1089
- status: response.status,
1090
- integrationEnabled,
1091
- });
1092
- return integrationEnabled;
1093
- }
1094
- catch (error) {
1095
- logger.debug("Anthropic integration check failed", {
1096
- projectId,
1097
- region,
1098
- error: error instanceof Error ? error.message : String(error),
1099
- });
1100
- // Assume integration might be enabled if we can't verify
1101
- return true;
1102
- }
1103
- }
1104
- /**
1105
- * Initialize health checks in the background (NON-BLOCKING)
1106
- * Starts background health monitoring without blocking initialization
1107
- */
1108
- static initializeBackgroundHealthChecks() {
1109
- // Run health checks in the background without awaiting
1110
- const backgroundHealthCheck = async () => {
1111
- try {
1112
- logger.debug("Starting background health check initialization");
1113
- await this.checkAllProvidersHealth({
1114
- includeConnectivityTest: false,
1115
- cacheResults: true,
1116
- timeout: 2000, // 2-second timeout for background checks
1117
- });
1118
- logger.debug("Background health check initialization completed");
1119
- }
1120
- catch (error) {
1121
- logger.warn("Background health check initialization failed", {
1122
- error: error instanceof Error ? error.message : String(error),
1123
- });
1124
- }
1125
- };
1126
- // Start background check without blocking
1127
- backgroundHealthCheck();
1128
- }
1129
- /**
1130
- * Clear health cache for a provider or all providers
1131
- */
1132
- static clearHealthCache(providerName) {
1133
- if (providerName) {
1134
- this.healthCache.delete(providerName);
1135
- this.consecutiveFailures.delete(providerName);
1136
- }
1137
- else {
1138
- this.healthCache.clear();
1139
- this.consecutiveFailures.clear();
1140
- }
1141
- }
1142
- /**
1143
- * Get the best healthy provider from a list of options (NON-BLOCKING)
1144
- * Prioritizes healthy providers over configured but unhealthy ones
1145
- * Uses fast, cached health checks to avoid blocking initialization
1146
- */
1147
- static async getBestHealthyProvider(preferredProviders = [
1148
- "openai",
1149
- "anthropic",
1150
- "vertex",
1151
- "bedrock",
1152
- "azure",
1153
- "google-ai",
1154
- ]) {
1155
- const healthStatuses = await this.checkAllProvidersHealth({
1156
- includeConnectivityTest: false, // Quick config check only
1157
- cacheResults: true,
1158
- timeout: 1000, // Fast 1-second timeout to avoid blocking
1159
- });
1160
- // First try to find a healthy provider in order of preference
1161
- for (const provider of preferredProviders) {
1162
- const health = healthStatuses.find((h) => h.provider === provider);
1163
- if (health?.isHealthy) {
1164
- logger.debug(`Selected healthy provider: ${provider}`);
1165
- return provider;
1166
- }
1167
- }
1168
- // Fallback to first healthy provider
1169
- const firstHealthyProvider = healthStatuses.find((h) => h.isHealthy);
1170
- if (firstHealthyProvider) {
1171
- logger.info(`Using fallback healthy provider: ${firstHealthyProvider.provider}`);
1172
- return firstHealthyProvider.provider;
1173
- }
1174
- // Last resort: first configured provider
1175
- const anyConfigured = healthStatuses.find((h) => h.isConfigured);
1176
- if (anyConfigured) {
1177
- logger.warn(`Using configured but potentially unhealthy provider: ${anyConfigured.provider}`);
1178
- return anyConfigured.provider;
1179
- }
1180
- logger.error("No healthy or configured providers found");
1181
- return null;
1182
- }
1183
- /**
1184
- * Get health status for all registered providers
1185
- */
1186
- static async checkAllProvidersHealth(options = {}) {
1187
- const providers = [
1188
- AIProviderName.VERTEX,
1189
- AIProviderName.GOOGLE_AI,
1190
- AIProviderName.ANTHROPIC,
1191
- AIProviderName.OPENAI,
1192
- AIProviderName.BEDROCK,
1193
- AIProviderName.AZURE,
1194
- AIProviderName.OLLAMA,
1195
- ];
1196
- const healthChecks = providers.map((provider) => this.checkProviderHealth(provider, options));
1197
- const results = await Promise.allSettled(healthChecks);
1198
- return results.map((result, index) => {
1199
- if (result.status === "fulfilled") {
1200
- return result.value;
1201
- }
1202
- else {
1203
- // Return a failed health status for rejected promises
1204
- return {
1205
- provider: providers[index],
1206
- isHealthy: false,
1207
- isConfigured: false,
1208
- hasApiKey: false,
1209
- lastChecked: new Date(),
1210
- error: result.reason?.message || "Health check failed",
1211
- configurationIssues: ["Health check promise rejected"],
1212
- recommendations: [
1213
- "Check provider configuration and network connectivity",
1214
- ],
1215
- };
1216
- }
1217
- });
1218
- }
1219
- /**
1220
- * Get a summary of provider health
1221
- */
1222
- static getHealthSummary(healthStatuses) {
1223
- const healthy = healthStatuses.filter((h) => h.isHealthy);
1224
- const configured = healthStatuses.filter((h) => h.isConfigured);
1225
- const hasIssues = healthStatuses.filter((h) => h.configurationIssues.length > 0);
1226
- return {
1227
- total: healthStatuses.length,
1228
- healthy: healthy.length,
1229
- configured: configured.length,
1230
- hasIssues: hasIssues.length,
1231
- healthyProviders: healthy.map((h) => h.provider),
1232
- unhealthyProviders: healthStatuses
1233
- .filter((h) => !h.isHealthy)
1234
- .map((h) => h.provider),
1235
- };
1236
- }
1237
- }