@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.
- package/CHANGELOG.md +16 -0
- package/README.md +29 -25
- package/dist/adapters/video/vertexVideoHandler.js +3 -3
- package/dist/agent/directTools.d.ts +5 -5
- package/dist/cli/commands/config.d.ts +9 -9
- package/dist/cli/commands/serve.d.ts +37 -0
- package/dist/cli/commands/serve.js +302 -229
- package/dist/cli/commands/setup-anthropic.d.ts +2 -2
- package/dist/cli/commands/setup-azure.d.ts +2 -2
- package/dist/cli/commands/setup-bedrock.d.ts +2 -2
- package/dist/cli/commands/setup-gcp.d.ts +2 -2
- package/dist/cli/commands/setup-google-ai.d.ts +2 -2
- package/dist/cli/commands/setup-huggingface.d.ts +2 -2
- package/dist/cli/commands/setup-mistral.d.ts +2 -2
- package/dist/cli/commands/setup-openai.d.ts +2 -2
- package/dist/cli/commands/setup.d.ts +2 -2
- package/dist/cli/factories/commandFactory.js +16 -2
- package/dist/cli/loop/optionsSchema.d.ts +2 -2
- package/dist/cli/loop/optionsSchema.js +4 -0
- package/dist/cli/loop/session.d.ts +4 -0
- package/dist/cli/loop/session.js +49 -4
- package/dist/cli/utils/interactiveSetup.d.ts +4 -4
- package/dist/config/conversationMemory.d.ts +2 -0
- package/dist/config/conversationMemory.js +5 -5
- package/dist/constants/contextWindows.d.ts +46 -0
- package/dist/constants/contextWindows.js +156 -0
- package/dist/context/budgetChecker.d.ts +18 -0
- package/dist/context/budgetChecker.js +71 -0
- package/dist/context/contextCompactor.d.ts +22 -0
- package/dist/context/contextCompactor.js +106 -0
- package/dist/context/effectiveHistory.d.ts +52 -0
- package/dist/context/effectiveHistory.js +105 -0
- package/dist/context/errorDetection.d.ts +14 -0
- package/dist/context/errorDetection.js +124 -0
- package/dist/context/fileSummarizationService.d.ts +54 -0
- package/dist/context/fileSummarizationService.js +255 -0
- package/dist/context/fileSummarizer.d.ts +56 -0
- package/dist/context/fileSummarizer.js +145 -0
- package/dist/context/fileTokenBudget.d.ts +53 -0
- package/dist/context/fileTokenBudget.js +127 -0
- package/dist/context/prompts/summarizationPrompt.d.ts +17 -0
- package/dist/context/prompts/summarizationPrompt.js +110 -0
- package/dist/context/stages/fileReadDeduplicator.d.ts +10 -0
- package/dist/context/stages/fileReadDeduplicator.js +66 -0
- package/dist/context/stages/slidingWindowTruncator.d.ts +11 -0
- package/dist/context/stages/slidingWindowTruncator.js +42 -0
- package/dist/context/stages/structuredSummarizer.d.ts +10 -0
- package/dist/context/stages/structuredSummarizer.js +49 -0
- package/dist/context/stages/toolOutputPruner.d.ts +10 -0
- package/dist/context/stages/toolOutputPruner.js +52 -0
- package/dist/context/summarizationEngine.d.ts +45 -0
- package/dist/context/summarizationEngine.js +110 -0
- package/dist/context/toolOutputLimits.d.ts +17 -0
- package/dist/context/toolOutputLimits.js +84 -0
- package/dist/context/toolPairRepair.d.ts +16 -0
- package/dist/context/toolPairRepair.js +66 -0
- package/dist/core/analytics.js +11 -4
- package/dist/core/baseProvider.d.ts +6 -0
- package/dist/core/baseProvider.js +83 -14
- package/dist/core/conversationMemoryManager.d.ts +14 -11
- package/dist/core/conversationMemoryManager.js +36 -68
- package/dist/core/dynamicModels.js +3 -2
- package/dist/core/modules/GenerationHandler.js +2 -0
- package/dist/core/modules/MessageBuilder.d.ts +1 -1
- package/dist/core/modules/MessageBuilder.js +2 -0
- package/dist/core/modules/TelemetryHandler.d.ts +2 -3
- package/dist/core/modules/TelemetryHandler.js +3 -3
- package/dist/core/modules/ToolsManager.d.ts +2 -2
- package/dist/core/redisConversationMemoryManager.d.ts +19 -14
- package/dist/core/redisConversationMemoryManager.js +94 -86
- package/dist/factories/providerFactory.d.ts +2 -2
- package/dist/files/fileReferenceRegistry.d.ts +276 -0
- package/dist/files/fileReferenceRegistry.js +1543 -0
- package/dist/files/fileTools.d.ts +423 -0
- package/dist/files/fileTools.js +449 -0
- package/dist/files/index.d.ts +14 -0
- package/dist/files/index.js +13 -0
- package/dist/files/streamingReader.d.ts +93 -0
- package/dist/files/streamingReader.js +321 -0
- package/dist/files/types.d.ts +23 -0
- package/dist/files/types.js +23 -0
- package/dist/image-gen/imageGenTools.d.ts +2 -2
- package/dist/image-gen/types.d.ts +12 -12
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/lib/adapters/video/vertexVideoHandler.js +3 -3
- package/dist/lib/agent/directTools.d.ts +7 -7
- package/dist/lib/config/conversationMemory.d.ts +2 -0
- package/dist/lib/config/conversationMemory.js +5 -5
- package/dist/lib/constants/contextWindows.d.ts +46 -0
- package/dist/lib/constants/contextWindows.js +157 -0
- package/dist/lib/context/budgetChecker.d.ts +18 -0
- package/dist/lib/context/budgetChecker.js +72 -0
- package/dist/lib/context/contextCompactor.d.ts +22 -0
- package/dist/lib/context/contextCompactor.js +107 -0
- package/dist/lib/context/effectiveHistory.d.ts +52 -0
- package/dist/lib/context/effectiveHistory.js +106 -0
- package/dist/lib/context/errorDetection.d.ts +14 -0
- package/dist/lib/context/errorDetection.js +125 -0
- package/dist/lib/context/fileSummarizationService.d.ts +54 -0
- package/dist/lib/context/fileSummarizationService.js +256 -0
- package/dist/lib/context/fileSummarizer.d.ts +56 -0
- package/dist/lib/context/fileSummarizer.js +146 -0
- package/dist/lib/context/fileTokenBudget.d.ts +53 -0
- package/dist/lib/context/fileTokenBudget.js +128 -0
- package/dist/lib/context/prompts/summarizationPrompt.d.ts +17 -0
- package/dist/lib/context/prompts/summarizationPrompt.js +111 -0
- package/dist/lib/context/stages/fileReadDeduplicator.d.ts +10 -0
- package/dist/lib/context/stages/fileReadDeduplicator.js +67 -0
- package/dist/lib/context/stages/slidingWindowTruncator.d.ts +11 -0
- package/dist/lib/context/stages/slidingWindowTruncator.js +43 -0
- package/dist/lib/context/stages/structuredSummarizer.d.ts +10 -0
- package/dist/lib/context/stages/structuredSummarizer.js +50 -0
- package/dist/lib/context/stages/toolOutputPruner.d.ts +10 -0
- package/dist/lib/context/stages/toolOutputPruner.js +53 -0
- package/dist/lib/context/summarizationEngine.d.ts +45 -0
- package/dist/lib/context/summarizationEngine.js +111 -0
- package/dist/lib/context/toolOutputLimits.d.ts +17 -0
- package/dist/lib/context/toolOutputLimits.js +85 -0
- package/dist/lib/context/toolPairRepair.d.ts +16 -0
- package/dist/lib/context/toolPairRepair.js +67 -0
- package/dist/lib/core/analytics.js +11 -4
- package/dist/lib/core/baseProvider.d.ts +6 -0
- package/dist/lib/core/baseProvider.js +83 -14
- package/dist/lib/core/conversationMemoryManager.d.ts +14 -11
- package/dist/lib/core/conversationMemoryManager.js +36 -68
- package/dist/lib/core/dynamicModels.js +3 -2
- package/dist/lib/core/modules/GenerationHandler.js +2 -0
- package/dist/lib/core/modules/MessageBuilder.d.ts +1 -1
- package/dist/lib/core/modules/MessageBuilder.js +2 -0
- package/dist/lib/core/modules/TelemetryHandler.d.ts +2 -3
- package/dist/lib/core/modules/TelemetryHandler.js +3 -3
- package/dist/lib/core/modules/ToolsManager.d.ts +2 -2
- package/dist/lib/core/redisConversationMemoryManager.d.ts +19 -14
- package/dist/lib/core/redisConversationMemoryManager.js +94 -86
- package/dist/lib/factories/providerFactory.d.ts +2 -2
- package/dist/lib/files/fileReferenceRegistry.d.ts +276 -0
- package/dist/lib/files/fileReferenceRegistry.js +1544 -0
- package/dist/lib/files/fileTools.d.ts +423 -0
- package/dist/lib/files/fileTools.js +450 -0
- package/dist/lib/files/index.d.ts +14 -0
- package/dist/lib/files/index.js +14 -0
- package/dist/lib/files/streamingReader.d.ts +93 -0
- package/dist/lib/files/streamingReader.js +322 -0
- package/dist/lib/files/types.d.ts +23 -0
- package/dist/lib/files/types.js +24 -0
- package/dist/lib/image-gen/imageGenTools.d.ts +2 -2
- package/dist/lib/image-gen/types.d.ts +12 -12
- package/dist/lib/index.d.ts +4 -0
- package/dist/lib/index.js +5 -0
- package/dist/lib/mcp/httpRetryHandler.js +6 -2
- package/dist/lib/memory/mem0Initializer.d.ts +2 -2
- package/dist/lib/neurolink.d.ts +66 -2
- package/dist/lib/neurolink.js +777 -315
- package/dist/lib/processors/archive/ArchiveProcessor.d.ts +327 -0
- package/dist/lib/processors/archive/ArchiveProcessor.js +1309 -0
- package/dist/lib/processors/archive/index.d.ts +33 -0
- package/dist/lib/processors/archive/index.js +43 -0
- package/dist/lib/processors/base/BaseFileProcessor.js +2 -1
- package/dist/lib/processors/base/types.d.ts +70 -64
- package/dist/lib/processors/base/types.js +6 -0
- package/dist/lib/processors/cli/fileProcessorCli.d.ts +8 -8
- package/dist/lib/processors/cli/fileProcessorCli.js +5 -5
- package/dist/lib/processors/config/mimeTypes.js +25 -0
- package/dist/lib/processors/config/sizeLimits.d.ts +52 -40
- package/dist/lib/processors/config/sizeLimits.js +56 -44
- package/dist/lib/processors/document/ExcelProcessor.d.ts +14 -0
- package/dist/lib/processors/document/ExcelProcessor.js +72 -1
- package/dist/lib/processors/document/PptxProcessor.d.ts +63 -0
- package/dist/lib/processors/document/PptxProcessor.js +158 -0
- package/dist/lib/processors/document/index.d.ts +1 -0
- package/dist/lib/processors/document/index.js +6 -0
- package/dist/lib/processors/errors/FileErrorCode.d.ts +2 -2
- package/dist/lib/processors/errors/errorHelpers.d.ts +2 -2
- package/dist/lib/processors/errors/errorHelpers.js +12 -4
- package/dist/lib/processors/errors/errorSerializer.d.ts +4 -4
- package/dist/lib/processors/index.d.ts +8 -2
- package/dist/lib/processors/index.js +5 -2
- package/dist/lib/processors/integration/FileProcessorIntegration.d.ts +8 -8
- package/dist/lib/processors/integration/FileProcessorIntegration.js +7 -7
- package/dist/lib/processors/media/AudioProcessor.d.ts +328 -0
- package/dist/lib/processors/media/AudioProcessor.js +708 -0
- package/dist/lib/processors/media/VideoProcessor.d.ts +350 -0
- package/dist/lib/processors/media/VideoProcessor.js +992 -0
- package/dist/lib/processors/media/index.d.ts +27 -0
- package/dist/lib/processors/media/index.js +37 -0
- package/dist/lib/processors/registry/ProcessorRegistry.d.ts +19 -5
- package/dist/lib/processors/registry/ProcessorRegistry.js +103 -8
- package/dist/lib/processors/registry/index.d.ts +1 -1
- package/dist/lib/processors/registry/index.js +1 -1
- package/dist/lib/processors/registry/types.d.ts +2 -2
- package/dist/lib/providers/amazonBedrock.js +2 -1
- package/dist/lib/providers/anthropic.js +2 -2
- package/dist/lib/providers/anthropicBaseProvider.js +10 -4
- package/dist/lib/providers/azureOpenai.js +14 -25
- package/dist/lib/providers/googleAiStudio.js +136 -457
- package/dist/lib/providers/googleNativeGemini3.d.ts +119 -0
- package/dist/lib/providers/googleNativeGemini3.js +264 -0
- package/dist/lib/providers/googleVertex.d.ts +15 -1
- package/dist/lib/providers/googleVertex.js +341 -775
- package/dist/lib/providers/huggingFace.js +20 -5
- package/dist/lib/providers/litellm.js +6 -4
- package/dist/lib/providers/mistral.js +3 -2
- package/dist/lib/providers/openAI.js +2 -2
- package/dist/lib/providers/openRouter.js +8 -7
- package/dist/lib/providers/openaiCompatible.js +10 -4
- package/dist/lib/providers/sagemaker/detection.d.ts +6 -6
- package/dist/lib/providers/sagemaker/diagnostics.d.ts +4 -4
- package/dist/lib/providers/sagemaker/parsers.d.ts +4 -4
- package/dist/lib/rag/chunkers/RecursiveChunker.js +2 -2
- package/dist/lib/rag/document/loaders.d.ts +6 -71
- package/dist/lib/rag/document/loaders.js +5 -5
- package/dist/lib/rag/graphRag/graphRAG.js +26 -9
- package/dist/lib/rag/metadata/MetadataExtractorFactory.d.ts +5 -55
- package/dist/lib/rag/metadata/metadataExtractor.js +6 -3
- package/dist/lib/rag/pipeline/RAGPipeline.d.ts +8 -126
- package/dist/lib/rag/pipeline/RAGPipeline.js +11 -11
- package/dist/lib/rag/pipeline/contextAssembly.d.ts +3 -42
- package/dist/lib/rag/pipeline/contextAssembly.js +6 -3
- package/dist/lib/rag/reranker/RerankerFactory.d.ts +5 -60
- package/dist/lib/rag/resilience/CircuitBreaker.d.ts +3 -33
- package/dist/lib/rag/resilience/RetryHandler.d.ts +2 -21
- package/dist/lib/rag/resilience/RetryHandler.js +6 -2
- package/dist/lib/rag/retrieval/hybridSearch.d.ts +3 -41
- package/dist/lib/rag/retrieval/vectorQueryTool.d.ts +2 -13
- package/dist/lib/rag/retrieval/vectorQueryTool.js +4 -3
- package/dist/lib/rag/types.d.ts +3 -3
- package/dist/lib/sdk/toolRegistration.d.ts +2 -2
- package/dist/lib/server/middleware/cache.d.ts +2 -2
- package/dist/lib/server/middleware/rateLimit.d.ts +2 -2
- package/dist/lib/server/routes/mcpRoutes.js +277 -249
- package/dist/lib/server/routes/memoryRoutes.js +287 -281
- package/dist/lib/server/utils/validation.d.ts +10 -10
- package/dist/lib/services/server/ai/observability/instrumentation.d.ts +24 -2
- package/dist/lib/services/server/ai/observability/instrumentation.js +12 -1
- package/dist/lib/session/globalSessionState.d.ts +2 -2
- package/dist/lib/telemetry/telemetryService.d.ts +2 -2
- package/dist/lib/types/common.d.ts +39 -0
- package/dist/lib/types/contextTypes.d.ts +255 -0
- package/dist/lib/types/contextTypes.js +0 -2
- package/dist/lib/types/conversation.d.ts +62 -0
- package/dist/lib/types/conversationMemoryInterface.d.ts +27 -0
- package/dist/lib/types/conversationMemoryInterface.js +7 -0
- package/dist/lib/types/fileReferenceTypes.d.ts +222 -0
- package/dist/lib/types/fileReferenceTypes.js +9 -0
- package/dist/lib/types/fileTypes.d.ts +26 -3
- package/dist/lib/types/generateTypes.d.ts +50 -1
- package/dist/lib/types/index.d.ts +4 -5
- package/dist/lib/types/index.js +8 -10
- package/dist/lib/types/modelTypes.d.ts +2 -2
- package/dist/lib/types/processorTypes.d.ts +597 -0
- package/dist/lib/types/processorTypes.js +91 -0
- package/dist/lib/types/ragTypes.d.ts +489 -0
- package/dist/lib/types/ragTypes.js +8 -0
- package/dist/lib/types/sdkTypes.d.ts +17 -18
- package/dist/lib/types/streamTypes.d.ts +24 -1
- package/dist/lib/utils/async/retry.d.ts +2 -2
- package/dist/lib/utils/async/withTimeout.js +3 -1
- package/dist/lib/utils/conversationMemory.d.ts +12 -6
- package/dist/lib/utils/conversationMemory.js +91 -36
- package/dist/lib/utils/errorHandling.d.ts +5 -0
- package/dist/lib/utils/errorHandling.js +19 -0
- package/dist/lib/utils/fileDetector.d.ts +62 -0
- package/dist/lib/utils/fileDetector.js +1014 -14
- package/dist/lib/utils/json/safeParse.d.ts +2 -2
- package/dist/lib/utils/messageBuilder.js +806 -153
- package/dist/lib/utils/modelChoices.d.ts +2 -2
- package/dist/lib/utils/multimodalOptionsBuilder.d.ts +2 -1
- package/dist/lib/utils/multimodalOptionsBuilder.js +1 -0
- package/dist/lib/utils/pricing.d.ts +12 -0
- package/dist/lib/utils/pricing.js +134 -0
- package/dist/lib/utils/rateLimiter.d.ts +2 -2
- package/dist/lib/utils/redis.d.ts +17 -0
- package/dist/lib/utils/redis.js +105 -0
- package/dist/lib/utils/sanitizers/filename.d.ts +4 -4
- package/dist/lib/utils/sanitizers/svg.d.ts +2 -2
- package/dist/lib/utils/thinkingConfig.d.ts +6 -6
- package/dist/lib/utils/timeout.d.ts +10 -0
- package/dist/lib/utils/timeout.js +15 -0
- package/dist/lib/utils/tokenEstimation.d.ts +68 -0
- package/dist/lib/utils/tokenEstimation.js +113 -0
- package/dist/lib/utils/tokenUtils.d.ts +4 -4
- package/dist/lib/utils/ttsProcessor.d.ts +2 -2
- package/dist/lib/workflow/config.d.ts +150 -150
- package/dist/mcp/httpRetryHandler.js +6 -2
- package/dist/memory/mem0Initializer.d.ts +2 -2
- package/dist/neurolink.d.ts +66 -2
- package/dist/neurolink.js +777 -315
- package/dist/processors/archive/ArchiveProcessor.d.ts +327 -0
- package/dist/processors/archive/ArchiveProcessor.js +1308 -0
- package/dist/processors/archive/index.d.ts +33 -0
- package/dist/processors/archive/index.js +42 -0
- package/dist/processors/base/BaseFileProcessor.js +2 -1
- package/dist/processors/base/types.d.ts +70 -64
- package/dist/processors/base/types.js +6 -0
- package/dist/processors/cli/fileProcessorCli.d.ts +8 -8
- package/dist/processors/cli/fileProcessorCli.js +5 -5
- package/dist/processors/config/mimeTypes.js +25 -0
- package/dist/processors/config/sizeLimits.d.ts +52 -40
- package/dist/processors/config/sizeLimits.js +56 -44
- package/dist/processors/document/ExcelProcessor.d.ts +14 -0
- package/dist/processors/document/ExcelProcessor.js +72 -1
- package/dist/processors/document/PptxProcessor.d.ts +63 -0
- package/dist/processors/document/PptxProcessor.js +157 -0
- package/dist/processors/document/index.d.ts +1 -0
- package/dist/processors/document/index.js +6 -0
- package/dist/processors/errors/FileErrorCode.d.ts +2 -2
- package/dist/processors/errors/errorHelpers.d.ts +2 -2
- package/dist/processors/errors/errorHelpers.js +12 -4
- package/dist/processors/errors/errorSerializer.d.ts +4 -4
- package/dist/processors/index.d.ts +8 -2
- package/dist/processors/index.js +5 -2
- package/dist/processors/integration/FileProcessorIntegration.d.ts +8 -8
- package/dist/processors/integration/FileProcessorIntegration.js +7 -7
- package/dist/processors/media/AudioProcessor.d.ts +328 -0
- package/dist/processors/media/AudioProcessor.js +707 -0
- package/dist/processors/media/VideoProcessor.d.ts +350 -0
- package/dist/processors/media/VideoProcessor.js +991 -0
- package/dist/processors/media/ffprobe-static.d.ts +4 -0
- package/dist/processors/media/index.d.ts +27 -0
- package/dist/processors/media/index.js +36 -0
- package/dist/processors/registry/ProcessorRegistry.d.ts +19 -5
- package/dist/processors/registry/ProcessorRegistry.js +103 -8
- package/dist/processors/registry/index.d.ts +1 -1
- package/dist/processors/registry/index.js +1 -1
- package/dist/processors/registry/types.d.ts +2 -2
- package/dist/providers/amazonBedrock.js +2 -1
- package/dist/providers/anthropic.js +2 -2
- package/dist/providers/anthropicBaseProvider.js +10 -4
- package/dist/providers/azureOpenai.js +14 -25
- package/dist/providers/googleAiStudio.js +136 -457
- package/dist/providers/googleNativeGemini3.d.ts +119 -0
- package/dist/providers/googleNativeGemini3.js +263 -0
- package/dist/providers/googleVertex.d.ts +15 -1
- package/dist/providers/googleVertex.js +341 -775
- package/dist/providers/huggingFace.js +20 -5
- package/dist/providers/litellm.js +6 -4
- package/dist/providers/mistral.js +3 -2
- package/dist/providers/openAI.js +2 -2
- package/dist/providers/openRouter.js +8 -7
- package/dist/providers/openaiCompatible.js +10 -4
- package/dist/providers/sagemaker/detection.d.ts +6 -6
- package/dist/providers/sagemaker/diagnostics.d.ts +4 -4
- package/dist/providers/sagemaker/parsers.d.ts +4 -4
- package/dist/rag/chunkers/RecursiveChunker.js +2 -2
- package/dist/rag/document/loaders.d.ts +6 -71
- package/dist/rag/document/loaders.js +5 -5
- package/dist/rag/graphRag/graphRAG.js +26 -9
- package/dist/rag/metadata/MetadataExtractorFactory.d.ts +5 -55
- package/dist/rag/metadata/metadataExtractor.js +6 -3
- package/dist/rag/pipeline/RAGPipeline.d.ts +8 -126
- package/dist/rag/pipeline/RAGPipeline.js +11 -11
- package/dist/rag/pipeline/contextAssembly.d.ts +3 -42
- package/dist/rag/pipeline/contextAssembly.js +6 -3
- package/dist/rag/reranker/RerankerFactory.d.ts +5 -60
- package/dist/rag/resilience/CircuitBreaker.d.ts +3 -33
- package/dist/rag/resilience/RetryHandler.d.ts +2 -21
- package/dist/rag/resilience/RetryHandler.js +6 -2
- package/dist/rag/retrieval/hybridSearch.d.ts +3 -41
- package/dist/rag/retrieval/vectorQueryTool.d.ts +2 -13
- package/dist/rag/retrieval/vectorQueryTool.js +4 -3
- package/dist/rag/types.d.ts +3 -3
- package/dist/sdk/toolRegistration.d.ts +2 -2
- package/dist/server/middleware/cache.d.ts +2 -2
- package/dist/server/middleware/rateLimit.d.ts +2 -2
- package/dist/server/routes/mcpRoutes.js +277 -249
- package/dist/server/routes/memoryRoutes.js +287 -281
- package/dist/server/utils/validation.d.ts +4 -4
- package/dist/services/server/ai/observability/instrumentation.d.ts +24 -2
- package/dist/services/server/ai/observability/instrumentation.js +12 -1
- package/dist/session/globalSessionState.d.ts +2 -2
- package/dist/telemetry/telemetryService.d.ts +2 -2
- package/dist/types/common.d.ts +39 -0
- package/dist/types/contextTypes.d.ts +255 -0
- package/dist/types/contextTypes.js +0 -2
- package/dist/types/conversation.d.ts +62 -0
- package/dist/types/conversationMemoryInterface.d.ts +27 -0
- package/dist/types/conversationMemoryInterface.js +6 -0
- package/dist/types/fileReferenceTypes.d.ts +222 -0
- package/dist/types/fileReferenceTypes.js +8 -0
- package/dist/types/fileTypes.d.ts +26 -3
- package/dist/types/generateTypes.d.ts +50 -1
- package/dist/types/index.d.ts +4 -5
- package/dist/types/index.js +8 -10
- package/dist/types/processorTypes.d.ts +597 -0
- package/dist/types/processorTypes.js +90 -0
- package/dist/types/ragTypes.d.ts +489 -0
- package/dist/types/ragTypes.js +7 -0
- package/dist/types/sdkTypes.d.ts +17 -18
- package/dist/types/streamTypes.d.ts +24 -1
- package/dist/utils/async/retry.d.ts +2 -2
- package/dist/utils/async/withTimeout.js +3 -1
- package/dist/utils/conversationMemory.d.ts +12 -6
- package/dist/utils/conversationMemory.js +91 -36
- package/dist/utils/errorHandling.d.ts +5 -0
- package/dist/utils/errorHandling.js +19 -0
- package/dist/utils/fileDetector.d.ts +62 -0
- package/dist/utils/fileDetector.js +1014 -14
- package/dist/utils/json/safeParse.d.ts +2 -2
- package/dist/utils/messageBuilder.js +806 -153
- package/dist/utils/modelChoices.d.ts +2 -2
- package/dist/utils/multimodalOptionsBuilder.d.ts +2 -1
- package/dist/utils/multimodalOptionsBuilder.js +1 -0
- package/dist/utils/pricing.d.ts +12 -0
- package/dist/utils/pricing.js +133 -0
- package/dist/utils/rateLimiter.d.ts +2 -2
- package/dist/utils/redis.d.ts +17 -0
- package/dist/utils/redis.js +105 -0
- package/dist/utils/sanitizers/filename.d.ts +4 -4
- package/dist/utils/sanitizers/svg.d.ts +2 -2
- package/dist/utils/thinkingConfig.d.ts +6 -6
- package/dist/utils/timeout.d.ts +10 -0
- package/dist/utils/timeout.js +15 -0
- package/dist/utils/tokenEstimation.d.ts +68 -0
- package/dist/utils/tokenEstimation.js +112 -0
- package/dist/utils/tokenUtils.d.ts +4 -4
- package/dist/utils/ttsProcessor.d.ts +2 -2
- package/dist/workflow/config.d.ts +104 -104
- package/package.json +18 -6
- package/dist/lib/utils/conversationMemoryUtils.d.ts +0 -25
- package/dist/lib/utils/conversationMemoryUtils.js +0 -138
- package/dist/utils/conversationMemoryUtils.d.ts +0 -25
- package/dist/utils/conversationMemoryUtils.js +0 -137
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared Summarization Engine
|
|
3
|
+
*
|
|
4
|
+
* Extracted from ConversationMemoryManager and RedisConversationMemoryManager
|
|
5
|
+
* to eliminate code duplication. Both managers delegate to this engine.
|
|
6
|
+
*/
|
|
7
|
+
import { TokenUtils } from "../constants/tokens.js";
|
|
8
|
+
import { buildContextFromPointer, generateSummary, } from "../utils/conversationMemory.js";
|
|
9
|
+
import { RECENT_MESSAGES_RATIO } from "../config/conversationMemory.js";
|
|
10
|
+
import { logger } from "../utils/logger.js";
|
|
11
|
+
/**
|
|
12
|
+
* Centralized summarization engine for conversation memory.
|
|
13
|
+
* Handles token counting, threshold checking, and summary generation.
|
|
14
|
+
*/
|
|
15
|
+
export class SummarizationEngine {
|
|
16
|
+
/**
|
|
17
|
+
* Check if a session needs summarization and perform it if so.
|
|
18
|
+
* @param session - Session memory to check and potentially summarize
|
|
19
|
+
* @param threshold - Token threshold that triggers summarization
|
|
20
|
+
* @param config - Conversation memory configuration (partial allowed)
|
|
21
|
+
* @param logPrefix - Prefix for log messages
|
|
22
|
+
* @returns True if summarization was performed
|
|
23
|
+
*/
|
|
24
|
+
async checkAndSummarize(session, threshold, config, logPrefix = "[SummarizationEngine]") {
|
|
25
|
+
const contextMessages = buildContextFromPointer(session);
|
|
26
|
+
const tokenCount = this.estimateTokens(contextMessages);
|
|
27
|
+
session.lastTokenCount = tokenCount;
|
|
28
|
+
session.lastCountedAt = Date.now();
|
|
29
|
+
logger.debug(`${logPrefix} Token count check`, {
|
|
30
|
+
sessionId: session.sessionId,
|
|
31
|
+
tokenCount,
|
|
32
|
+
threshold,
|
|
33
|
+
needsSummarization: tokenCount >= threshold,
|
|
34
|
+
});
|
|
35
|
+
if (tokenCount >= threshold) {
|
|
36
|
+
await this.summarizeSession(session, threshold, config, logPrefix);
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Perform token-based summarization on a session.
|
|
43
|
+
* Uses pointer-based, non-destructive approach.
|
|
44
|
+
* @param session - Session memory to summarize
|
|
45
|
+
* @param threshold - Token threshold for calculating split point
|
|
46
|
+
* @param config - Conversation memory configuration (partial allowed)
|
|
47
|
+
* @param logPrefix - Prefix for log messages
|
|
48
|
+
*/
|
|
49
|
+
async summarizeSession(session, threshold, config, logPrefix = "[SummarizationEngine]") {
|
|
50
|
+
const startIndex = session.summarizedUpToMessageId
|
|
51
|
+
? session.messages.findIndex((m) => m.id === session.summarizedUpToMessageId) + 1
|
|
52
|
+
: 0;
|
|
53
|
+
const recentMessages = session.messages.slice(startIndex);
|
|
54
|
+
if (recentMessages.length === 0) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const targetRecentTokens = threshold * RECENT_MESSAGES_RATIO;
|
|
58
|
+
const splitIndex = this.findSplitIndexByTokens(recentMessages, targetRecentTokens);
|
|
59
|
+
const messagesToSummarize = recentMessages.slice(0, splitIndex);
|
|
60
|
+
if (messagesToSummarize.length === 0) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const summary = await generateSummary(messagesToSummarize, config, logPrefix, session.summarizedMessage);
|
|
64
|
+
if (!summary) {
|
|
65
|
+
logger.warn(`${logPrefix} Summary generation failed`, {
|
|
66
|
+
sessionId: session.sessionId,
|
|
67
|
+
});
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const lastSummarized = messagesToSummarize[messagesToSummarize.length - 1];
|
|
71
|
+
session.summarizedUpToMessageId = lastSummarized.id;
|
|
72
|
+
session.summarizedMessage = summary;
|
|
73
|
+
logger.info(`${logPrefix} Summarization complete`, {
|
|
74
|
+
sessionId: session.sessionId,
|
|
75
|
+
summarizedCount: messagesToSummarize.length,
|
|
76
|
+
totalMessages: session.messages.length,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Estimate total tokens for a message array.
|
|
81
|
+
* @param messages - Array of chat messages
|
|
82
|
+
* @returns Estimated token count
|
|
83
|
+
*/
|
|
84
|
+
estimateTokens(messages) {
|
|
85
|
+
return messages.reduce((total, msg) => {
|
|
86
|
+
return total + TokenUtils.estimateTokenCount(msg.content);
|
|
87
|
+
}, 0);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Find split index to keep recent messages within target token count.
|
|
91
|
+
* Works backwards from the most recent message to find the split point.
|
|
92
|
+
* @param messages - Array of messages to analyze
|
|
93
|
+
* @param targetRecentTokens - Target token count for recent messages
|
|
94
|
+
* @returns Index at which to split (messages before this index will be summarized)
|
|
95
|
+
*/
|
|
96
|
+
findSplitIndexByTokens(messages, targetRecentTokens) {
|
|
97
|
+
let recentTokens = 0;
|
|
98
|
+
let splitIndex = messages.length;
|
|
99
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
100
|
+
const msgTokens = TokenUtils.estimateTokenCount(messages[i].content);
|
|
101
|
+
if (recentTokens + msgTokens > targetRecentTokens) {
|
|
102
|
+
splitIndex = i + 1;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
recentTokens += msgTokens;
|
|
106
|
+
}
|
|
107
|
+
// Ensure at least one message is summarized
|
|
108
|
+
return Math.max(1, splitIndex);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
//# sourceMappingURL=summarizationEngine.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool Output Size Limits
|
|
3
|
+
*
|
|
4
|
+
* Truncates tool outputs exceeding size limits.
|
|
5
|
+
* Can save full output to disk with a pointer.
|
|
6
|
+
* Modeled on OpenCode's approach.
|
|
7
|
+
*/
|
|
8
|
+
/** Maximum tool output size in bytes (50KB) */
|
|
9
|
+
export declare const MAX_TOOL_OUTPUT_BYTES: number;
|
|
10
|
+
/** Maximum tool output lines */
|
|
11
|
+
export declare const MAX_TOOL_OUTPUT_LINES = 2000;
|
|
12
|
+
import type { TruncateOptions, TruncateResult } from "../types/contextTypes.js";
|
|
13
|
+
export type { TruncateOptions, TruncateResult } from "../types/contextTypes.js";
|
|
14
|
+
/**
|
|
15
|
+
* Truncate tool output if it exceeds size limits.
|
|
16
|
+
*/
|
|
17
|
+
export declare function truncateToolOutput(output: string, options?: TruncateOptions): TruncateResult;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool Output Size Limits
|
|
3
|
+
*
|
|
4
|
+
* Truncates tool outputs exceeding size limits.
|
|
5
|
+
* Can save full output to disk with a pointer.
|
|
6
|
+
* Modeled on OpenCode's approach.
|
|
7
|
+
*/
|
|
8
|
+
import { writeFileSync, mkdirSync } from "fs";
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
import { randomUUID } from "crypto";
|
|
11
|
+
import { tmpdir } from "os";
|
|
12
|
+
/** Maximum tool output size in bytes (50KB) */
|
|
13
|
+
export const MAX_TOOL_OUTPUT_BYTES = 50 * 1024;
|
|
14
|
+
/** Maximum tool output lines */
|
|
15
|
+
export const MAX_TOOL_OUTPUT_LINES = 2_000;
|
|
16
|
+
/**
|
|
17
|
+
* Truncate tool output if it exceeds size limits.
|
|
18
|
+
*/
|
|
19
|
+
export function truncateToolOutput(output, options) {
|
|
20
|
+
const maxBytes = options?.maxBytes ?? MAX_TOOL_OUTPUT_BYTES;
|
|
21
|
+
const maxLines = options?.maxLines ?? MAX_TOOL_OUTPUT_LINES;
|
|
22
|
+
const direction = options?.direction ?? "tail";
|
|
23
|
+
const saveToDisk = options?.saveToDisk ?? false;
|
|
24
|
+
const originalSize = Buffer.byteLength(output, "utf-8");
|
|
25
|
+
// Check byte limit
|
|
26
|
+
const exceedsBytes = originalSize > maxBytes;
|
|
27
|
+
// Check line limit
|
|
28
|
+
const lines = output.split("\n");
|
|
29
|
+
const exceedsLines = lines.length > maxLines;
|
|
30
|
+
if (!exceedsBytes && !exceedsLines) {
|
|
31
|
+
return { content: output, truncated: false, originalSize };
|
|
32
|
+
}
|
|
33
|
+
// Save to disk if requested
|
|
34
|
+
let savedPath;
|
|
35
|
+
if (saveToDisk) {
|
|
36
|
+
try {
|
|
37
|
+
const saveDir = options?.saveDir ?? join(tmpdir(), "neurolink-tool-output");
|
|
38
|
+
mkdirSync(saveDir, { recursive: true });
|
|
39
|
+
savedPath = join(saveDir, `tool-output-${randomUUID()}.txt`);
|
|
40
|
+
writeFileSync(savedPath, output, "utf-8");
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Silently fail disk save
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// Apply truncation
|
|
47
|
+
let truncated;
|
|
48
|
+
if (exceedsLines) {
|
|
49
|
+
if (direction === "head") {
|
|
50
|
+
truncated = lines.slice(0, maxLines).join("\n");
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
truncated = lines.slice(-maxLines).join("\n");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
truncated = output;
|
|
58
|
+
}
|
|
59
|
+
// Apply byte limit
|
|
60
|
+
if (Buffer.byteLength(truncated, "utf-8") > maxBytes) {
|
|
61
|
+
if (direction === "head") {
|
|
62
|
+
truncated = truncated.slice(0, maxBytes);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
truncated = truncated.slice(-maxBytes);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Add truncation notice
|
|
69
|
+
const notice = savedPath
|
|
70
|
+
? `\n\n[Output truncated from ${originalSize} bytes to ${Buffer.byteLength(truncated, "utf-8")} bytes. Full output saved to: ${savedPath}]`
|
|
71
|
+
: `\n\n[Output truncated from ${originalSize} bytes to ${Buffer.byteLength(truncated, "utf-8")} bytes]`;
|
|
72
|
+
if (direction === "head") {
|
|
73
|
+
truncated = truncated + notice;
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
truncated = notice + "\n" + truncated;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
content: truncated,
|
|
80
|
+
truncated: true,
|
|
81
|
+
savedPath,
|
|
82
|
+
originalSize,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=toolOutputLimits.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool Use/Result Pair Repair
|
|
3
|
+
*
|
|
4
|
+
* After compaction, validates that every tool_use (tool_call) has a
|
|
5
|
+
* corresponding tool_result and vice versa. Inserts synthetic
|
|
6
|
+
* placeholders for orphaned entries.
|
|
7
|
+
*/
|
|
8
|
+
import type { ChatMessage } from "../types/conversation.js";
|
|
9
|
+
import type { RepairResult } from "../types/contextTypes.js";
|
|
10
|
+
export type { RepairResult } from "../types/contextTypes.js";
|
|
11
|
+
/**
|
|
12
|
+
* Repair orphaned tool_use/tool_result pairs in a message array.
|
|
13
|
+
*
|
|
14
|
+
* Ensures every tool_call has a following tool_result and vice versa.
|
|
15
|
+
*/
|
|
16
|
+
export declare function repairToolPairs(messages: ChatMessage[]): RepairResult;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool Use/Result Pair Repair
|
|
3
|
+
*
|
|
4
|
+
* After compaction, validates that every tool_use (tool_call) has a
|
|
5
|
+
* corresponding tool_result and vice versa. Inserts synthetic
|
|
6
|
+
* placeholders for orphaned entries.
|
|
7
|
+
*/
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
9
|
+
/**
|
|
10
|
+
* Repair orphaned tool_use/tool_result pairs in a message array.
|
|
11
|
+
*
|
|
12
|
+
* Ensures every tool_call has a following tool_result and vice versa.
|
|
13
|
+
*/
|
|
14
|
+
export function repairToolPairs(messages) {
|
|
15
|
+
const result = [];
|
|
16
|
+
let orphanedCallsFixed = 0;
|
|
17
|
+
let orphanedResultsFixed = 0;
|
|
18
|
+
for (let i = 0; i < messages.length; i++) {
|
|
19
|
+
const msg = messages[i];
|
|
20
|
+
const nextMsg = i + 1 < messages.length ? messages[i + 1] : undefined;
|
|
21
|
+
if (msg.role === "tool_call") {
|
|
22
|
+
result.push(msg);
|
|
23
|
+
// Check if next message is the corresponding tool_result
|
|
24
|
+
if (!nextMsg || nextMsg.role !== "tool_result") {
|
|
25
|
+
// Insert synthetic tool_result
|
|
26
|
+
result.push({
|
|
27
|
+
id: `repair-result-${randomUUID()}`,
|
|
28
|
+
role: "tool_result",
|
|
29
|
+
content: "[Tool result unavailable - conversation was compacted]",
|
|
30
|
+
tool: msg.tool,
|
|
31
|
+
timestamp: msg.timestamp,
|
|
32
|
+
metadata: { truncated: true },
|
|
33
|
+
});
|
|
34
|
+
orphanedCallsFixed++;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
else if (msg.role === "tool_result") {
|
|
38
|
+
// Check if previous message was the corresponding tool_call
|
|
39
|
+
const prevMsg = result.length > 0 ? result[result.length - 1] : undefined;
|
|
40
|
+
if (!prevMsg ||
|
|
41
|
+
(prevMsg.role !== "tool_call" && prevMsg.role !== "tool_result")) {
|
|
42
|
+
// Insert synthetic tool_call before this result
|
|
43
|
+
result.push({
|
|
44
|
+
id: `repair-call-${randomUUID()}`,
|
|
45
|
+
role: "tool_call",
|
|
46
|
+
content: `[Tool call for ${msg.tool || "unknown"} - conversation was compacted]`,
|
|
47
|
+
tool: msg.tool,
|
|
48
|
+
timestamp: msg.timestamp,
|
|
49
|
+
metadata: { truncated: true },
|
|
50
|
+
});
|
|
51
|
+
orphanedResultsFixed++;
|
|
52
|
+
}
|
|
53
|
+
result.push(msg);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
result.push(msg);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const repaired = orphanedCallsFixed > 0 || orphanedResultsFixed > 0;
|
|
60
|
+
return {
|
|
61
|
+
repaired,
|
|
62
|
+
messages: repaired ? result : messages,
|
|
63
|
+
orphanedCallsFixed,
|
|
64
|
+
orphanedResultsFixed,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=toolPairRepair.js.map
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { logger } from "../utils/logger.js";
|
|
8
8
|
import { modelConfig } from "./modelConfiguration.js";
|
|
9
9
|
import { extractTokenUsage as extractTokenUsageUtil } from "../utils/tokenUtils.js";
|
|
10
|
+
import { calculateCost, hasPricing } from "../utils/pricing.js";
|
|
10
11
|
/**
|
|
11
12
|
* Create analytics data structure from AI response
|
|
12
13
|
*/
|
|
@@ -60,19 +61,25 @@ function extractTokenUsage(result) {
|
|
|
60
61
|
return extractTokenUsageUtil(result.usage);
|
|
61
62
|
}
|
|
62
63
|
/**
|
|
63
|
-
* Estimate cost based on provider, model, and token usage
|
|
64
|
+
* Estimate cost based on provider, model, and token usage.
|
|
65
|
+
* Uses the per-model pricing table first (which includes cache token rates),
|
|
66
|
+
* then falls back to the provider-level configuration system.
|
|
64
67
|
*/
|
|
65
68
|
function estimateCost(provider, model, tokens) {
|
|
66
69
|
try {
|
|
67
|
-
//
|
|
70
|
+
// Try the per-model pricing table first (includes cache token rates)
|
|
71
|
+
if (hasPricing(provider, model)) {
|
|
72
|
+
return calculateCost(provider, model, tokens);
|
|
73
|
+
}
|
|
74
|
+
// Fall back to the configuration system for providers/models not in the pricing table
|
|
68
75
|
const costInfo = modelConfig.getCostInfo(provider.toLowerCase(), model);
|
|
69
76
|
if (!costInfo) {
|
|
70
77
|
return undefined;
|
|
71
78
|
}
|
|
72
|
-
// Calculate cost using the configuration system
|
|
79
|
+
// Calculate cost using the configuration system (per-1K-token rates)
|
|
73
80
|
const inputCost = (tokens.input / 1000) * costInfo.input;
|
|
74
81
|
const outputCost = (tokens.output / 1000) * costInfo.output;
|
|
75
|
-
return Math.round((inputCost + outputCost) *
|
|
82
|
+
return Math.round((inputCost + outputCost) * 1_000_000) / 1_000_000; // Round to 6 decimal places
|
|
76
83
|
}
|
|
77
84
|
catch (error) {
|
|
78
85
|
logger.debug("Cost estimation failed", { provider, model, error });
|
|
@@ -46,6 +46,12 @@ export declare abstract class BaseProvider implements AIProvider {
|
|
|
46
46
|
* Execute fake streaming - extracted method for reusability
|
|
47
47
|
*/
|
|
48
48
|
private executeFakeStreaming;
|
|
49
|
+
/**
|
|
50
|
+
* Apply per-call tool filtering (whitelist/blacklist) to a tools record.
|
|
51
|
+
* If toolFilter is set, only tools whose names are in the list are kept.
|
|
52
|
+
* If excludeTools is set, matching tools are removed. excludeTools is applied after toolFilter.
|
|
53
|
+
*/
|
|
54
|
+
private applyToolFiltering;
|
|
49
55
|
/**
|
|
50
56
|
* Prepare generation context including tools and model
|
|
51
57
|
*/
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { directAgentTools } from "../agent/directTools.js";
|
|
2
2
|
import { IMAGE_GENERATION_MODELS } from "../core/constants.js";
|
|
3
3
|
import { MiddlewareFactory } from "../middleware/factory.js";
|
|
4
|
+
import { isAbortError } from "../utils/errorHandling.js";
|
|
4
5
|
import { logger } from "../utils/logger.js";
|
|
5
|
-
import { createTimeoutController, TimeoutError } from "../utils/timeout.js";
|
|
6
|
+
import { composeAbortSignals, createTimeoutController, TimeoutError, } from "../utils/timeout.js";
|
|
6
7
|
import { shouldDisableBuiltinTools } from "../utils/toolUtils.js";
|
|
7
8
|
import { getKeyCount, getKeysAsString } from "../utils/transformationUtils.js";
|
|
8
9
|
import { TTSProcessor } from "../utils/ttsProcessor.js";
|
|
@@ -101,16 +102,11 @@ export class BaseProvider {
|
|
|
101
102
|
// executeStream() can simply use options.tools (or getAllTools() + options.tools)
|
|
102
103
|
// and get the complete tool set without needing per-provider merge logic.
|
|
103
104
|
if (!options.disableTools && this.supportsTools()) {
|
|
104
|
-
const
|
|
105
|
-
const externalTools = (options.tools || {});
|
|
106
|
-
const mergedTools = { ...baseTools, ...externalTools };
|
|
105
|
+
const mergedTools = await this.getToolsForStream(options);
|
|
107
106
|
options = { ...options, tools: mergedTools };
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
externalToolCount: Object.keys(externalTools).length,
|
|
112
|
-
totalToolCount: Object.keys(mergedTools).length,
|
|
113
|
-
});
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
options = { ...options, tools: {} };
|
|
114
110
|
}
|
|
115
111
|
// CRITICAL FIX: Always prefer real streaming over fake streaming
|
|
116
112
|
// Try real streaming first, use fake streaming only as fallback
|
|
@@ -175,6 +171,13 @@ export class BaseProvider {
|
|
|
175
171
|
toolUsageContext: options.toolUsageContext,
|
|
176
172
|
context: options.context,
|
|
177
173
|
csvOptions: options.csvOptions,
|
|
174
|
+
// Forward abort, tool filtering, and timeout options to prevent
|
|
175
|
+
// silent bypass when falling back from real streaming to fake streaming
|
|
176
|
+
abortSignal: options.abortSignal,
|
|
177
|
+
toolFilter: options.toolFilter,
|
|
178
|
+
excludeTools: options.excludeTools,
|
|
179
|
+
skipToolPromptInjection: options.skipToolPromptInjection,
|
|
180
|
+
timeout: options.timeout,
|
|
178
181
|
};
|
|
179
182
|
logger.debug(`Calling generate for fake streaming`, {
|
|
180
183
|
provider: this.providerName,
|
|
@@ -254,18 +257,62 @@ export class BaseProvider {
|
|
|
254
257
|
throw this.handleProviderError(error);
|
|
255
258
|
}
|
|
256
259
|
}
|
|
260
|
+
/**
|
|
261
|
+
* Apply per-call tool filtering (whitelist/blacklist) to a tools record.
|
|
262
|
+
* If toolFilter is set, only tools whose names are in the list are kept.
|
|
263
|
+
* If excludeTools is set, matching tools are removed. excludeTools is applied after toolFilter.
|
|
264
|
+
*/
|
|
265
|
+
applyToolFiltering(tools, options) {
|
|
266
|
+
if ((!options.toolFilter || options.toolFilter.length === 0) &&
|
|
267
|
+
(!options.excludeTools || options.excludeTools.length === 0)) {
|
|
268
|
+
return tools;
|
|
269
|
+
}
|
|
270
|
+
const beforeCount = Object.keys(tools).length;
|
|
271
|
+
let filtered = { ...tools };
|
|
272
|
+
if (options.toolFilter && options.toolFilter.length > 0) {
|
|
273
|
+
const allowSet = new Set(options.toolFilter);
|
|
274
|
+
const result = {};
|
|
275
|
+
for (const [name, tool] of Object.entries(filtered)) {
|
|
276
|
+
if (allowSet.has(name)) {
|
|
277
|
+
result[name] = tool;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
filtered = result;
|
|
281
|
+
}
|
|
282
|
+
if (options.excludeTools && options.excludeTools.length > 0) {
|
|
283
|
+
const denySet = new Set(options.excludeTools);
|
|
284
|
+
for (const name of Object.keys(filtered)) {
|
|
285
|
+
if (denySet.has(name)) {
|
|
286
|
+
delete filtered[name];
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const afterCount = Object.keys(filtered).length;
|
|
291
|
+
if (beforeCount !== afterCount) {
|
|
292
|
+
logger.debug(`Tool filtering applied`, {
|
|
293
|
+
provider: this.providerName,
|
|
294
|
+
beforeCount,
|
|
295
|
+
afterCount,
|
|
296
|
+
toolFilter: options.toolFilter,
|
|
297
|
+
excludeTools: options.excludeTools,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
return filtered;
|
|
301
|
+
}
|
|
257
302
|
/**
|
|
258
303
|
* Prepare generation context including tools and model
|
|
259
304
|
*/
|
|
260
305
|
async prepareGenerationContext(options) {
|
|
261
306
|
const shouldUseTools = !options.disableTools && this.supportsTools();
|
|
262
307
|
const baseTools = shouldUseTools ? await this.getAllTools() : {};
|
|
263
|
-
|
|
308
|
+
let tools = shouldUseTools
|
|
264
309
|
? {
|
|
265
310
|
...baseTools,
|
|
266
311
|
...(options.tools || {}),
|
|
267
312
|
}
|
|
268
313
|
: {};
|
|
314
|
+
// Apply per-call tool filtering (whitelist/blacklist)
|
|
315
|
+
tools = this.applyToolFiltering(tools, options);
|
|
269
316
|
logger.debug(`Final tools prepared for AI`, {
|
|
270
317
|
provider: this.providerName,
|
|
271
318
|
directTools: getKeyCount(baseTools),
|
|
@@ -294,7 +341,9 @@ export class BaseProvider {
|
|
|
294
341
|
}
|
|
295
342
|
const baseTools = await this.getAllTools();
|
|
296
343
|
const externalTools = (options.tools || {});
|
|
297
|
-
|
|
344
|
+
let merged = { ...baseTools, ...externalTools };
|
|
345
|
+
// Apply per-call tool filtering (whitelist/blacklist)
|
|
346
|
+
merged = this.applyToolFiltering(merged, options);
|
|
298
347
|
logger.debug(`Tools prepared for streaming`, {
|
|
299
348
|
provider: this.providerName,
|
|
300
349
|
baseToolCount: Object.keys(baseTools).length,
|
|
@@ -424,7 +473,19 @@ export class BaseProvider {
|
|
|
424
473
|
// ===== Normal AI Generation Flow =====
|
|
425
474
|
const { tools, model } = await this.prepareGenerationContext(options);
|
|
426
475
|
const messages = await this.buildMessages(options);
|
|
427
|
-
|
|
476
|
+
// Compose timeout signal with user-provided abort signal (mirrors stream path)
|
|
477
|
+
const timeoutController = createTimeoutController(options.timeout, this.providerName, "generate");
|
|
478
|
+
const composedSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal);
|
|
479
|
+
const composedOptions = composedSignal
|
|
480
|
+
? { ...options, abortSignal: composedSignal }
|
|
481
|
+
: options;
|
|
482
|
+
let generateResult;
|
|
483
|
+
try {
|
|
484
|
+
generateResult = await this.executeGeneration(model, messages, tools, composedOptions);
|
|
485
|
+
}
|
|
486
|
+
finally {
|
|
487
|
+
timeoutController?.cleanup();
|
|
488
|
+
}
|
|
428
489
|
this.analyzeAIResponse(generateResult);
|
|
429
490
|
this.logGenerationComplete(generateResult);
|
|
430
491
|
const responseTime = Date.now() - startTime;
|
|
@@ -471,7 +532,15 @@ export class BaseProvider {
|
|
|
471
532
|
return await this.enhanceResult(enhancedResult, options, startTime);
|
|
472
533
|
}
|
|
473
534
|
catch (error) {
|
|
474
|
-
|
|
535
|
+
// Abort errors are expected when a generation is cancelled — log at info, not error
|
|
536
|
+
if (isAbortError(error)) {
|
|
537
|
+
logger.info(`Generate aborted for ${this.providerName}`, {
|
|
538
|
+
error: error instanceof Error ? error.message : String(error),
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
else {
|
|
542
|
+
logger.error(`Generate failed for ${this.providerName}:`, error);
|
|
543
|
+
}
|
|
475
544
|
throw this.handleProviderError(error);
|
|
476
545
|
}
|
|
477
546
|
}
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
* Conversation Memory Manager for NeuroLink
|
|
3
3
|
* Handles in-memory conversation storage, session management, and context injection
|
|
4
4
|
*/
|
|
5
|
-
import type {
|
|
6
|
-
|
|
5
|
+
import type { ChatMessage, ConversationMemoryConfig, ConversationMemoryStats, SessionMemory, StoreConversationTurnOptions } from "../types/conversation.js";
|
|
6
|
+
import type { IConversationMemoryManager } from "../types/conversationMemoryInterface.js";
|
|
7
|
+
export declare class ConversationMemoryManager implements IConversationMemoryManager {
|
|
7
8
|
private sessions;
|
|
8
9
|
config: ConversationMemoryConfig;
|
|
9
10
|
private isInitialized;
|
|
11
|
+
private summarizationEngine;
|
|
10
12
|
/**
|
|
11
13
|
* Track sessions currently being summarized to prevent race conditions
|
|
12
14
|
*/
|
|
@@ -16,6 +18,15 @@ export declare class ConversationMemoryManager {
|
|
|
16
18
|
* Initialize the memory manager
|
|
17
19
|
*/
|
|
18
20
|
initialize(): Promise<void>;
|
|
21
|
+
/** Whether this memory manager can persist data (always true for in-memory within process) */
|
|
22
|
+
get canPersist(): boolean;
|
|
23
|
+
/** Whether Redis client is configured (always false for in-memory) */
|
|
24
|
+
get isRedisConfigured(): boolean;
|
|
25
|
+
/** Get health status for monitoring */
|
|
26
|
+
getHealthStatus(): {
|
|
27
|
+
initialized: boolean;
|
|
28
|
+
connected: boolean;
|
|
29
|
+
};
|
|
19
30
|
/**
|
|
20
31
|
* Store a conversation turn for a session
|
|
21
32
|
* TOKEN-BASED: Validates message size and triggers summarization based on tokens
|
|
@@ -40,16 +51,8 @@ export declare class ConversationMemoryManager {
|
|
|
40
51
|
* Now consistently async to match Redis implementation
|
|
41
52
|
*/
|
|
42
53
|
buildContextMessages(sessionId: string): Promise<ChatMessage[]>;
|
|
43
|
-
getSession(sessionId: string): SessionMemory | undefined;
|
|
54
|
+
getSession(sessionId: string, _userId?: string): SessionMemory | undefined;
|
|
44
55
|
createSummarySystemMessage(content: string, summarizesFrom?: string, summarizesTo?: string): ChatMessage;
|
|
45
|
-
/**
|
|
46
|
-
* Token-based summarization (pointer-based, non-destructive)
|
|
47
|
-
*/
|
|
48
|
-
private summarizeSessionTokenBased;
|
|
49
|
-
/**
|
|
50
|
-
* Find split index to keep recent messages within target token count
|
|
51
|
-
*/
|
|
52
|
-
private findSplitIndexByTokens;
|
|
53
56
|
private ensureInitialized;
|
|
54
57
|
private createNewSession;
|
|
55
58
|
private enforceSessionLimit;
|