@juspay/neurolink 9.5.3 → 9.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (423) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +29 -25
  3. package/dist/adapters/video/vertexVideoHandler.js +3 -3
  4. package/dist/agent/directTools.d.ts +5 -5
  5. package/dist/cli/commands/config.d.ts +9 -9
  6. package/dist/cli/commands/serve.d.ts +37 -0
  7. package/dist/cli/commands/serve.js +302 -229
  8. package/dist/cli/commands/setup-anthropic.d.ts +2 -2
  9. package/dist/cli/commands/setup-azure.d.ts +2 -2
  10. package/dist/cli/commands/setup-bedrock.d.ts +2 -2
  11. package/dist/cli/commands/setup-gcp.d.ts +2 -2
  12. package/dist/cli/commands/setup-google-ai.d.ts +2 -2
  13. package/dist/cli/commands/setup-huggingface.d.ts +2 -2
  14. package/dist/cli/commands/setup-mistral.d.ts +2 -2
  15. package/dist/cli/commands/setup-openai.d.ts +2 -2
  16. package/dist/cli/commands/setup.d.ts +2 -2
  17. package/dist/cli/factories/commandFactory.js +16 -2
  18. package/dist/cli/loop/optionsSchema.d.ts +2 -2
  19. package/dist/cli/loop/optionsSchema.js +4 -0
  20. package/dist/cli/loop/session.d.ts +4 -0
  21. package/dist/cli/loop/session.js +49 -4
  22. package/dist/cli/utils/interactiveSetup.d.ts +4 -4
  23. package/dist/config/conversationMemory.d.ts +2 -0
  24. package/dist/config/conversationMemory.js +5 -5
  25. package/dist/constants/contextWindows.d.ts +46 -0
  26. package/dist/constants/contextWindows.js +156 -0
  27. package/dist/context/budgetChecker.d.ts +18 -0
  28. package/dist/context/budgetChecker.js +71 -0
  29. package/dist/context/contextCompactor.d.ts +22 -0
  30. package/dist/context/contextCompactor.js +106 -0
  31. package/dist/context/effectiveHistory.d.ts +52 -0
  32. package/dist/context/effectiveHistory.js +105 -0
  33. package/dist/context/errorDetection.d.ts +14 -0
  34. package/dist/context/errorDetection.js +124 -0
  35. package/dist/context/fileSummarizationService.d.ts +54 -0
  36. package/dist/context/fileSummarizationService.js +255 -0
  37. package/dist/context/fileSummarizer.d.ts +56 -0
  38. package/dist/context/fileSummarizer.js +145 -0
  39. package/dist/context/fileTokenBudget.d.ts +53 -0
  40. package/dist/context/fileTokenBudget.js +127 -0
  41. package/dist/context/prompts/summarizationPrompt.d.ts +17 -0
  42. package/dist/context/prompts/summarizationPrompt.js +110 -0
  43. package/dist/context/stages/fileReadDeduplicator.d.ts +10 -0
  44. package/dist/context/stages/fileReadDeduplicator.js +66 -0
  45. package/dist/context/stages/slidingWindowTruncator.d.ts +11 -0
  46. package/dist/context/stages/slidingWindowTruncator.js +42 -0
  47. package/dist/context/stages/structuredSummarizer.d.ts +10 -0
  48. package/dist/context/stages/structuredSummarizer.js +49 -0
  49. package/dist/context/stages/toolOutputPruner.d.ts +10 -0
  50. package/dist/context/stages/toolOutputPruner.js +52 -0
  51. package/dist/context/summarizationEngine.d.ts +45 -0
  52. package/dist/context/summarizationEngine.js +110 -0
  53. package/dist/context/toolOutputLimits.d.ts +17 -0
  54. package/dist/context/toolOutputLimits.js +84 -0
  55. package/dist/context/toolPairRepair.d.ts +16 -0
  56. package/dist/context/toolPairRepair.js +66 -0
  57. package/dist/core/analytics.js +11 -4
  58. package/dist/core/baseProvider.d.ts +6 -0
  59. package/dist/core/baseProvider.js +83 -14
  60. package/dist/core/conversationMemoryManager.d.ts +14 -11
  61. package/dist/core/conversationMemoryManager.js +36 -68
  62. package/dist/core/dynamicModels.js +3 -2
  63. package/dist/core/modules/GenerationHandler.js +2 -0
  64. package/dist/core/modules/MessageBuilder.d.ts +1 -1
  65. package/dist/core/modules/MessageBuilder.js +2 -0
  66. package/dist/core/modules/TelemetryHandler.d.ts +2 -3
  67. package/dist/core/modules/TelemetryHandler.js +3 -3
  68. package/dist/core/modules/ToolsManager.d.ts +2 -2
  69. package/dist/core/redisConversationMemoryManager.d.ts +19 -14
  70. package/dist/core/redisConversationMemoryManager.js +94 -86
  71. package/dist/factories/providerFactory.d.ts +2 -2
  72. package/dist/files/fileReferenceRegistry.d.ts +276 -0
  73. package/dist/files/fileReferenceRegistry.js +1543 -0
  74. package/dist/files/fileTools.d.ts +423 -0
  75. package/dist/files/fileTools.js +449 -0
  76. package/dist/files/index.d.ts +14 -0
  77. package/dist/files/index.js +13 -0
  78. package/dist/files/streamingReader.d.ts +93 -0
  79. package/dist/files/streamingReader.js +321 -0
  80. package/dist/files/types.d.ts +23 -0
  81. package/dist/files/types.js +23 -0
  82. package/dist/image-gen/imageGenTools.d.ts +2 -2
  83. package/dist/image-gen/types.d.ts +12 -12
  84. package/dist/index.d.ts +4 -0
  85. package/dist/index.js +5 -0
  86. package/dist/lib/adapters/video/vertexVideoHandler.js +3 -3
  87. package/dist/lib/agent/directTools.d.ts +7 -7
  88. package/dist/lib/config/conversationMemory.d.ts +2 -0
  89. package/dist/lib/config/conversationMemory.js +5 -5
  90. package/dist/lib/constants/contextWindows.d.ts +46 -0
  91. package/dist/lib/constants/contextWindows.js +157 -0
  92. package/dist/lib/context/budgetChecker.d.ts +18 -0
  93. package/dist/lib/context/budgetChecker.js +72 -0
  94. package/dist/lib/context/contextCompactor.d.ts +22 -0
  95. package/dist/lib/context/contextCompactor.js +107 -0
  96. package/dist/lib/context/effectiveHistory.d.ts +52 -0
  97. package/dist/lib/context/effectiveHistory.js +106 -0
  98. package/dist/lib/context/errorDetection.d.ts +14 -0
  99. package/dist/lib/context/errorDetection.js +125 -0
  100. package/dist/lib/context/fileSummarizationService.d.ts +54 -0
  101. package/dist/lib/context/fileSummarizationService.js +256 -0
  102. package/dist/lib/context/fileSummarizer.d.ts +56 -0
  103. package/dist/lib/context/fileSummarizer.js +146 -0
  104. package/dist/lib/context/fileTokenBudget.d.ts +53 -0
  105. package/dist/lib/context/fileTokenBudget.js +128 -0
  106. package/dist/lib/context/prompts/summarizationPrompt.d.ts +17 -0
  107. package/dist/lib/context/prompts/summarizationPrompt.js +111 -0
  108. package/dist/lib/context/stages/fileReadDeduplicator.d.ts +10 -0
  109. package/dist/lib/context/stages/fileReadDeduplicator.js +67 -0
  110. package/dist/lib/context/stages/slidingWindowTruncator.d.ts +11 -0
  111. package/dist/lib/context/stages/slidingWindowTruncator.js +43 -0
  112. package/dist/lib/context/stages/structuredSummarizer.d.ts +10 -0
  113. package/dist/lib/context/stages/structuredSummarizer.js +50 -0
  114. package/dist/lib/context/stages/toolOutputPruner.d.ts +10 -0
  115. package/dist/lib/context/stages/toolOutputPruner.js +53 -0
  116. package/dist/lib/context/summarizationEngine.d.ts +45 -0
  117. package/dist/lib/context/summarizationEngine.js +111 -0
  118. package/dist/lib/context/toolOutputLimits.d.ts +17 -0
  119. package/dist/lib/context/toolOutputLimits.js +85 -0
  120. package/dist/lib/context/toolPairRepair.d.ts +16 -0
  121. package/dist/lib/context/toolPairRepair.js +67 -0
  122. package/dist/lib/core/analytics.js +11 -4
  123. package/dist/lib/core/baseProvider.d.ts +6 -0
  124. package/dist/lib/core/baseProvider.js +83 -14
  125. package/dist/lib/core/conversationMemoryManager.d.ts +14 -11
  126. package/dist/lib/core/conversationMemoryManager.js +36 -68
  127. package/dist/lib/core/dynamicModels.js +3 -2
  128. package/dist/lib/core/modules/GenerationHandler.js +2 -0
  129. package/dist/lib/core/modules/MessageBuilder.d.ts +1 -1
  130. package/dist/lib/core/modules/MessageBuilder.js +2 -0
  131. package/dist/lib/core/modules/TelemetryHandler.d.ts +2 -3
  132. package/dist/lib/core/modules/TelemetryHandler.js +3 -3
  133. package/dist/lib/core/modules/ToolsManager.d.ts +2 -2
  134. package/dist/lib/core/redisConversationMemoryManager.d.ts +19 -14
  135. package/dist/lib/core/redisConversationMemoryManager.js +94 -86
  136. package/dist/lib/factories/providerFactory.d.ts +2 -2
  137. package/dist/lib/files/fileReferenceRegistry.d.ts +276 -0
  138. package/dist/lib/files/fileReferenceRegistry.js +1544 -0
  139. package/dist/lib/files/fileTools.d.ts +423 -0
  140. package/dist/lib/files/fileTools.js +450 -0
  141. package/dist/lib/files/index.d.ts +14 -0
  142. package/dist/lib/files/index.js +14 -0
  143. package/dist/lib/files/streamingReader.d.ts +93 -0
  144. package/dist/lib/files/streamingReader.js +322 -0
  145. package/dist/lib/files/types.d.ts +23 -0
  146. package/dist/lib/files/types.js +24 -0
  147. package/dist/lib/image-gen/imageGenTools.d.ts +2 -2
  148. package/dist/lib/image-gen/types.d.ts +12 -12
  149. package/dist/lib/index.d.ts +4 -0
  150. package/dist/lib/index.js +5 -0
  151. package/dist/lib/mcp/httpRetryHandler.js +6 -2
  152. package/dist/lib/memory/mem0Initializer.d.ts +2 -2
  153. package/dist/lib/neurolink.d.ts +66 -2
  154. package/dist/lib/neurolink.js +777 -315
  155. package/dist/lib/processors/archive/ArchiveProcessor.d.ts +327 -0
  156. package/dist/lib/processors/archive/ArchiveProcessor.js +1309 -0
  157. package/dist/lib/processors/archive/index.d.ts +33 -0
  158. package/dist/lib/processors/archive/index.js +43 -0
  159. package/dist/lib/processors/base/BaseFileProcessor.js +2 -1
  160. package/dist/lib/processors/base/types.d.ts +70 -64
  161. package/dist/lib/processors/base/types.js +6 -0
  162. package/dist/lib/processors/cli/fileProcessorCli.d.ts +8 -8
  163. package/dist/lib/processors/cli/fileProcessorCli.js +5 -5
  164. package/dist/lib/processors/config/mimeTypes.js +25 -0
  165. package/dist/lib/processors/config/sizeLimits.d.ts +52 -40
  166. package/dist/lib/processors/config/sizeLimits.js +56 -44
  167. package/dist/lib/processors/document/ExcelProcessor.d.ts +14 -0
  168. package/dist/lib/processors/document/ExcelProcessor.js +72 -1
  169. package/dist/lib/processors/document/PptxProcessor.d.ts +63 -0
  170. package/dist/lib/processors/document/PptxProcessor.js +158 -0
  171. package/dist/lib/processors/document/index.d.ts +1 -0
  172. package/dist/lib/processors/document/index.js +6 -0
  173. package/dist/lib/processors/errors/FileErrorCode.d.ts +2 -2
  174. package/dist/lib/processors/errors/errorHelpers.d.ts +2 -2
  175. package/dist/lib/processors/errors/errorHelpers.js +12 -4
  176. package/dist/lib/processors/errors/errorSerializer.d.ts +4 -4
  177. package/dist/lib/processors/index.d.ts +8 -2
  178. package/dist/lib/processors/index.js +5 -2
  179. package/dist/lib/processors/integration/FileProcessorIntegration.d.ts +8 -8
  180. package/dist/lib/processors/integration/FileProcessorIntegration.js +7 -7
  181. package/dist/lib/processors/media/AudioProcessor.d.ts +328 -0
  182. package/dist/lib/processors/media/AudioProcessor.js +708 -0
  183. package/dist/lib/processors/media/VideoProcessor.d.ts +350 -0
  184. package/dist/lib/processors/media/VideoProcessor.js +992 -0
  185. package/dist/lib/processors/media/index.d.ts +27 -0
  186. package/dist/lib/processors/media/index.js +37 -0
  187. package/dist/lib/processors/registry/ProcessorRegistry.d.ts +19 -5
  188. package/dist/lib/processors/registry/ProcessorRegistry.js +103 -8
  189. package/dist/lib/processors/registry/index.d.ts +1 -1
  190. package/dist/lib/processors/registry/index.js +1 -1
  191. package/dist/lib/processors/registry/types.d.ts +2 -2
  192. package/dist/lib/providers/amazonBedrock.js +2 -1
  193. package/dist/lib/providers/anthropic.js +2 -2
  194. package/dist/lib/providers/anthropicBaseProvider.js +10 -4
  195. package/dist/lib/providers/azureOpenai.js +14 -25
  196. package/dist/lib/providers/googleAiStudio.js +136 -457
  197. package/dist/lib/providers/googleNativeGemini3.d.ts +119 -0
  198. package/dist/lib/providers/googleNativeGemini3.js +264 -0
  199. package/dist/lib/providers/googleVertex.d.ts +15 -1
  200. package/dist/lib/providers/googleVertex.js +341 -775
  201. package/dist/lib/providers/huggingFace.js +20 -5
  202. package/dist/lib/providers/litellm.js +6 -4
  203. package/dist/lib/providers/mistral.js +3 -2
  204. package/dist/lib/providers/openAI.js +2 -2
  205. package/dist/lib/providers/openRouter.js +8 -7
  206. package/dist/lib/providers/openaiCompatible.js +10 -4
  207. package/dist/lib/providers/sagemaker/detection.d.ts +6 -6
  208. package/dist/lib/providers/sagemaker/diagnostics.d.ts +4 -4
  209. package/dist/lib/providers/sagemaker/parsers.d.ts +4 -4
  210. package/dist/lib/rag/chunkers/RecursiveChunker.js +2 -2
  211. package/dist/lib/rag/document/loaders.d.ts +6 -71
  212. package/dist/lib/rag/document/loaders.js +5 -5
  213. package/dist/lib/rag/graphRag/graphRAG.js +26 -9
  214. package/dist/lib/rag/metadata/MetadataExtractorFactory.d.ts +5 -55
  215. package/dist/lib/rag/metadata/metadataExtractor.js +6 -3
  216. package/dist/lib/rag/pipeline/RAGPipeline.d.ts +8 -126
  217. package/dist/lib/rag/pipeline/RAGPipeline.js +11 -11
  218. package/dist/lib/rag/pipeline/contextAssembly.d.ts +3 -42
  219. package/dist/lib/rag/pipeline/contextAssembly.js +6 -3
  220. package/dist/lib/rag/reranker/RerankerFactory.d.ts +5 -60
  221. package/dist/lib/rag/resilience/CircuitBreaker.d.ts +3 -33
  222. package/dist/lib/rag/resilience/RetryHandler.d.ts +2 -21
  223. package/dist/lib/rag/resilience/RetryHandler.js +6 -2
  224. package/dist/lib/rag/retrieval/hybridSearch.d.ts +3 -41
  225. package/dist/lib/rag/retrieval/vectorQueryTool.d.ts +2 -13
  226. package/dist/lib/rag/retrieval/vectorQueryTool.js +4 -3
  227. package/dist/lib/rag/types.d.ts +3 -3
  228. package/dist/lib/sdk/toolRegistration.d.ts +2 -2
  229. package/dist/lib/server/middleware/cache.d.ts +2 -2
  230. package/dist/lib/server/middleware/rateLimit.d.ts +2 -2
  231. package/dist/lib/server/routes/mcpRoutes.js +277 -249
  232. package/dist/lib/server/routes/memoryRoutes.js +287 -281
  233. package/dist/lib/server/utils/validation.d.ts +10 -10
  234. package/dist/lib/services/server/ai/observability/instrumentation.d.ts +24 -2
  235. package/dist/lib/services/server/ai/observability/instrumentation.js +12 -1
  236. package/dist/lib/session/globalSessionState.d.ts +2 -2
  237. package/dist/lib/telemetry/telemetryService.d.ts +2 -2
  238. package/dist/lib/types/common.d.ts +39 -0
  239. package/dist/lib/types/contextTypes.d.ts +255 -0
  240. package/dist/lib/types/contextTypes.js +0 -2
  241. package/dist/lib/types/conversation.d.ts +62 -0
  242. package/dist/lib/types/conversationMemoryInterface.d.ts +27 -0
  243. package/dist/lib/types/conversationMemoryInterface.js +7 -0
  244. package/dist/lib/types/fileReferenceTypes.d.ts +222 -0
  245. package/dist/lib/types/fileReferenceTypes.js +9 -0
  246. package/dist/lib/types/fileTypes.d.ts +26 -3
  247. package/dist/lib/types/generateTypes.d.ts +50 -1
  248. package/dist/lib/types/index.d.ts +4 -5
  249. package/dist/lib/types/index.js +8 -10
  250. package/dist/lib/types/modelTypes.d.ts +2 -2
  251. package/dist/lib/types/processorTypes.d.ts +597 -0
  252. package/dist/lib/types/processorTypes.js +91 -0
  253. package/dist/lib/types/ragTypes.d.ts +489 -0
  254. package/dist/lib/types/ragTypes.js +8 -0
  255. package/dist/lib/types/sdkTypes.d.ts +17 -18
  256. package/dist/lib/types/streamTypes.d.ts +24 -1
  257. package/dist/lib/utils/async/retry.d.ts +2 -2
  258. package/dist/lib/utils/async/withTimeout.js +3 -1
  259. package/dist/lib/utils/conversationMemory.d.ts +12 -6
  260. package/dist/lib/utils/conversationMemory.js +91 -36
  261. package/dist/lib/utils/errorHandling.d.ts +5 -0
  262. package/dist/lib/utils/errorHandling.js +19 -0
  263. package/dist/lib/utils/fileDetector.d.ts +62 -0
  264. package/dist/lib/utils/fileDetector.js +1014 -14
  265. package/dist/lib/utils/json/safeParse.d.ts +2 -2
  266. package/dist/lib/utils/messageBuilder.js +806 -153
  267. package/dist/lib/utils/modelChoices.d.ts +2 -2
  268. package/dist/lib/utils/multimodalOptionsBuilder.d.ts +2 -1
  269. package/dist/lib/utils/multimodalOptionsBuilder.js +1 -0
  270. package/dist/lib/utils/pricing.d.ts +12 -0
  271. package/dist/lib/utils/pricing.js +134 -0
  272. package/dist/lib/utils/rateLimiter.d.ts +2 -2
  273. package/dist/lib/utils/redis.d.ts +17 -0
  274. package/dist/lib/utils/redis.js +105 -0
  275. package/dist/lib/utils/sanitizers/filename.d.ts +4 -4
  276. package/dist/lib/utils/sanitizers/svg.d.ts +2 -2
  277. package/dist/lib/utils/thinkingConfig.d.ts +6 -6
  278. package/dist/lib/utils/timeout.d.ts +10 -0
  279. package/dist/lib/utils/timeout.js +15 -0
  280. package/dist/lib/utils/tokenEstimation.d.ts +68 -0
  281. package/dist/lib/utils/tokenEstimation.js +113 -0
  282. package/dist/lib/utils/tokenUtils.d.ts +4 -4
  283. package/dist/lib/utils/ttsProcessor.d.ts +2 -2
  284. package/dist/lib/workflow/config.d.ts +150 -150
  285. package/dist/mcp/httpRetryHandler.js +6 -2
  286. package/dist/memory/mem0Initializer.d.ts +2 -2
  287. package/dist/neurolink.d.ts +66 -2
  288. package/dist/neurolink.js +777 -315
  289. package/dist/processors/archive/ArchiveProcessor.d.ts +327 -0
  290. package/dist/processors/archive/ArchiveProcessor.js +1308 -0
  291. package/dist/processors/archive/index.d.ts +33 -0
  292. package/dist/processors/archive/index.js +42 -0
  293. package/dist/processors/base/BaseFileProcessor.js +2 -1
  294. package/dist/processors/base/types.d.ts +70 -64
  295. package/dist/processors/base/types.js +6 -0
  296. package/dist/processors/cli/fileProcessorCli.d.ts +8 -8
  297. package/dist/processors/cli/fileProcessorCli.js +5 -5
  298. package/dist/processors/config/mimeTypes.js +25 -0
  299. package/dist/processors/config/sizeLimits.d.ts +52 -40
  300. package/dist/processors/config/sizeLimits.js +56 -44
  301. package/dist/processors/document/ExcelProcessor.d.ts +14 -0
  302. package/dist/processors/document/ExcelProcessor.js +72 -1
  303. package/dist/processors/document/PptxProcessor.d.ts +63 -0
  304. package/dist/processors/document/PptxProcessor.js +157 -0
  305. package/dist/processors/document/index.d.ts +1 -0
  306. package/dist/processors/document/index.js +6 -0
  307. package/dist/processors/errors/FileErrorCode.d.ts +2 -2
  308. package/dist/processors/errors/errorHelpers.d.ts +2 -2
  309. package/dist/processors/errors/errorHelpers.js +12 -4
  310. package/dist/processors/errors/errorSerializer.d.ts +4 -4
  311. package/dist/processors/index.d.ts +8 -2
  312. package/dist/processors/index.js +5 -2
  313. package/dist/processors/integration/FileProcessorIntegration.d.ts +8 -8
  314. package/dist/processors/integration/FileProcessorIntegration.js +7 -7
  315. package/dist/processors/media/AudioProcessor.d.ts +328 -0
  316. package/dist/processors/media/AudioProcessor.js +707 -0
  317. package/dist/processors/media/VideoProcessor.d.ts +350 -0
  318. package/dist/processors/media/VideoProcessor.js +991 -0
  319. package/dist/processors/media/ffprobe-static.d.ts +4 -0
  320. package/dist/processors/media/index.d.ts +27 -0
  321. package/dist/processors/media/index.js +36 -0
  322. package/dist/processors/registry/ProcessorRegistry.d.ts +19 -5
  323. package/dist/processors/registry/ProcessorRegistry.js +103 -8
  324. package/dist/processors/registry/index.d.ts +1 -1
  325. package/dist/processors/registry/index.js +1 -1
  326. package/dist/processors/registry/types.d.ts +2 -2
  327. package/dist/providers/amazonBedrock.js +2 -1
  328. package/dist/providers/anthropic.js +2 -2
  329. package/dist/providers/anthropicBaseProvider.js +10 -4
  330. package/dist/providers/azureOpenai.js +14 -25
  331. package/dist/providers/googleAiStudio.js +136 -457
  332. package/dist/providers/googleNativeGemini3.d.ts +119 -0
  333. package/dist/providers/googleNativeGemini3.js +263 -0
  334. package/dist/providers/googleVertex.d.ts +15 -1
  335. package/dist/providers/googleVertex.js +341 -775
  336. package/dist/providers/huggingFace.js +20 -5
  337. package/dist/providers/litellm.js +6 -4
  338. package/dist/providers/mistral.js +3 -2
  339. package/dist/providers/openAI.js +2 -2
  340. package/dist/providers/openRouter.js +8 -7
  341. package/dist/providers/openaiCompatible.js +10 -4
  342. package/dist/providers/sagemaker/detection.d.ts +6 -6
  343. package/dist/providers/sagemaker/diagnostics.d.ts +4 -4
  344. package/dist/providers/sagemaker/parsers.d.ts +4 -4
  345. package/dist/rag/chunkers/RecursiveChunker.js +2 -2
  346. package/dist/rag/document/loaders.d.ts +6 -71
  347. package/dist/rag/document/loaders.js +5 -5
  348. package/dist/rag/graphRag/graphRAG.js +26 -9
  349. package/dist/rag/metadata/MetadataExtractorFactory.d.ts +5 -55
  350. package/dist/rag/metadata/metadataExtractor.js +6 -3
  351. package/dist/rag/pipeline/RAGPipeline.d.ts +8 -126
  352. package/dist/rag/pipeline/RAGPipeline.js +11 -11
  353. package/dist/rag/pipeline/contextAssembly.d.ts +3 -42
  354. package/dist/rag/pipeline/contextAssembly.js +6 -3
  355. package/dist/rag/reranker/RerankerFactory.d.ts +5 -60
  356. package/dist/rag/resilience/CircuitBreaker.d.ts +3 -33
  357. package/dist/rag/resilience/RetryHandler.d.ts +2 -21
  358. package/dist/rag/resilience/RetryHandler.js +6 -2
  359. package/dist/rag/retrieval/hybridSearch.d.ts +3 -41
  360. package/dist/rag/retrieval/vectorQueryTool.d.ts +2 -13
  361. package/dist/rag/retrieval/vectorQueryTool.js +4 -3
  362. package/dist/rag/types.d.ts +3 -3
  363. package/dist/sdk/toolRegistration.d.ts +2 -2
  364. package/dist/server/middleware/cache.d.ts +2 -2
  365. package/dist/server/middleware/rateLimit.d.ts +2 -2
  366. package/dist/server/routes/mcpRoutes.js +277 -249
  367. package/dist/server/routes/memoryRoutes.js +287 -281
  368. package/dist/server/utils/validation.d.ts +4 -4
  369. package/dist/services/server/ai/observability/instrumentation.d.ts +24 -2
  370. package/dist/services/server/ai/observability/instrumentation.js +12 -1
  371. package/dist/session/globalSessionState.d.ts +2 -2
  372. package/dist/telemetry/telemetryService.d.ts +2 -2
  373. package/dist/types/common.d.ts +39 -0
  374. package/dist/types/contextTypes.d.ts +255 -0
  375. package/dist/types/contextTypes.js +0 -2
  376. package/dist/types/conversation.d.ts +62 -0
  377. package/dist/types/conversationMemoryInterface.d.ts +27 -0
  378. package/dist/types/conversationMemoryInterface.js +6 -0
  379. package/dist/types/fileReferenceTypes.d.ts +222 -0
  380. package/dist/types/fileReferenceTypes.js +8 -0
  381. package/dist/types/fileTypes.d.ts +26 -3
  382. package/dist/types/generateTypes.d.ts +50 -1
  383. package/dist/types/index.d.ts +4 -5
  384. package/dist/types/index.js +8 -10
  385. package/dist/types/processorTypes.d.ts +597 -0
  386. package/dist/types/processorTypes.js +90 -0
  387. package/dist/types/ragTypes.d.ts +489 -0
  388. package/dist/types/ragTypes.js +7 -0
  389. package/dist/types/sdkTypes.d.ts +17 -18
  390. package/dist/types/streamTypes.d.ts +24 -1
  391. package/dist/utils/async/retry.d.ts +2 -2
  392. package/dist/utils/async/withTimeout.js +3 -1
  393. package/dist/utils/conversationMemory.d.ts +12 -6
  394. package/dist/utils/conversationMemory.js +91 -36
  395. package/dist/utils/errorHandling.d.ts +5 -0
  396. package/dist/utils/errorHandling.js +19 -0
  397. package/dist/utils/fileDetector.d.ts +62 -0
  398. package/dist/utils/fileDetector.js +1014 -14
  399. package/dist/utils/json/safeParse.d.ts +2 -2
  400. package/dist/utils/messageBuilder.js +806 -153
  401. package/dist/utils/modelChoices.d.ts +2 -2
  402. package/dist/utils/multimodalOptionsBuilder.d.ts +2 -1
  403. package/dist/utils/multimodalOptionsBuilder.js +1 -0
  404. package/dist/utils/pricing.d.ts +12 -0
  405. package/dist/utils/pricing.js +133 -0
  406. package/dist/utils/rateLimiter.d.ts +2 -2
  407. package/dist/utils/redis.d.ts +17 -0
  408. package/dist/utils/redis.js +105 -0
  409. package/dist/utils/sanitizers/filename.d.ts +4 -4
  410. package/dist/utils/sanitizers/svg.d.ts +2 -2
  411. package/dist/utils/thinkingConfig.d.ts +6 -6
  412. package/dist/utils/timeout.d.ts +10 -0
  413. package/dist/utils/timeout.js +15 -0
  414. package/dist/utils/tokenEstimation.d.ts +68 -0
  415. package/dist/utils/tokenEstimation.js +112 -0
  416. package/dist/utils/tokenUtils.d.ts +4 -4
  417. package/dist/utils/ttsProcessor.d.ts +2 -2
  418. package/dist/workflow/config.d.ts +104 -104
  419. package/package.json +18 -6
  420. package/dist/lib/utils/conversationMemoryUtils.d.ts +0 -25
  421. package/dist/lib/utils/conversationMemoryUtils.js +0 -138
  422. package/dist/utils/conversationMemoryUtils.d.ts +0 -25
  423. package/dist/utils/conversationMemoryUtils.js +0 -137
@@ -0,0 +1,992 @@
1
+ /**
2
+ * Video Processor
3
+ *
4
+ * Handles downloading, validating, and processing video files for AI consumption.
5
+ * Since LLMs cannot process raw video, this processor extracts:
6
+ * - Structured metadata (duration, resolution, codecs, etc.)
7
+ * - Keyframes at configurable intervals (resized to 768px JPEG)
8
+ * - Embedded subtitle tracks (if present)
9
+ *
10
+ * The extracted content is formatted as text + images that can be sent to any
11
+ * AI provider for analysis.
12
+ *
13
+ * Uses fluent-ffmpeg for video processing and sharp for frame resizing.
14
+ * Requires ffmpeg/ffprobe to be available (via ffmpeg-static or system PATH).
15
+ *
16
+ * Key features:
17
+ * - Adaptive keyframe extraction intervals based on video duration
18
+ * - Frame count capping (max 20 frames) to control token usage
19
+ * - JPEG quality optimization for AI vision models
20
+ * - Embedded subtitle extraction (SRT format)
21
+ * - Graceful degradation on corrupt files or missing codecs
22
+ * - Temp file cleanup with finally blocks
23
+ * - Configurable timeouts for ffmpeg and ffprobe operations
24
+ *
25
+ * @module processors/media/VideoProcessor
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * import { videoProcessor, processVideo, isVideoFile } from "./VideoProcessor.js";
30
+ *
31
+ * // Check if a file is a video file
32
+ * if (isVideoFile(fileInfo.mimetype, fileInfo.name)) {
33
+ * const result = await processVideo(fileInfo, {
34
+ * authHeaders: { Authorization: "Bearer token" },
35
+ * });
36
+ *
37
+ * if (result.success) {
38
+ * console.log(`Duration: ${result.data.metadata.durationFormatted}`);
39
+ * console.log(`Keyframes: ${result.data.frameCount}`);
40
+ * console.log(`Text for LLM:\n${result.data.textContent}`);
41
+ * }
42
+ * }
43
+ * ```
44
+ */
45
+ /// <reference path="./ffprobe-static.d.ts" />
46
+ import { randomUUID } from "crypto";
47
+ import ffmpegCommand from "fluent-ffmpeg";
48
+ import { createWriteStream, existsSync, promises as fs } from "fs";
49
+ import { tmpdir } from "os";
50
+ import { join } from "path";
51
+ import sharp from "sharp";
52
+ import { Readable } from "stream";
53
+ import { pipeline } from "stream/promises";
54
+ import { BaseFileProcessor } from "../base/BaseFileProcessor.js";
55
+ import { SIZE_LIMITS_MB } from "../config/index.js";
56
+ import { FileErrorCode } from "../errors/index.js";
57
+ // =============================================================================
58
+ // FFMPEG PATH INITIALIZATION
59
+ // =============================================================================
60
+ /**
61
+ * Whether ffmpeg/ffprobe paths have been initialized.
62
+ * We only attempt path resolution once to avoid repeated dynamic import overhead.
63
+ */
64
+ let ffmpegPathInitialized = false;
65
+ /**
66
+ * Initialize ffmpeg and ffprobe binary paths.
67
+ * Tries ffmpeg-static/ffprobe-static first, falls back to system binaries in PATH.
68
+ *
69
+ * This is called lazily on the first processFile() invocation so that the module
70
+ * can be imported without side effects.
71
+ */
72
+ async function initFfmpegPaths() {
73
+ if (ffmpegPathInitialized) {
74
+ return;
75
+ }
76
+ ffmpegPathInitialized = true;
77
+ // Try ffmpeg-static first, fall back to system ffmpeg.
78
+ // IMPORTANT: Verify the binary actually exists before setting the path.
79
+ // On some platforms (e.g., macOS ARM), ffmpeg-static installs the npm package
80
+ // but the pre-built binary download fails silently, leaving a non-existent path.
81
+ // If we set a bad path, ffmpeg commands fail with ENOENT instead of using
82
+ // the perfectly good system ffmpeg in PATH.
83
+ try {
84
+ const ffmpegStatic = await import("ffmpeg-static");
85
+ const ffmpegPath = ffmpegStatic.default;
86
+ if (typeof ffmpegPath === "string" && existsSync(ffmpegPath)) {
87
+ ffmpegCommand.setFfmpegPath(ffmpegPath);
88
+ }
89
+ }
90
+ catch {
91
+ // Use system ffmpeg (already in PATH)
92
+ }
93
+ // Try ffprobe-static first, fall back to system ffprobe
94
+ try {
95
+ const ffprobeStatic = (await import("ffprobe-static"));
96
+ // Direct path property (CommonJS default)
97
+ if (typeof ffprobeStatic["path"] === "string" &&
98
+ existsSync(ffprobeStatic["path"])) {
99
+ ffmpegCommand.setFfprobePath(ffprobeStatic["path"]);
100
+ }
101
+ else if (ffprobeStatic["default"] &&
102
+ typeof ffprobeStatic["default"] === "object" &&
103
+ typeof ffprobeStatic["default"]["path"] ===
104
+ "string") {
105
+ const probePath = ffprobeStatic["default"]["path"];
106
+ if (existsSync(probePath)) {
107
+ ffmpegCommand.setFfprobePath(probePath);
108
+ }
109
+ }
110
+ }
111
+ catch {
112
+ // Use system ffprobe (already in PATH)
113
+ }
114
+ }
115
+ // =============================================================================
116
+ // CONSTANTS
117
+ // =============================================================================
118
+ /**
119
+ * Video processing configuration constants.
120
+ * Controls frame extraction behavior, quality, and timeout limits.
121
+ */
122
+ const VIDEO_CONFIG = {
123
+ /** Maximum number of keyframes to extract from a video */
124
+ MAX_FRAMES: 100,
125
+ /**
126
+ * Frame extraction intervals based on video duration.
127
+ * Shorter videos get more frequent frames; longer videos use wider intervals.
128
+ */
129
+ FRAME_INTERVALS: [
130
+ { maxDuration: 10, intervalSec: 1 }, // 10s → up to 10 frames
131
+ { maxDuration: 30, intervalSec: 2 }, // 30s → up to 15 frames
132
+ { maxDuration: 120, intervalSec: 3 }, // 2min → up to 40 frames
133
+ { maxDuration: 600, intervalSec: 6 }, // 10min → up to 100 frames
134
+ { maxDuration: 1800, intervalSec: 20 }, // 30min → up to 90 frames
135
+ { maxDuration: Infinity, intervalSec: 60 }, // >30min → adaptive kicks in
136
+ ],
137
+ /** Maximum dimension (width or height) for extracted keyframes in pixels */
138
+ FRAME_MAX_DIMENSION: 768,
139
+ /** JPEG quality for extracted keyframes (0-100) */
140
+ FRAME_JPEG_QUALITY: 80,
141
+ /** Timeout for ffmpeg frame extraction / subtitle extraction in milliseconds */
142
+ FFMPEG_TIMEOUT_MS: 120_000,
143
+ /** Timeout for ffprobe metadata extraction in milliseconds */
144
+ FFPROBE_TIMEOUT_MS: 10_000,
145
+ };
146
+ /** Supported video MIME types */
147
+ const SUPPORTED_VIDEO_MIME_TYPES = [
148
+ "video/mp4",
149
+ "video/x-matroska",
150
+ "video/quicktime",
151
+ "video/webm",
152
+ "video/x-msvideo",
153
+ "video/x-ms-wmv",
154
+ "video/x-flv",
155
+ "video/3gpp",
156
+ "video/3gpp2",
157
+ "video/MP2T",
158
+ "video/ogg",
159
+ ];
160
+ /** Supported video file extensions */
161
+ const SUPPORTED_VIDEO_EXTENSIONS = [
162
+ ".mp4",
163
+ ".m4v",
164
+ ".mkv",
165
+ ".mov",
166
+ ".avi",
167
+ ".wmv",
168
+ ".flv",
169
+ ".webm",
170
+ ".3gp",
171
+ ".3g2",
172
+ ".ts",
173
+ ".mts",
174
+ ".m2ts",
175
+ ".ogv",
176
+ ".vob",
177
+ ];
178
+ /**
179
+ * Maximum video file size in MB.
180
+ * Uses VIDEO_MAX_MB (500 MB) to support long meeting recordings and screen captures.
181
+ */
182
+ const VIDEO_MAX_SIZE_MB = SIZE_LIMITS_MB.VIDEO_MAX_MB;
183
+ /** Default timeout for video download (2 minutes for larger files) */
184
+ const VIDEO_DOWNLOAD_TIMEOUT_MS = 120_000;
185
+ // =============================================================================
186
+ // VIDEO PROCESSOR CLASS
187
+ // =============================================================================
188
+ /**
189
+ * Video Processor - extracts metadata, keyframes, and subtitles from video files.
190
+ *
191
+ * Since LLMs cannot process raw video, this processor converts videos into
192
+ * a structured representation consisting of:
193
+ * 1. Text metadata block (duration, resolution, codecs, etc.)
194
+ * 2. Keyframe images (JPEG, resized to 768px max dimension)
195
+ * 3. Subtitle text (if embedded in the video)
196
+ *
197
+ * The processor uses a temp file approach because ffmpeg requires file paths
198
+ * for most operations. Temp files are always cleaned up in finally blocks.
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * const processor = new VideoProcessor();
203
+ * const result = await processor.processFile({
204
+ * id: "video-1",
205
+ * name: "presentation.mp4",
206
+ * mimetype: "video/mp4",
207
+ * size: 15_000_000,
208
+ * buffer: videoBuffer,
209
+ * });
210
+ *
211
+ * if (result.success) {
212
+ * // result.data.textContent - text description for LLM
213
+ * // result.data.keyframes - array of JPEG buffers
214
+ * // result.data.subtitleText - extracted subtitles (if any)
215
+ * }
216
+ * ```
217
+ */
218
+ export class VideoProcessor extends BaseFileProcessor {
219
+ constructor() {
220
+ super({
221
+ maxSizeMB: VIDEO_MAX_SIZE_MB,
222
+ timeoutMs: VIDEO_DOWNLOAD_TIMEOUT_MS,
223
+ supportedMimeTypes: [...SUPPORTED_VIDEO_MIME_TYPES],
224
+ supportedExtensions: [...SUPPORTED_VIDEO_EXTENSIONS],
225
+ fileTypeName: "video",
226
+ defaultFilename: "video.mp4",
227
+ });
228
+ }
229
+ // ===========================================================================
230
+ // ABSTRACT METHOD IMPLEMENTATION
231
+ // ===========================================================================
232
+ /**
233
+ * Build processed result stub.
234
+ * This is a synchronous placeholder - actual processing happens in the
235
+ * overridden processFile method since ffmpeg operations are asynchronous
236
+ * and require temp file I/O.
237
+ *
238
+ * @param buffer - Downloaded file content
239
+ * @param fileInfo - Original file information
240
+ * @returns Empty ProcessedVideo structure
241
+ */
242
+ buildProcessedResult(buffer, fileInfo) {
243
+ return {
244
+ buffer,
245
+ mimetype: fileInfo.mimetype || "video/mp4",
246
+ size: fileInfo.size,
247
+ filename: this.getFilename(fileInfo),
248
+ textContent: "",
249
+ keyframes: [],
250
+ metadata: {
251
+ duration: 0,
252
+ durationFormatted: "0s",
253
+ width: 0,
254
+ height: 0,
255
+ codec: "unknown",
256
+ fps: 0,
257
+ bitrate: 0,
258
+ subtitleTracks: 0,
259
+ fileSize: fileInfo.size,
260
+ },
261
+ hasKeyframes: false,
262
+ frameCount: 0,
263
+ };
264
+ }
265
+ // ===========================================================================
266
+ // MAIN PROCESSING OVERRIDE
267
+ // ===========================================================================
268
+ /**
269
+ * Override processFile for async video processing with ffmpeg.
270
+ *
271
+ * Processing pipeline:
272
+ * 1. Validate file type and size
273
+ * 2. Get buffer (from fileInfo.buffer or download from URL)
274
+ * 3. Write buffer to temp file (ffmpeg requires file paths)
275
+ * 4. Extract metadata using ffprobe
276
+ * 5. Extract keyframes at calculated intervals, resize with sharp
277
+ * 6. Extract subtitle tracks if embedded
278
+ * 7. Build textContent summary for LLM
279
+ * 8. Clean up temp files
280
+ *
281
+ * @param fileInfo - File information with URL or buffer
282
+ * @param options - Optional processing options
283
+ * @returns Processing result with extracted video data or error
284
+ */
285
+ async processFile(fileInfo, options) {
286
+ // Ensure ffmpeg paths are initialized before any processing
287
+ await initFfmpegPaths();
288
+ // Temp directory for this processing run
289
+ const tempDir = join(tmpdir(), `neurolink-video-${randomUUID()}`);
290
+ let tempCreated = false;
291
+ try {
292
+ // Step 1: Validate file type and size
293
+ const validationResult = this.validateFileWithResult(fileInfo);
294
+ if (!validationResult.success) {
295
+ return { success: false, error: validationResult.error };
296
+ }
297
+ // Step 2: Get file buffer
298
+ let buffer;
299
+ if (fileInfo.buffer) {
300
+ buffer = fileInfo.buffer;
301
+ }
302
+ else if (fileInfo.url) {
303
+ const downloadResult = await this.downloadFileWithRetry(fileInfo, options);
304
+ if (!downloadResult.success) {
305
+ return { success: false, error: downloadResult.error };
306
+ }
307
+ if (!downloadResult.data) {
308
+ return {
309
+ success: false,
310
+ error: this.createError(FileErrorCode.DOWNLOAD_FAILED, {
311
+ reason: "Download succeeded but returned no data",
312
+ }),
313
+ };
314
+ }
315
+ buffer = downloadResult.data;
316
+ // Validate actual downloaded size
317
+ if (!this.validateFileSize(buffer.length)) {
318
+ return {
319
+ success: false,
320
+ error: this.createError(FileErrorCode.FILE_TOO_LARGE, {
321
+ sizeMB: (buffer.length / (1024 * 1024)).toFixed(2),
322
+ maxMB: this.config.maxSizeMB,
323
+ type: this.config.fileTypeName,
324
+ }),
325
+ };
326
+ }
327
+ }
328
+ else {
329
+ return {
330
+ success: false,
331
+ error: this.createError(FileErrorCode.DOWNLOAD_FAILED, {
332
+ reason: "No buffer or URL provided for file",
333
+ }),
334
+ };
335
+ }
336
+ // Step 3: Write buffer to temp file (ffmpeg needs a file path)
337
+ await fs.mkdir(tempDir, { recursive: true });
338
+ tempCreated = true;
339
+ const extension = this.getExtensionFromFileInfo(fileInfo);
340
+ const tempVideoPath = join(tempDir, `input${extension}`);
341
+ await this.writeBufferToFile(buffer, tempVideoPath);
342
+ // Step 4: Extract metadata via ffprobe
343
+ const probeResult = await this.probeVideo(tempVideoPath);
344
+ if (!probeResult.success) {
345
+ return {
346
+ success: false,
347
+ error: this.createError(FileErrorCode.PROCESSING_FAILED, {
348
+ fileType: "video",
349
+ reason: probeResult.error,
350
+ }),
351
+ };
352
+ }
353
+ const probeData = probeResult.data;
354
+ const metadata = this.buildMetadata(probeData, buffer.length);
355
+ // Step 5: Extract keyframes
356
+ let keyframes = [];
357
+ try {
358
+ keyframes = await this.extractKeyframes(tempVideoPath, tempDir, metadata.duration);
359
+ }
360
+ catch {
361
+ // Non-fatal: continue without keyframes if extraction fails
362
+ // (e.g., audio-only file in a video container)
363
+ }
364
+ // Step 6: Extract subtitles
365
+ let subtitleText;
366
+ if (metadata.subtitleTracks > 0) {
367
+ try {
368
+ subtitleText = await this.extractSubtitles(tempVideoPath, tempDir);
369
+ }
370
+ catch {
371
+ // Non-fatal: continue without subtitles if extraction fails
372
+ }
373
+ }
374
+ // Step 7: Build textContent for LLM
375
+ const textContent = this.buildTextContent(metadata, keyframes.length, subtitleText, this.getFilename(fileInfo));
376
+ // Step 8: Return structured result
377
+ return {
378
+ success: true,
379
+ data: {
380
+ buffer,
381
+ mimetype: fileInfo.mimetype || "video/mp4",
382
+ size: fileInfo.size,
383
+ filename: this.getFilename(fileInfo),
384
+ textContent,
385
+ keyframes,
386
+ metadata,
387
+ subtitleText,
388
+ hasKeyframes: keyframes.length > 0,
389
+ frameCount: keyframes.length,
390
+ },
391
+ };
392
+ }
393
+ catch (error) {
394
+ return {
395
+ success: false,
396
+ error: this.createError(FileErrorCode.PROCESSING_FAILED, {
397
+ fileType: "video",
398
+ error: error instanceof Error ? error.message : String(error),
399
+ }, error instanceof Error ? error : undefined),
400
+ };
401
+ }
402
+ finally {
403
+ // Step 8: Clean up temp files
404
+ if (tempCreated) {
405
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {
406
+ // Ignore cleanup errors - temp files will be cleaned by OS eventually
407
+ });
408
+ }
409
+ }
410
+ }
411
+ // ===========================================================================
412
+ // METADATA EXTRACTION
413
+ // ===========================================================================
414
+ /**
415
+ * Probe a video file to extract metadata using ffprobe.
416
+ *
417
+ * @param filePath - Path to the video file
418
+ * @returns Success result with probe data or error message
419
+ */
420
+ probeVideo(filePath) {
421
+ return new Promise((resolve) => {
422
+ const timeoutId = setTimeout(() => {
423
+ resolve({
424
+ success: false,
425
+ error: `ffprobe timed out after ${VIDEO_CONFIG.FFPROBE_TIMEOUT_MS}ms`,
426
+ });
427
+ }, VIDEO_CONFIG.FFPROBE_TIMEOUT_MS);
428
+ ffmpegCommand.ffprobe(filePath, (err, data) => {
429
+ clearTimeout(timeoutId);
430
+ if (err) {
431
+ resolve({
432
+ success: false,
433
+ error: `ffprobe failed: ${err.message}`,
434
+ });
435
+ }
436
+ else {
437
+ resolve({ success: true, data });
438
+ }
439
+ });
440
+ });
441
+ }
442
+ /**
443
+ * Build a structured metadata object from ffprobe data.
444
+ *
445
+ * @param probeData - Raw ffprobe output
446
+ * @param fileSize - Original file size in bytes
447
+ * @returns Structured video metadata
448
+ */
449
+ buildMetadata(probeData, fileSize) {
450
+ const videoStream = probeData.streams.find((s) => s.codec_type === "video");
451
+ const audioStream = probeData.streams.find((s) => s.codec_type === "audio");
452
+ const subtitleStreams = probeData.streams.filter((s) => s.codec_type === "subtitle");
453
+ const duration = probeData.format?.duration
454
+ ? parseFloat(String(probeData.format.duration))
455
+ : 0;
456
+ // Parse FPS from r_frame_rate (e.g., "30000/1001" or "25/1")
457
+ let fps = 0;
458
+ if (videoStream?.r_frame_rate) {
459
+ const parts = String(videoStream.r_frame_rate).split("/");
460
+ if (parts.length === 2) {
461
+ const num = parseFloat(parts[0]);
462
+ const den = parseFloat(parts[1]);
463
+ if (den > 0) {
464
+ fps = Math.round((num / den) * 100) / 100;
465
+ }
466
+ }
467
+ else {
468
+ fps = parseFloat(parts[0]) || 0;
469
+ }
470
+ }
471
+ return {
472
+ duration,
473
+ durationFormatted: this.formatDuration(duration),
474
+ width: videoStream?.width ?? 0,
475
+ height: videoStream?.height ?? 0,
476
+ codec: videoStream?.codec_name ?? "unknown",
477
+ fps,
478
+ bitrate: probeData.format?.bit_rate
479
+ ? parseInt(String(probeData.format.bit_rate), 10)
480
+ : 0,
481
+ audioCodec: audioStream?.codec_name,
482
+ audioChannels: audioStream?.channels,
483
+ audioSampleRate: audioStream?.sample_rate
484
+ ? parseInt(String(audioStream.sample_rate), 10)
485
+ : undefined,
486
+ subtitleTracks: subtitleStreams.length,
487
+ fileSize,
488
+ };
489
+ }
490
+ // ===========================================================================
491
+ // KEYFRAME EXTRACTION
492
+ // ===========================================================================
493
+ /**
494
+ * Extract keyframes from a video at calculated intervals.
495
+ *
496
+ * The interval between frames is determined by the video duration:
497
+ * - <= 10s: every 1s (very short clips — dense coverage)
498
+ * - <= 30s: every 2s (short bug clips)
499
+ * - <= 120s: every 5s (standard screen recordings)
500
+ * - <= 600s: every 15s (longer demos)
501
+ * - <= 1800s: every 60s (meeting recordings)
502
+ * - > 1800s: every 180s (full meetings)
503
+ *
504
+ * Results are capped at MAX_FRAMES (100) and each frame is resized
505
+ * to fit within 768x768px while maintaining aspect ratio.
506
+ * The interval is adaptive: if the tier interval would exceed MAX_FRAMES,
507
+ * the interval widens to duration/MAX_FRAMES for full-video coverage.
508
+ *
509
+ * @param videoPath - Path to the video file
510
+ * @param tempDir - Temp directory for frame output
511
+ * @param durationSec - Video duration in seconds
512
+ * @returns Array of JPEG frame buffers
513
+ */
514
+ async extractKeyframes(videoPath, tempDir, durationSec) {
515
+ if (durationSec <= 0) {
516
+ return [];
517
+ }
518
+ // Determine extraction interval based on duration
519
+ const intervalSec = this.getFrameInterval(durationSec);
520
+ // Calculate timestamps to extract
521
+ const timestamps = [];
522
+ for (let t = 0; t < durationSec && timestamps.length < VIDEO_CONFIG.MAX_FRAMES; t += intervalSec) {
523
+ timestamps.push(t);
524
+ }
525
+ if (timestamps.length === 0) {
526
+ // For very short videos, grab at least one frame at t=0
527
+ timestamps.push(0);
528
+ }
529
+ // Extract frames using ffmpeg
530
+ const framesDir = join(tempDir, "frames");
531
+ await fs.mkdir(framesDir, { recursive: true });
532
+ await this.runFfmpegFrameExtraction(videoPath, framesDir, timestamps);
533
+ // Read extracted frames and resize with sharp
534
+ const keyframes = [];
535
+ for (let i = 0; i < timestamps.length; i++) {
536
+ const framePath = join(framesDir, `frame_${String(i + 1).padStart(4, "0")}.jpg`);
537
+ try {
538
+ await fs.access(framePath);
539
+ const rawFrame = await fs.readFile(framePath);
540
+ // Resize to fit within max dimension while preserving aspect ratio
541
+ const resized = await sharp(rawFrame)
542
+ .resize(VIDEO_CONFIG.FRAME_MAX_DIMENSION, VIDEO_CONFIG.FRAME_MAX_DIMENSION, {
543
+ fit: "inside",
544
+ withoutEnlargement: true,
545
+ })
546
+ .jpeg({ quality: VIDEO_CONFIG.FRAME_JPEG_QUALITY })
547
+ .toBuffer();
548
+ keyframes.push(resized);
549
+ }
550
+ catch {
551
+ // Skip individual frame on resize/encode failure
552
+ }
553
+ }
554
+ return keyframes;
555
+ }
556
+ /**
557
+ * Run ffmpeg to extract frames at specified timestamps.
558
+ *
559
+ * Uses the `-vf select` filter to pick frames at exact timestamps,
560
+ * which is more efficient than seeking for each frame individually.
561
+ *
562
+ * @param videoPath - Path to the video file
563
+ * @param outputDir - Directory to write frame files
564
+ * @param timestamps - Array of timestamps in seconds
565
+ */
566
+ runFfmpegFrameExtraction(videoPath, outputDir, timestamps) {
567
+ return new Promise((resolve, reject) => {
568
+ // Build select filter expression: select='eq(n,0)+eq(n,250)+...'
569
+ // Instead, use fps filter for simpler approach - extract at regular intervals
570
+ // using -vf fps=1/interval approach which is more reliable
571
+ // Build timestamp-based filter
572
+ const selectExpr = timestamps
573
+ .map((t) => `gte(t\\,${t})*lt(t\\,${t + 0.5})`)
574
+ .join("+");
575
+ const timeoutId = setTimeout(() => {
576
+ reject(new Error(`ffmpeg frame extraction timed out after ${VIDEO_CONFIG.FFMPEG_TIMEOUT_MS}ms`));
577
+ }, VIDEO_CONFIG.FFMPEG_TIMEOUT_MS);
578
+ ffmpegCommand(videoPath)
579
+ .outputOptions([
580
+ "-vf",
581
+ `select='${selectExpr}',scale='min(${VIDEO_CONFIG.FRAME_MAX_DIMENSION}\\,iw):-2'`,
582
+ "-vsync",
583
+ "vfr",
584
+ "-q:v",
585
+ "3",
586
+ "-frames:v",
587
+ String(timestamps.length),
588
+ ])
589
+ .output(join(outputDir, "frame_%04d.jpg"))
590
+ .on("end", () => {
591
+ clearTimeout(timeoutId);
592
+ resolve();
593
+ })
594
+ .on("error", (err) => {
595
+ clearTimeout(timeoutId);
596
+ reject(err);
597
+ })
598
+ .run();
599
+ });
600
+ }
601
+ /**
602
+ * Determine the frame extraction interval based on video duration.
603
+ *
604
+ * @param durationSec - Video duration in seconds
605
+ * @returns Interval in seconds between extracted frames
606
+ */
607
+ getFrameInterval(durationSec) {
608
+ let intervalSec = 180; // fallback
609
+ for (const tier of VIDEO_CONFIG.FRAME_INTERVALS) {
610
+ if (durationSec <= tier.maxDuration) {
611
+ intervalSec = tier.intervalSec;
612
+ break;
613
+ }
614
+ }
615
+ // Adaptive: if the tier interval would produce more frames than MAX_FRAMES,
616
+ // widen the interval so frames are evenly distributed across the full video
617
+ const estimatedFrames = Math.floor(durationSec / intervalSec);
618
+ if (estimatedFrames > VIDEO_CONFIG.MAX_FRAMES) {
619
+ intervalSec = Math.ceil(durationSec / VIDEO_CONFIG.MAX_FRAMES);
620
+ }
621
+ return intervalSec;
622
+ }
623
+ // ===========================================================================
624
+ // SUBTITLE EXTRACTION
625
+ // ===========================================================================
626
+ /**
627
+ * Extract embedded subtitle text from the first subtitle track.
628
+ *
629
+ * Uses ffmpeg to convert the first subtitle stream to SRT format,
630
+ * then strips SRT formatting (timestamps, sequence numbers) to produce
631
+ * plain text.
632
+ *
633
+ * @param videoPath - Path to the video file
634
+ * @param tempDir - Temp directory for subtitle output
635
+ * @returns Extracted subtitle text, or undefined if extraction fails
636
+ */
637
+ async extractSubtitles(videoPath, tempDir) {
638
+ const subtitlePath = join(tempDir, "subtitles.srt");
639
+ await new Promise((resolve, reject) => {
640
+ const timeoutId = setTimeout(() => {
641
+ reject(new Error(`ffmpeg subtitle extraction timed out after ${VIDEO_CONFIG.FFMPEG_TIMEOUT_MS}ms`));
642
+ }, VIDEO_CONFIG.FFMPEG_TIMEOUT_MS);
643
+ ffmpegCommand(videoPath)
644
+ .outputOptions(["-map", "0:s:0", "-c:s", "srt"])
645
+ .output(subtitlePath)
646
+ .on("end", () => {
647
+ clearTimeout(timeoutId);
648
+ resolve();
649
+ })
650
+ .on("error", (err) => {
651
+ clearTimeout(timeoutId);
652
+ reject(err);
653
+ })
654
+ .run();
655
+ });
656
+ try {
657
+ const srtContent = await fs.readFile(subtitlePath, "utf-8");
658
+ return this.parseSrtToPlainText(srtContent);
659
+ }
660
+ catch {
661
+ return undefined;
662
+ }
663
+ }
664
+ /**
665
+ * Parse SRT subtitle content into plain text.
666
+ * Strips sequence numbers, timestamps, and blank lines.
667
+ *
668
+ * @param srt - Raw SRT content
669
+ * @returns Plain text from subtitles
670
+ */
671
+ parseSrtToPlainText(srt) {
672
+ if (!srt.trim()) {
673
+ return "";
674
+ }
675
+ return srt
676
+ .split("\n")
677
+ .filter((line) => {
678
+ const trimmed = line.trim();
679
+ // Skip empty lines
680
+ if (!trimmed) {
681
+ return false;
682
+ }
683
+ // Skip sequence numbers (pure digits)
684
+ if (/^\d+$/.test(trimmed)) {
685
+ return false;
686
+ }
687
+ // Skip timestamp lines (e.g., "00:01:23,456 --> 00:01:25,789")
688
+ if (/^\d{2}:\d{2}:\d{2}[,.]\d{3}\s*-->/.test(trimmed)) {
689
+ return false;
690
+ }
691
+ return true;
692
+ })
693
+ .map((line) => line.trim())
694
+ .join("\n")
695
+ .trim();
696
+ }
697
+ // ===========================================================================
698
+ // TEXT CONTENT BUILDER
699
+ // ===========================================================================
700
+ /**
701
+ * Build a structured text description of the video for LLM consumption.
702
+ *
703
+ * The output includes:
704
+ * - File name and basic info
705
+ * - Technical metadata (resolution, codec, duration, etc.)
706
+ * - Frame extraction summary
707
+ * - Subtitle text (if available)
708
+ *
709
+ * @param metadata - Extracted video metadata
710
+ * @param frameCount - Number of keyframes extracted
711
+ * @param subtitleText - Extracted subtitle text (if any)
712
+ * @param filename - Original filename
713
+ * @returns Formatted text content for the LLM
714
+ */
715
+ buildTextContent(metadata, frameCount, subtitleText, filename) {
716
+ const lines = [];
717
+ lines.push(`[Video File: ${filename}]`);
718
+ lines.push("");
719
+ lines.push("## Video Metadata");
720
+ lines.push(`- Duration: ${metadata.durationFormatted}`);
721
+ lines.push(`- Resolution: ${metadata.width}x${metadata.height}`);
722
+ lines.push(`- Video Codec: ${metadata.codec}`);
723
+ if (metadata.fps > 0) {
724
+ lines.push(`- Frame Rate: ${metadata.fps} fps`);
725
+ }
726
+ if (metadata.bitrate > 0) {
727
+ lines.push(`- Bitrate: ${(metadata.bitrate / 1000).toFixed(0)} kbps`);
728
+ }
729
+ if (metadata.audioCodec) {
730
+ lines.push(`- Audio Codec: ${metadata.audioCodec}`);
731
+ if (metadata.audioChannels) {
732
+ lines.push(`- Audio Channels: ${metadata.audioChannels === 1 ? "mono" : metadata.audioChannels === 2 ? "stereo" : `${metadata.audioChannels}ch`}`);
733
+ }
734
+ if (metadata.audioSampleRate) {
735
+ lines.push(`- Audio Sample Rate: ${(metadata.audioSampleRate / 1000).toFixed(1)} kHz`);
736
+ }
737
+ }
738
+ lines.push(`- File Size: ${(metadata.fileSize / (1024 * 1024)).toFixed(1)} MB`);
739
+ lines.push("");
740
+ if (frameCount > 0) {
741
+ const intervalSec = this.getFrameInterval(metadata.duration);
742
+ lines.push(`## Keyframes (${frameCount} frames extracted every ~${intervalSec}s)`);
743
+ lines.push("The following images are keyframes extracted from the video at regular intervals.");
744
+ }
745
+ else {
746
+ lines.push("## Keyframes");
747
+ lines.push("No keyframes could be extracted from this video (it may be audio-only or use an unsupported codec).");
748
+ }
749
+ if (subtitleText) {
750
+ lines.push("");
751
+ lines.push("## Subtitles / Captions");
752
+ // Truncate very long subtitle text to avoid blowing up context
753
+ const maxSubtitleChars = 10_000;
754
+ if (subtitleText.length > maxSubtitleChars) {
755
+ lines.push(subtitleText.substring(0, maxSubtitleChars) +
756
+ `\n... [truncated, ${subtitleText.length - maxSubtitleChars} more characters]`);
757
+ }
758
+ else {
759
+ lines.push(subtitleText);
760
+ }
761
+ }
762
+ return lines.join("\n");
763
+ }
764
+ // ===========================================================================
765
+ // UTILITY METHODS
766
+ // ===========================================================================
767
+ /**
768
+ * Format a duration in seconds to a human-readable string.
769
+ *
770
+ * @param seconds - Duration in seconds
771
+ * @returns Formatted string (e.g., "1h 23m 45s")
772
+ */
773
+ formatDuration(seconds) {
774
+ if (seconds <= 0) {
775
+ return "0s";
776
+ }
777
+ const hours = Math.floor(seconds / 3600);
778
+ const minutes = Math.floor((seconds % 3600) / 60);
779
+ const secs = Math.floor(seconds % 60);
780
+ const parts = [];
781
+ if (hours > 0) {
782
+ parts.push(`${hours}h`);
783
+ }
784
+ if (minutes > 0) {
785
+ parts.push(`${minutes}m`);
786
+ }
787
+ if (secs > 0 || parts.length === 0) {
788
+ parts.push(`${secs}s`);
789
+ }
790
+ return parts.join(" ");
791
+ }
792
+ /**
793
+ * Get a file extension from FileInfo, falling back to ".mp4".
794
+ *
795
+ * @param fileInfo - File information
796
+ * @returns File extension with leading dot
797
+ */
798
+ getExtensionFromFileInfo(fileInfo) {
799
+ const name = fileInfo.name || "";
800
+ const dotIndex = name.lastIndexOf(".");
801
+ if (dotIndex >= 0) {
802
+ return name.substring(dotIndex).toLowerCase();
803
+ }
804
+ // Fallback: derive from MIME type
805
+ const mimeExtMap = {
806
+ "video/mp4": ".mp4",
807
+ "video/x-matroska": ".mkv",
808
+ "video/quicktime": ".mov",
809
+ "video/webm": ".webm",
810
+ "video/x-msvideo": ".avi",
811
+ "video/x-ms-wmv": ".wmv",
812
+ "video/x-flv": ".flv",
813
+ "video/3gpp": ".3gp",
814
+ "video/3gpp2": ".3g2",
815
+ "video/MP2T": ".ts",
816
+ "video/ogg": ".ogv",
817
+ };
818
+ return mimeExtMap[fileInfo.mimetype] || ".mp4";
819
+ }
820
+ /**
821
+ * Write a buffer to a file using streaming to handle large files efficiently.
822
+ *
823
+ * @param buffer - Buffer to write
824
+ * @param filePath - Destination file path
825
+ */
826
+ async writeBufferToFile(buffer, filePath) {
827
+ const readable = Readable.from(buffer);
828
+ const writable = createWriteStream(filePath);
829
+ await pipeline(readable, writable);
830
+ }
831
+ // ===========================================================================
832
+ // TARGETED EXTRACTION API
833
+ // ===========================================================================
834
+ /**
835
+ * Extract frames from a specific time range in a video.
836
+ *
837
+ * This is the on-demand extraction method called by the `extract_file_content`
838
+ * tool. Unlike initial keyframe extraction (which covers the full video),
839
+ * this targets a specific time window with configurable frame count.
840
+ *
841
+ * @param buffer - Video file buffer
842
+ * @param filename - Original filename (for extension detection)
843
+ * @param startSec - Start time in seconds
844
+ * @param endSec - End time in seconds
845
+ * @param frameCount - Number of frames to extract in the range (default: 5)
846
+ * @returns Array of JPEG frame buffers
847
+ */
848
+ async extractFrameRange(buffer, filename, startSec, endSec, frameCount = 5) {
849
+ await initFfmpegPaths();
850
+ const tempDir = join(tmpdir(), `neurolink-video-extract-${randomUUID()}`);
851
+ try {
852
+ await fs.mkdir(tempDir, { recursive: true });
853
+ // Write buffer to temp file
854
+ const ext = this.guessExtensionFromName(filename);
855
+ const tempVideoPath = join(tempDir, `input${ext}`);
856
+ await this.writeBufferToFile(buffer, tempVideoPath);
857
+ // Calculate evenly-spaced timestamps within the range
858
+ const duration = endSec - startSec;
859
+ if (duration <= 0) {
860
+ return [];
861
+ }
862
+ const clampedCount = Math.min(frameCount, VIDEO_CONFIG.MAX_FRAMES);
863
+ const timestamps = [];
864
+ if (clampedCount === 1) {
865
+ timestamps.push(startSec);
866
+ }
867
+ else {
868
+ const step = duration / (clampedCount - 1);
869
+ for (let i = 0; i < clampedCount; i++) {
870
+ timestamps.push(startSec + step * i);
871
+ }
872
+ }
873
+ // Extract frames
874
+ const framesDir = join(tempDir, "frames");
875
+ await fs.mkdir(framesDir, { recursive: true });
876
+ await this.runFfmpegFrameExtraction(tempVideoPath, framesDir, timestamps);
877
+ // Read and resize frames
878
+ const keyframes = [];
879
+ for (let i = 0; i < timestamps.length; i++) {
880
+ const framePath = join(framesDir, `frame_${String(i + 1).padStart(4, "0")}.jpg`);
881
+ try {
882
+ await fs.access(framePath);
883
+ const rawFrame = await fs.readFile(framePath);
884
+ const resized = await sharp(rawFrame)
885
+ .resize(VIDEO_CONFIG.FRAME_MAX_DIMENSION, VIDEO_CONFIG.FRAME_MAX_DIMENSION, {
886
+ fit: "inside",
887
+ withoutEnlargement: true,
888
+ })
889
+ .jpeg({ quality: VIDEO_CONFIG.FRAME_JPEG_QUALITY })
890
+ .toBuffer();
891
+ keyframes.push(resized);
892
+ }
893
+ catch {
894
+ // Skip individual frame failures
895
+ }
896
+ }
897
+ return keyframes;
898
+ }
899
+ finally {
900
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {
901
+ /* cleanup - ignore temp dir removal errors */
902
+ });
903
+ }
904
+ }
905
+ /**
906
+ * Guess file extension from filename, with fallback to .mp4.
907
+ */
908
+ guessExtensionFromName(filename) {
909
+ const dotIndex = filename.lastIndexOf(".");
910
+ if (dotIndex >= 0) {
911
+ return filename.substring(dotIndex).toLowerCase();
912
+ }
913
+ return ".mp4";
914
+ }
915
+ }
916
+ // =============================================================================
917
+ // SINGLETON INSTANCE
918
+ // =============================================================================
919
+ /**
920
+ * Singleton Video processor instance.
921
+ * Use this for standard video processing operations.
922
+ *
923
+ * @example
924
+ * ```typescript
925
+ * import { videoProcessor } from "./VideoProcessor.js";
926
+ *
927
+ * const result = await videoProcessor.processFile(fileInfo);
928
+ * ```
929
+ */
930
+ export const videoProcessor = new VideoProcessor();
931
+ // =============================================================================
932
+ // HELPER FUNCTIONS
933
+ // =============================================================================
934
+ /**
935
+ * Check if a file is a video file.
936
+ * Matches by MIME type or file extension.
937
+ *
938
+ * @param mimetype - MIME type of the file
939
+ * @param filename - Filename (for extension-based detection)
940
+ * @returns true if the file is a supported video file
941
+ *
942
+ * @example
943
+ * ```typescript
944
+ * if (isVideoFile("video/mp4", "recording.mp4")) {
945
+ * const result = await processVideo(fileInfo);
946
+ * }
947
+ *
948
+ * if (isVideoFile("", "clip.mkv")) {
949
+ * // Also matches by extension
950
+ * }
951
+ * ```
952
+ */
953
+ export function isVideoFile(mimetype, filename) {
954
+ return videoProcessor.isFileSupported(mimetype, filename);
955
+ }
956
+ /**
957
+ * Process a single video file.
958
+ * Convenience function that uses the singleton processor.
959
+ *
960
+ * @param fileInfo - File information (can include URL or buffer)
961
+ * @param options - Optional processing options (auth headers, timeout, retry config)
962
+ * @returns Processing result with extracted video data or error
963
+ *
964
+ * @example
965
+ * ```typescript
966
+ * import { processVideo } from "./VideoProcessor.js";
967
+ *
968
+ * const result = await processVideo({
969
+ * id: "vid-123",
970
+ * name: "demo.mp4",
971
+ * mimetype: "video/mp4",
972
+ * size: 15_000_000,
973
+ * buffer: videoBuffer,
974
+ * });
975
+ *
976
+ * if (result.success) {
977
+ * console.log(`Duration: ${result.data.metadata.durationFormatted}`);
978
+ * console.log(`Extracted ${result.data.frameCount} keyframes`);
979
+ * console.log(`Text content:\n${result.data.textContent}`);
980
+ *
981
+ * if (result.data.subtitleText) {
982
+ * console.log(`Subtitles:\n${result.data.subtitleText}`);
983
+ * }
984
+ * } else {
985
+ * console.error(`Processing failed: ${result.error?.userMessage}`);
986
+ * }
987
+ * ```
988
+ */
989
+ export async function processVideo(fileInfo, options) {
990
+ return videoProcessor.processFile(fileInfo, options);
991
+ }
992
+ //# sourceMappingURL=VideoProcessor.js.map