@flutchai/flutch-sdk 0.1.25 → 0.1.26

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/dist/index.d.cts CHANGED
@@ -2,8 +2,9 @@ import { JSONSchema7 } from 'json-schema';
2
2
  import * as _nestjs_common from '@nestjs/common';
3
3
  import { OnModuleInit, Logger, Type, CanActivate, ExecutionContext, DynamicModule } from '@nestjs/common';
4
4
  import { ConfigService } from '@nestjs/config';
5
- import { HumanMessage, AIMessageChunk } from '@langchain/core/messages';
5
+ import { HumanMessage, AIMessage, AIMessageChunk } from '@langchain/core/messages';
6
6
  import { BaseChannel, CompiledStateGraph, LangGraphRunnableConfig } from '@langchain/langgraph';
7
+ import { MongoClient } from 'mongodb';
7
8
  import Redis from 'ioredis';
8
9
  import { Registry } from 'prom-client';
9
10
  import { Response, Request } from 'express';
@@ -956,6 +957,28 @@ declare class CallbackController {
956
957
  handleCallback(req: CallbackRequest): Promise<CallbackResult>;
957
958
  }
958
959
 
960
+ interface BaseGraphContext {
961
+ messageId?: string;
962
+ threadId: string;
963
+ userId: string;
964
+ agentId: string;
965
+ companyId?: string;
966
+ }
967
+ interface BaseGraphConfig<TSettings = any, TContext extends BaseGraphContext = BaseGraphContext> {
968
+ thread_id: string;
969
+ checkpoint_ns: string;
970
+ checkpoint_id: string;
971
+ context: TContext;
972
+ metadata: {
973
+ userId: string;
974
+ agentId: string;
975
+ requestId: string;
976
+ graphType: string;
977
+ version: string;
978
+ workflowType: string;
979
+ };
980
+ graphSettings?: TSettings;
981
+ }
959
982
  interface IGraphManifest {
960
983
  companySlug: string;
961
984
  name: string;
@@ -1000,14 +1023,9 @@ declare abstract class AbstractGraphBuilder<V extends string = string> {
1000
1023
  protected manifest?: IGraphManifest;
1001
1024
  constructor();
1002
1025
  abstract buildGraph(config: any): Promise<any>;
1003
- protected createGraphContext(payload: IGraphRequestPayload): {
1004
- messageId?: string;
1005
- threadId: string;
1006
- userId: string;
1007
- agentId: string;
1008
- companyId?: string;
1009
- };
1026
+ protected createGraphContext(payload: IGraphRequestPayload): BaseGraphContext;
1010
1027
  prepareConfig(payload: IGraphRequestPayload): Promise<any>;
1028
+ protected customizeConfig(config: any, payload: IGraphRequestPayload): Promise<any>;
1011
1029
  protected loadManifest(): Promise<IGraphManifest | null>;
1012
1030
  protected loadManifestSync(): IGraphManifest | null;
1013
1031
  protected validateManifest(manifest: IGraphManifest): void;
@@ -1180,14 +1198,25 @@ declare class GraphEngineFactory {
1180
1198
  getEngine(engineType: GraphEngineType): IGraphEngine;
1181
1199
  }
1182
1200
 
1201
+ declare function createStaticMessage(content: string, config: LangGraphRunnableConfig): Promise<AIMessage>;
1202
+
1203
+ interface MongoDBConfig {
1204
+ uri?: string;
1205
+ dbName?: string;
1206
+ checkpointCollectionName?: string;
1207
+ checkpointWritesCollectionName?: string;
1208
+ }
1183
1209
  interface UniversalGraphModuleOptions {
1184
1210
  engineType?: GraphEngineType;
1185
1211
  versioning?: VersioningConfig[];
1212
+ mongodb?: MongoDBConfig;
1186
1213
  }
1187
1214
  declare class UniversalGraphModule {
1188
1215
  static forRoot(options: UniversalGraphModuleOptions): DynamicModule;
1189
1216
  }
1190
1217
 
1218
+ declare function createMongoClientAdapter(mongooseClient: any): MongoClient;
1219
+
1191
1220
  declare enum ModelProvider {
1192
1221
  FLUTCH = "flutch",
1193
1222
  FLUTCH_MISTRAL = "flutch-mistral",
@@ -1568,4 +1597,4 @@ declare class StaticDiscovery implements ServiceDiscoveryProvider {
1568
1597
  }>>;
1569
1598
  }
1570
1599
 
1571
- export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, AttachmentType, type AuditEntry, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, type BaseGraphState, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, type CallbackContext, CallbackController, type CallbackEntry, type CallbackHandler, type CallbackMetadata, CallbackMetrics, type CallbackPatch, type CallbackPatchHandler, CallbackPatchService, CallbackRateLimiter, type CallbackRecord, CallbackRegistry, type CallbackRequest, type CallbackResult, CallbackStore, CallbackTokenGuard, type CallbackUser, type ChannelState, type ChartType, ChatFeature, type ChatModelCreator, type ChatModelOrRunnable, type ChatModelWithTools, type CitationValue, type CompiledGraphFor, type ConcreteModels, type CustomDocument, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExtendedCallbackContext, type ExtendedCallbackHandler, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, type IAgentToolConfig, type IAgentToolConfiguration, type IAttachment, type IBaseEntity, type IChartDataPoint, type IChartDataset, type IChartValue, type IContentBlock, type IContentChain, type IDeletionInfo, type IGenericGraphType, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphManifest, type IGraphMetadata, type IGraphMetadataRegistry, type IGraphRequestPayload, type IGraphResponsePayload, type IGraphRunnableConfig, type IGraphService, type IGraphServiceRegistry, type IGraphSettingsRepository, type IGraphTraceEvent, type IGraphTracer, type IGraphTypeMetadata, type IGraphTypeRegistry, type IModelInitializer, type IReasoningChain, type IReasoningStep, type IStoredMessageContent, type ISystemToolCredentials, type IToolCall, type IToolCatalog, type IToolConfigOption, type IToolExecutionContext, type ITracingEvent, type IUsageMetrics, type IUsageRecorder, type IdempotencyConfig, type IdempotencyEntry, IdempotencyManager, IdempotencyStatus, type KnowledgeBaseInfo, type LLMCallRecord, type LLMConfig, type LLModel, LangGraphEngine, type MappedChannels, McpConverter, type McpRuntimeClient, McpRuntimeHttpClient, type McpTool, McpToolFilter, type Model, type ModelByIdConfig, type ModelByIdWithTypeConfig, type ModelConfig, type ModelConfigFetcher, type ModelConfigWithToken, type ModelConfigWithTokenAndType, type ModelCreator, type ModelCreators, ModelInitializer, ModelProvider, ModelType, type RateLimitConfig, type RateLimitResult, type RequestContext, type RerankModelCreator, type RetrieveQueryOptions, type RetrieverConfig, RetrieverSearchType, RetrieverService, type RouterConfig, type ServiceDiscoveryProvider, SmartCallbackRouter, StaticDiscovery, type StreamAccumulator, StreamChannel, type StrictGraphRunnableConfig, TelegramPatchHandler, type ToolExecutionResult, type TraceApiCallResult, type TracingLevel, UIDispatchController, type UIDispatchDto, UIEndpoint, type UIEndpointClassMetadata, type UIEndpointMethodMetadata, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, type UniversalGraphModuleOptions, UniversalGraphService, type VersionResolution, type VersionResolutionOptions, type VersionRoute, VersionedGraphService, type VersioningConfig, VoyageAIRerank, type VoyageAIRerankConfig, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
1600
+ export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, AttachmentType, type AuditEntry, type BaseGraphConfig, type BaseGraphContext, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, type BaseGraphState, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, type CallbackContext, CallbackController, type CallbackEntry, type CallbackHandler, type CallbackMetadata, CallbackMetrics, type CallbackPatch, type CallbackPatchHandler, CallbackPatchService, CallbackRateLimiter, type CallbackRecord, CallbackRegistry, type CallbackRequest, type CallbackResult, CallbackStore, CallbackTokenGuard, type CallbackUser, type ChannelState, type ChartType, ChatFeature, type ChatModelCreator, type ChatModelOrRunnable, type ChatModelWithTools, type CitationValue, type CompiledGraphFor, type ConcreteModels, type CustomDocument, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExtendedCallbackContext, type ExtendedCallbackHandler, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, type IAgentToolConfig, type IAgentToolConfiguration, type IAttachment, type IBaseEntity, type IChartDataPoint, type IChartDataset, type IChartValue, type IContentBlock, type IContentChain, type IDeletionInfo, type IGenericGraphType, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphManifest, type IGraphMetadata, type IGraphMetadataRegistry, type IGraphRequestPayload, type IGraphResponsePayload, type IGraphRunnableConfig, type IGraphService, type IGraphServiceRegistry, type IGraphSettingsRepository, type IGraphTraceEvent, type IGraphTracer, type IGraphTypeMetadata, type IGraphTypeRegistry, type IModelInitializer, type IReasoningChain, type IReasoningStep, type IStoredMessageContent, type ISystemToolCredentials, type IToolCall, type IToolCatalog, type IToolConfigOption, type IToolExecutionContext, type ITracingEvent, type IUsageMetrics, type IUsageRecorder, type IdempotencyConfig, type IdempotencyEntry, IdempotencyManager, IdempotencyStatus, type KnowledgeBaseInfo, type LLMCallRecord, type LLMConfig, type LLModel, LangGraphEngine, type MappedChannels, McpConverter, type McpRuntimeClient, McpRuntimeHttpClient, type McpTool, McpToolFilter, type Model, type ModelByIdConfig, type ModelByIdWithTypeConfig, type ModelConfig, type ModelConfigFetcher, type ModelConfigWithToken, type ModelConfigWithTokenAndType, type ModelCreator, type ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, type RateLimitConfig, type RateLimitResult, type RequestContext, type RerankModelCreator, type RetrieveQueryOptions, type RetrieverConfig, RetrieverSearchType, RetrieverService, type RouterConfig, type ServiceDiscoveryProvider, SmartCallbackRouter, StaticDiscovery, type StreamAccumulator, StreamChannel, type StrictGraphRunnableConfig, TelegramPatchHandler, type ToolExecutionResult, type TraceApiCallResult, type TracingLevel, UIDispatchController, type UIDispatchDto, UIEndpoint, type UIEndpointClassMetadata, type UIEndpointMethodMetadata, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, type UniversalGraphModuleOptions, UniversalGraphService, type VersionResolution, type VersionResolutionOptions, type VersionRoute, VersionedGraphService, type VersioningConfig, VoyageAIRerank, type VoyageAIRerankConfig, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, createMongoClientAdapter, createStaticMessage, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
package/dist/index.d.ts CHANGED
@@ -2,8 +2,9 @@ import { JSONSchema7 } from 'json-schema';
2
2
  import * as _nestjs_common from '@nestjs/common';
3
3
  import { OnModuleInit, Logger, Type, CanActivate, ExecutionContext, DynamicModule } from '@nestjs/common';
4
4
  import { ConfigService } from '@nestjs/config';
5
- import { HumanMessage, AIMessageChunk } from '@langchain/core/messages';
5
+ import { HumanMessage, AIMessage, AIMessageChunk } from '@langchain/core/messages';
6
6
  import { BaseChannel, CompiledStateGraph, LangGraphRunnableConfig } from '@langchain/langgraph';
7
+ import { MongoClient } from 'mongodb';
7
8
  import Redis from 'ioredis';
8
9
  import { Registry } from 'prom-client';
9
10
  import { Response, Request } from 'express';
@@ -956,6 +957,28 @@ declare class CallbackController {
956
957
  handleCallback(req: CallbackRequest): Promise<CallbackResult>;
957
958
  }
958
959
 
960
+ interface BaseGraphContext {
961
+ messageId?: string;
962
+ threadId: string;
963
+ userId: string;
964
+ agentId: string;
965
+ companyId?: string;
966
+ }
967
+ interface BaseGraphConfig<TSettings = any, TContext extends BaseGraphContext = BaseGraphContext> {
968
+ thread_id: string;
969
+ checkpoint_ns: string;
970
+ checkpoint_id: string;
971
+ context: TContext;
972
+ metadata: {
973
+ userId: string;
974
+ agentId: string;
975
+ requestId: string;
976
+ graphType: string;
977
+ version: string;
978
+ workflowType: string;
979
+ };
980
+ graphSettings?: TSettings;
981
+ }
959
982
  interface IGraphManifest {
960
983
  companySlug: string;
961
984
  name: string;
@@ -1000,14 +1023,9 @@ declare abstract class AbstractGraphBuilder<V extends string = string> {
1000
1023
  protected manifest?: IGraphManifest;
1001
1024
  constructor();
1002
1025
  abstract buildGraph(config: any): Promise<any>;
1003
- protected createGraphContext(payload: IGraphRequestPayload): {
1004
- messageId?: string;
1005
- threadId: string;
1006
- userId: string;
1007
- agentId: string;
1008
- companyId?: string;
1009
- };
1026
+ protected createGraphContext(payload: IGraphRequestPayload): BaseGraphContext;
1010
1027
  prepareConfig(payload: IGraphRequestPayload): Promise<any>;
1028
+ protected customizeConfig(config: any, payload: IGraphRequestPayload): Promise<any>;
1011
1029
  protected loadManifest(): Promise<IGraphManifest | null>;
1012
1030
  protected loadManifestSync(): IGraphManifest | null;
1013
1031
  protected validateManifest(manifest: IGraphManifest): void;
@@ -1180,14 +1198,25 @@ declare class GraphEngineFactory {
1180
1198
  getEngine(engineType: GraphEngineType): IGraphEngine;
1181
1199
  }
1182
1200
 
1201
+ declare function createStaticMessage(content: string, config: LangGraphRunnableConfig): Promise<AIMessage>;
1202
+
1203
+ interface MongoDBConfig {
1204
+ uri?: string;
1205
+ dbName?: string;
1206
+ checkpointCollectionName?: string;
1207
+ checkpointWritesCollectionName?: string;
1208
+ }
1183
1209
  interface UniversalGraphModuleOptions {
1184
1210
  engineType?: GraphEngineType;
1185
1211
  versioning?: VersioningConfig[];
1212
+ mongodb?: MongoDBConfig;
1186
1213
  }
1187
1214
  declare class UniversalGraphModule {
1188
1215
  static forRoot(options: UniversalGraphModuleOptions): DynamicModule;
1189
1216
  }
1190
1217
 
1218
+ declare function createMongoClientAdapter(mongooseClient: any): MongoClient;
1219
+
1191
1220
  declare enum ModelProvider {
1192
1221
  FLUTCH = "flutch",
1193
1222
  FLUTCH_MISTRAL = "flutch-mistral",
@@ -1568,4 +1597,4 @@ declare class StaticDiscovery implements ServiceDiscoveryProvider {
1568
1597
  }>>;
1569
1598
  }
1570
1599
 
1571
- export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, AttachmentType, type AuditEntry, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, type BaseGraphState, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, type CallbackContext, CallbackController, type CallbackEntry, type CallbackHandler, type CallbackMetadata, CallbackMetrics, type CallbackPatch, type CallbackPatchHandler, CallbackPatchService, CallbackRateLimiter, type CallbackRecord, CallbackRegistry, type CallbackRequest, type CallbackResult, CallbackStore, CallbackTokenGuard, type CallbackUser, type ChannelState, type ChartType, ChatFeature, type ChatModelCreator, type ChatModelOrRunnable, type ChatModelWithTools, type CitationValue, type CompiledGraphFor, type ConcreteModels, type CustomDocument, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExtendedCallbackContext, type ExtendedCallbackHandler, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, type IAgentToolConfig, type IAgentToolConfiguration, type IAttachment, type IBaseEntity, type IChartDataPoint, type IChartDataset, type IChartValue, type IContentBlock, type IContentChain, type IDeletionInfo, type IGenericGraphType, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphManifest, type IGraphMetadata, type IGraphMetadataRegistry, type IGraphRequestPayload, type IGraphResponsePayload, type IGraphRunnableConfig, type IGraphService, type IGraphServiceRegistry, type IGraphSettingsRepository, type IGraphTraceEvent, type IGraphTracer, type IGraphTypeMetadata, type IGraphTypeRegistry, type IModelInitializer, type IReasoningChain, type IReasoningStep, type IStoredMessageContent, type ISystemToolCredentials, type IToolCall, type IToolCatalog, type IToolConfigOption, type IToolExecutionContext, type ITracingEvent, type IUsageMetrics, type IUsageRecorder, type IdempotencyConfig, type IdempotencyEntry, IdempotencyManager, IdempotencyStatus, type KnowledgeBaseInfo, type LLMCallRecord, type LLMConfig, type LLModel, LangGraphEngine, type MappedChannels, McpConverter, type McpRuntimeClient, McpRuntimeHttpClient, type McpTool, McpToolFilter, type Model, type ModelByIdConfig, type ModelByIdWithTypeConfig, type ModelConfig, type ModelConfigFetcher, type ModelConfigWithToken, type ModelConfigWithTokenAndType, type ModelCreator, type ModelCreators, ModelInitializer, ModelProvider, ModelType, type RateLimitConfig, type RateLimitResult, type RequestContext, type RerankModelCreator, type RetrieveQueryOptions, type RetrieverConfig, RetrieverSearchType, RetrieverService, type RouterConfig, type ServiceDiscoveryProvider, SmartCallbackRouter, StaticDiscovery, type StreamAccumulator, StreamChannel, type StrictGraphRunnableConfig, TelegramPatchHandler, type ToolExecutionResult, type TraceApiCallResult, type TracingLevel, UIDispatchController, type UIDispatchDto, UIEndpoint, type UIEndpointClassMetadata, type UIEndpointMethodMetadata, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, type UniversalGraphModuleOptions, UniversalGraphService, type VersionResolution, type VersionResolutionOptions, type VersionRoute, VersionedGraphService, type VersioningConfig, VoyageAIRerank, type VoyageAIRerankConfig, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
1600
+ export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, AttachmentType, type AuditEntry, type BaseGraphConfig, type BaseGraphContext, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, type BaseGraphState, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, type CallbackContext, CallbackController, type CallbackEntry, type CallbackHandler, type CallbackMetadata, CallbackMetrics, type CallbackPatch, type CallbackPatchHandler, CallbackPatchService, CallbackRateLimiter, type CallbackRecord, CallbackRegistry, type CallbackRequest, type CallbackResult, CallbackStore, CallbackTokenGuard, type CallbackUser, type ChannelState, type ChartType, ChatFeature, type ChatModelCreator, type ChatModelOrRunnable, type ChatModelWithTools, type CitationValue, type CompiledGraphFor, type ConcreteModels, type CustomDocument, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExtendedCallbackContext, type ExtendedCallbackHandler, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, type IAgentToolConfig, type IAgentToolConfiguration, type IAttachment, type IBaseEntity, type IChartDataPoint, type IChartDataset, type IChartValue, type IContentBlock, type IContentChain, type IDeletionInfo, type IGenericGraphType, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphManifest, type IGraphMetadata, type IGraphMetadataRegistry, type IGraphRequestPayload, type IGraphResponsePayload, type IGraphRunnableConfig, type IGraphService, type IGraphServiceRegistry, type IGraphSettingsRepository, type IGraphTraceEvent, type IGraphTracer, type IGraphTypeMetadata, type IGraphTypeRegistry, type IModelInitializer, type IReasoningChain, type IReasoningStep, type IStoredMessageContent, type ISystemToolCredentials, type IToolCall, type IToolCatalog, type IToolConfigOption, type IToolExecutionContext, type ITracingEvent, type IUsageMetrics, type IUsageRecorder, type IdempotencyConfig, type IdempotencyEntry, IdempotencyManager, IdempotencyStatus, type KnowledgeBaseInfo, type LLMCallRecord, type LLMConfig, type LLModel, LangGraphEngine, type MappedChannels, McpConverter, type McpRuntimeClient, McpRuntimeHttpClient, type McpTool, McpToolFilter, type Model, type ModelByIdConfig, type ModelByIdWithTypeConfig, type ModelConfig, type ModelConfigFetcher, type ModelConfigWithToken, type ModelConfigWithTokenAndType, type ModelCreator, type ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, type RateLimitConfig, type RateLimitResult, type RequestContext, type RerankModelCreator, type RetrieveQueryOptions, type RetrieverConfig, RetrieverSearchType, RetrieverService, type RouterConfig, type ServiceDiscoveryProvider, SmartCallbackRouter, StaticDiscovery, type StreamAccumulator, StreamChannel, type StrictGraphRunnableConfig, TelegramPatchHandler, type ToolExecutionResult, type TraceApiCallResult, type TracingLevel, UIDispatchController, type UIDispatchDto, UIEndpoint, type UIEndpointClassMetadata, type UIEndpointMethodMetadata, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, type UniversalGraphModuleOptions, UniversalGraphService, type VersionResolution, type VersionResolutionOptions, type VersionRoute, VersionedGraphService, type VersioningConfig, VoyageAIRerank, type VoyageAIRerankConfig, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, createMongoClientAdapter, createStaticMessage, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
package/dist/index.js CHANGED
@@ -8,8 +8,12 @@ import { createHash, randomUUID, randomBytes } from 'crypto';
8
8
  import { Registry, collectDefaultMetrics, Counter, Histogram, Gauge } from 'prom-client';
9
9
  import { NestFactory, MetadataScanner, ModuleRef, DiscoveryModule } from '@nestjs/core';
10
10
  import * as net from 'net';
11
- import { ConfigModule } from '@nestjs/config';
11
+ import { ConfigService, ConfigModule } from '@nestjs/config';
12
+ import mongoose from 'mongoose';
13
+ import { MongoDBSaver } from '@langchain/langgraph-checkpoint-mongodb';
12
14
  import * as LangGraph from '@langchain/langgraph';
15
+ import { AIMessage } from '@langchain/core/messages';
16
+ import { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';
13
17
  import { DynamicStructuredTool } from '@langchain/core/tools';
14
18
  import { z } from 'zod';
15
19
  import axios2 from 'axios';
@@ -3164,13 +3168,37 @@ var _AbstractGraphBuilder = class _AbstractGraphBuilder {
3164
3168
  /**
3165
3169
  * Basic configuration preparation for graph execution
3166
3170
  * Automatically creates context with tracer and usageRecorder
3167
- * Can be overridden in child classes to add specific logic
3171
+ * Handles message deserialization and LangGraph-compatible structure
3172
+ * FINAL method - cannot be overridden. Use customizeConfig() hook instead.
3168
3173
  */
3169
3174
  async prepareConfig(payload) {
3170
3175
  const context = this.createGraphContext(payload);
3171
- return {
3176
+ let message = payload.message;
3177
+ if (payload.message && typeof payload.message === "object" && "lc" in payload.message) {
3178
+ try {
3179
+ const { load } = await import('@langchain/core/load');
3180
+ message = await load(JSON.stringify(payload.message));
3181
+ this.logger.debug({
3182
+ message: "Deserialized BaseMessage using load()",
3183
+ type: message.constructor?.name
3184
+ });
3185
+ } catch (error) {
3186
+ this.logger.warn({
3187
+ message: "Failed to deserialize message",
3188
+ error: error.message
3189
+ });
3190
+ }
3191
+ }
3192
+ const baseConfig = {
3193
+ // Input for LangGraph (messages array)
3194
+ input: message ? {
3195
+ messages: [message]
3196
+ } : void 0,
3197
+ // Configurable settings for LangGraph checkpointing and context
3172
3198
  configurable: {
3173
3199
  thread_id: payload.threadId,
3200
+ checkpoint_ns: this.graphType,
3201
+ checkpoint_id: `${payload.threadId}-${Date.now()}`,
3174
3202
  context,
3175
3203
  // Add metadata for compatibility
3176
3204
  metadata: {
@@ -3178,10 +3206,39 @@ var _AbstractGraphBuilder = class _AbstractGraphBuilder {
3178
3206
  agentId: payload.agentId,
3179
3207
  requestId: payload.requestId,
3180
3208
  graphType: this.graphType,
3181
- version: this.version
3182
- }
3209
+ version: this.version,
3210
+ workflowType: this.graphType
3211
+ },
3212
+ // Graph-specific settings from payload
3213
+ graphSettings: payload.graphSettings || {}
3183
3214
  }
3184
3215
  };
3216
+ const finalConfig = await this.customizeConfig(baseConfig, payload);
3217
+ return finalConfig;
3218
+ }
3219
+ /**
3220
+ * Hook for customizing config after base preparation
3221
+ * Override this method in child classes to add/modify config fields
3222
+ *
3223
+ * @param config - Base config prepared by SDK
3224
+ * @param payload - Original request payload
3225
+ * @returns Modified config
3226
+ *
3227
+ * @example
3228
+ * ```typescript
3229
+ * protected async customizeConfig(config: any, payload: IGraphRequestPayload): Promise<any> {
3230
+ * // Add custom fields
3231
+ * config.configurable.myCustomField = "value";
3232
+ *
3233
+ * // Modify existing fields
3234
+ * config.configurable.context.customData = await this.loadCustomData(payload);
3235
+ *
3236
+ * return config;
3237
+ * }
3238
+ * ```
3239
+ */
3240
+ async customizeConfig(config, payload) {
3241
+ return config;
3185
3242
  }
3186
3243
  /**
3187
3244
  * Load graph manifest (if using manifest-based approach)
@@ -3894,6 +3951,24 @@ async function bootstrap(AppModule, options = {}) {
3894
3951
  // src/core/index.ts
3895
3952
  init_builder_registry_service();
3896
3953
 
3954
+ // src/core/mongodb/mongodb-client.adapter.ts
3955
+ function createMongoClientAdapter(mongooseClient) {
3956
+ if (!mongooseClient || typeof mongooseClient.db !== "function") {
3957
+ throw new Error(
3958
+ "Invalid MongoDB client: missing required methods. Expected MongoClient from mongoose.Connection.getClient()"
3959
+ );
3960
+ }
3961
+ const requiredMethods = ["db", "close", "connect"];
3962
+ for (const method of requiredMethods) {
3963
+ if (typeof mongooseClient[method] !== "function") {
3964
+ throw new Error(
3965
+ `Invalid MongoDB client: missing required method '${method}'`
3966
+ );
3967
+ }
3968
+ }
3969
+ return mongooseClient;
3970
+ }
3971
+
3897
3972
  // src/messages/attachments.ts
3898
3973
  var AttachmentType = /* @__PURE__ */ ((AttachmentType2) => {
3899
3974
  AttachmentType2["IMAGE"] = "image";
@@ -4334,8 +4409,8 @@ function getLangGraphDispatch() {
4334
4409
  if (cachedDispatch !== void 0) {
4335
4410
  return cachedDispatch;
4336
4411
  }
4337
- const { dispatchCustomEvent } = LangGraph;
4338
- cachedDispatch = typeof dispatchCustomEvent === "function" ? dispatchCustomEvent : null;
4412
+ const { dispatchCustomEvent: dispatchCustomEvent2 } = LangGraph;
4413
+ cachedDispatch = typeof dispatchCustomEvent2 === "function" ? dispatchCustomEvent2 : null;
4339
4414
  return cachedDispatch;
4340
4415
  }
4341
4416
  function sanitizeTraceData(value, depth = 0, seen = /* @__PURE__ */ new WeakSet(), options) {
@@ -4642,6 +4717,14 @@ var EventProcessor = class {
4642
4717
  */
4643
4718
  processEvent(acc, event, onPartial) {
4644
4719
  this.captureTraceEvent(acc, event);
4720
+ if (event.event === "on_custom_event" && event.data) {
4721
+ const channel = event.metadata?.stream_channel ?? "text" /* TEXT */;
4722
+ if (event.name === "send_static_message" && event.data.content) {
4723
+ const blocks = this.normalizeContentBlocks(event.data.content);
4724
+ this.processContentStream(acc, channel, blocks, onPartial);
4725
+ }
4726
+ return;
4727
+ }
4645
4728
  if (event.event === "on_chat_model_stream" && event.data?.chunk?.content) {
4646
4729
  const channel = event.metadata?.stream_channel ?? "text" /* TEXT */;
4647
4730
  const blocks = this.normalizeContentBlocks(event.data.chunk.content);
@@ -4766,6 +4849,7 @@ var EventProcessor = class {
4766
4849
  }
4767
4850
  if (state.currentBlock) {
4768
4851
  state.contentChain.push(state.currentBlock);
4852
+ state.currentBlock = null;
4769
4853
  }
4770
4854
  if (state.contentChain.length > 0) {
4771
4855
  allChains.push({
@@ -5128,6 +5212,13 @@ LangGraphEngine = __decorateClass([
5128
5212
  Injectable(),
5129
5213
  __decorateParam(1, Optional())
5130
5214
  ], LangGraphEngine);
5215
+ async function createStaticMessage(content, config) {
5216
+ const message = new AIMessage({
5217
+ content
5218
+ });
5219
+ await dispatchCustomEvent("send_static_message", { content }, config);
5220
+ return message;
5221
+ }
5131
5222
 
5132
5223
  // src/core/universal-graph.module.ts
5133
5224
  init_builder_registry_service();
@@ -5315,6 +5406,58 @@ var UniversalGraphModule = class {
5315
5406
  },
5316
5407
  inject: [CallbackRegistry]
5317
5408
  },
5409
+ // MongoDB connection (optional - only if mongodb config provided)
5410
+ ...options.mongodb ? [
5411
+ {
5412
+ provide: "MONGO_CONNECTION",
5413
+ useFactory: async (configService) => {
5414
+ const logger2 = new Logger("UniversalGraphModule");
5415
+ const mongoUri = options.mongodb?.uri || configService.get("MONGODB_URI") || process.env.MONGODB_URI;
5416
+ const dbName = options.mongodb?.dbName || configService.get("MONGO_DB_NAME") || process.env.MONGO_DB_NAME;
5417
+ if (!mongoUri) {
5418
+ throw new Error(
5419
+ "MONGODB_URI is not defined in options, config, or environment"
5420
+ );
5421
+ }
5422
+ logger2.log(
5423
+ `Connecting to MongoDB: ${mongoUri?.substring(0, 50) + "..."}`
5424
+ );
5425
+ try {
5426
+ await mongoose.connect(mongoUri, { dbName });
5427
+ logger2.log(
5428
+ `Successfully connected to MongoDB (db: ${dbName})`
5429
+ );
5430
+ return mongoose.connection;
5431
+ } catch (error) {
5432
+ logger2.error("Failed to connect to MongoDB", error);
5433
+ throw error;
5434
+ }
5435
+ },
5436
+ inject: [ConfigService]
5437
+ },
5438
+ // MongoDB checkpointer
5439
+ {
5440
+ provide: "CHECKPOINTER",
5441
+ useFactory: async (connection, configService) => {
5442
+ const logger2 = new Logger("UniversalGraphModule");
5443
+ const dbName = options.mongodb?.dbName || configService.get("MONGO_DB_NAME") || process.env.MONGO_DB_NAME;
5444
+ const checkpointCollectionName = options.mongodb?.checkpointCollectionName || "checkpoints";
5445
+ const checkpointWritesCollectionName = options.mongodb?.checkpointWritesCollectionName || "checkpoint_writes";
5446
+ logger2.log(
5447
+ `Creating CHECKPOINTER with collections: ${checkpointCollectionName}, ${checkpointWritesCollectionName}`
5448
+ );
5449
+ const mongooseClient = connection.getClient();
5450
+ const mongoClient = createMongoClientAdapter(mongooseClient);
5451
+ return new MongoDBSaver({
5452
+ client: mongoClient,
5453
+ dbName,
5454
+ checkpointCollectionName,
5455
+ checkpointWritesCollectionName
5456
+ });
5457
+ },
5458
+ inject: ["MONGO_CONNECTION", ConfigService]
5459
+ }
5460
+ ] : [],
5318
5461
  {
5319
5462
  provide: "GRAPH_ENGINE",
5320
5463
  useFactory: (langGraphEngine) => langGraphEngine,
@@ -7186,6 +7329,6 @@ StaticDiscovery = __decorateClass([
7186
7329
  Injectable()
7187
7330
  ], StaticDiscovery);
7188
7331
 
7189
- export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, RetrieverSearchType, RetrieverService, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
7332
+ export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, FileBasedDiscovery, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, RetrieverSearchType, RetrieverService, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, bootstrap, createEndpointDescriptors, createMongoClientAdapter, createStaticMessage, findCallbackMethod, findEndpointMethod, getCallbackMetadata, getEndpointMetadata, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, registerFinanceExampleCallback, registerUIEndpointsFromClass, sanitizeTraceData, traceApiCall };
7190
7333
  //# sourceMappingURL=index.js.map
7191
7334
  //# sourceMappingURL=index.js.map