@flutchai/flutch-sdk 0.2.21 → 0.3.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/dist/index.d.cts CHANGED
@@ -6,7 +6,7 @@ import { BaseChannel, OverwriteValue, CompiledStateGraph, LangGraphRunnableConfi
6
6
  import { MongoClient, Db } from 'mongodb';
7
7
  import Redis from 'ioredis';
8
8
  import { Registry } from 'prom-client';
9
- import { Response, Request } from 'express';
9
+ import { Response, Request as Request$1 } from 'express';
10
10
  import { DiscoveryService, MetadataScanner, ModuleRef } from '@nestjs/core';
11
11
  import { AIMessageChunk, ToolMessage, AIMessage } from '@langchain/core/messages';
12
12
  import { Runnable, RunnableConfig } from '@langchain/core/runnables';
@@ -822,7 +822,7 @@ declare function getCallbackMetadata(target: any): CallbackMetadata[];
822
822
  declare function hasCallbacks(target: any): boolean;
823
823
  declare function findCallbackMethod(target: any, handler: string): string | symbol | null;
824
824
 
825
- interface CallbackRequest extends Request {
825
+ interface CallbackRequest extends Request$1 {
826
826
  callbackRecord: CallbackRecord;
827
827
  user?: CallbackUser;
828
828
  }
@@ -1012,6 +1012,20 @@ declare enum ChatFeature {
1012
1012
  JSON_MODE = "json_mode"
1013
1013
  }
1014
1014
 
1015
+ interface FlutchContext {
1016
+ messageId?: string;
1017
+ threadId?: string;
1018
+ agentId?: string;
1019
+ userId?: string;
1020
+ nodeName?: string;
1021
+ }
1022
+ declare function withFlutchContext<T>(ctx: FlutchContext, fn: () => T): T;
1023
+ declare function getFlutchContext(): FlutchContext | undefined;
1024
+ declare const flutchFetch: typeof fetch;
1025
+ declare function flutchHeaders(): Record<string, string>;
1026
+ declare function flutchMistralHook(req: Request): Request;
1027
+ declare function wrapCohereFetcher<T extends (args: any) => any>(inner: T): T;
1028
+
1015
1029
  type ToolConfig = string | {
1016
1030
  name: string;
1017
1031
  enabled?: boolean;
@@ -1545,10 +1559,12 @@ declare class LangGraphEngine implements IGraphEngine {
1545
1559
  private deserializeInput;
1546
1560
  invokeGraph(graph: any, preparedPayload: any, signal?: AbortSignal): Promise<any>;
1547
1561
  streamGraph(graph: any, preparedPayload: any, onPartial: (chunk: string) => void, signal?: AbortSignal): Promise<any>;
1562
+ private streamGraphInner;
1548
1563
  private sendTraceFromAccumulator;
1549
1564
  private sendMetricsWebhook;
1550
1565
  private sendTraceEventsBatch;
1551
1566
  private extractThreadId;
1567
+ private extractFlutchContext;
1552
1568
  private processGraphResult;
1553
1569
  }
1554
1570
 
@@ -1784,4 +1800,4 @@ declare class MongoTokenStore implements IOAuthTokenStore {
1784
1800
  private ensureIndex;
1785
1801
  }
1786
1802
 
1787
- export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, type ApiKeyResolver, 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 CustomDocument, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExecuteToolWithAttachmentsParams, type ExecuteToolWithAttachmentsResult, type ExtendedCallbackContext, type ExtendedCallbackHandler, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, 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 IGraphAttachment, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphLogger, 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 ILangGraphConfig, type IModelInitializer, type IOAuthTokenStore, 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 ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, MongoTokenStore, type OAuthProviderConfig, type OAuthProviderDef, OAuthTokenManager, type OAuthTokenManagerOptions, type OAuthTokens, type PostgresConfig, 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 ToolConfig, 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, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall };
1803
+ export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, type ApiKeyResolver, 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 CustomDocument, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExecuteToolWithAttachmentsParams, type ExecuteToolWithAttachmentsResult, type ExtendedCallbackContext, type ExtendedCallbackHandler, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, type FlutchContext, 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 IGraphAttachment, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphLogger, 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 ILangGraphConfig, type IModelInitializer, type IOAuthTokenStore, 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 ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, MongoTokenStore, type OAuthProviderConfig, type OAuthProviderDef, OAuthTokenManager, type OAuthTokenManagerOptions, type OAuthTokens, type PostgresConfig, 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 ToolConfig, 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, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, flutchFetch, flutchHeaders, flutchMistralHook, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getFlutchContext, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall, withFlutchContext, wrapCohereFetcher };
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ import { BaseChannel, OverwriteValue, CompiledStateGraph, LangGraphRunnableConfi
6
6
  import { MongoClient, Db } from 'mongodb';
7
7
  import Redis from 'ioredis';
8
8
  import { Registry } from 'prom-client';
9
- import { Response, Request } from 'express';
9
+ import { Response, Request as Request$1 } from 'express';
10
10
  import { DiscoveryService, MetadataScanner, ModuleRef } from '@nestjs/core';
11
11
  import { AIMessageChunk, ToolMessage, AIMessage } from '@langchain/core/messages';
12
12
  import { Runnable, RunnableConfig } from '@langchain/core/runnables';
@@ -822,7 +822,7 @@ declare function getCallbackMetadata(target: any): CallbackMetadata[];
822
822
  declare function hasCallbacks(target: any): boolean;
823
823
  declare function findCallbackMethod(target: any, handler: string): string | symbol | null;
824
824
 
825
- interface CallbackRequest extends Request {
825
+ interface CallbackRequest extends Request$1 {
826
826
  callbackRecord: CallbackRecord;
827
827
  user?: CallbackUser;
828
828
  }
@@ -1012,6 +1012,20 @@ declare enum ChatFeature {
1012
1012
  JSON_MODE = "json_mode"
1013
1013
  }
1014
1014
 
1015
+ interface FlutchContext {
1016
+ messageId?: string;
1017
+ threadId?: string;
1018
+ agentId?: string;
1019
+ userId?: string;
1020
+ nodeName?: string;
1021
+ }
1022
+ declare function withFlutchContext<T>(ctx: FlutchContext, fn: () => T): T;
1023
+ declare function getFlutchContext(): FlutchContext | undefined;
1024
+ declare const flutchFetch: typeof fetch;
1025
+ declare function flutchHeaders(): Record<string, string>;
1026
+ declare function flutchMistralHook(req: Request): Request;
1027
+ declare function wrapCohereFetcher<T extends (args: any) => any>(inner: T): T;
1028
+
1015
1029
  type ToolConfig = string | {
1016
1030
  name: string;
1017
1031
  enabled?: boolean;
@@ -1545,10 +1559,12 @@ declare class LangGraphEngine implements IGraphEngine {
1545
1559
  private deserializeInput;
1546
1560
  invokeGraph(graph: any, preparedPayload: any, signal?: AbortSignal): Promise<any>;
1547
1561
  streamGraph(graph: any, preparedPayload: any, onPartial: (chunk: string) => void, signal?: AbortSignal): Promise<any>;
1562
+ private streamGraphInner;
1548
1563
  private sendTraceFromAccumulator;
1549
1564
  private sendMetricsWebhook;
1550
1565
  private sendTraceEventsBatch;
1551
1566
  private extractThreadId;
1567
+ private extractFlutchContext;
1552
1568
  private processGraphResult;
1553
1569
  }
1554
1570
 
@@ -1784,4 +1800,4 @@ declare class MongoTokenStore implements IOAuthTokenStore {
1784
1800
  private ensureIndex;
1785
1801
  }
1786
1802
 
1787
- export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, type ApiKeyResolver, 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 CustomDocument, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExecuteToolWithAttachmentsParams, type ExecuteToolWithAttachmentsResult, type ExtendedCallbackContext, type ExtendedCallbackHandler, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, 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 IGraphAttachment, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphLogger, 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 ILangGraphConfig, type IModelInitializer, type IOAuthTokenStore, 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 ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, MongoTokenStore, type OAuthProviderConfig, type OAuthProviderDef, OAuthTokenManager, type OAuthTokenManagerOptions, type OAuthTokens, type PostgresConfig, 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 ToolConfig, 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, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall };
1803
+ export { type ACLValidationResult, AbstractGraphBuilder, type ApiCallTracerOptions, type ApiKeyResolver, 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 CustomDocument, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, type DataEnvelope, ENDPOINT_METADATA_KEY, type EmbeddingModelCreator, Endpoint, type EndpointDescriptor, type EndpointHandler, type EndpointMetadata, type EndpointOptions, EndpointRegistry, EventProcessor, type ExecuteToolWithAttachmentsParams, type ExecuteToolWithAttachmentsResult, type ExtendedCallbackContext, type ExtendedCallbackHandler, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, type FlutchContext, 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 IGraphAttachment, type IGraphBuilder, type IGraphCompiler, type IGraphConfigurable, type IGraphEngine, type IGraphLogger, 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 ILangGraphConfig, type IModelInitializer, type IOAuthTokenStore, 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 ModelCreators, ModelInitializer, ModelProvider, ModelType, type MongoDBConfig, MongoTokenStore, type OAuthProviderConfig, type OAuthProviderDef, OAuthTokenManager, type OAuthTokenManagerOptions, type OAuthTokens, type PostgresConfig, 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 ToolConfig, 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, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, flutchFetch, flutchHeaders, flutchMistralHook, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getFlutchContext, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall, withFlutchContext, wrapCohereFetcher };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Injectable, Inject, Get, Post, Body, Res, Param, Controller, UseGuards, Req, Logger, Optional, Module, UnauthorizedException, ValidationPipe, HttpException, HttpStatus, ForbiddenException, NotFoundException, InternalServerErrorException, Headers } from '@nestjs/common';
1
+ import { Injectable, Inject, Get, Post, Body, Res, Param, Controller, UseGuards, Req, Logger, Optional, Module, UnauthorizedException, ValidationPipe, HttpException, HttpStatus, ForbiddenException, NotFoundException, InternalServerErrorException, Headers as Headers$1 } from '@nestjs/common';
2
2
  import 'reflect-metadata';
3
3
  import { ApiOperation, ApiResponse, ApiParam, ApiTags, DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
4
4
  import * as fs from 'fs';
@@ -14,6 +14,7 @@ import { createHash, randomUUID, randomBytes } from 'crypto';
14
14
  import { Registry, collectDefaultMetrics, Counter, Histogram, Gauge } from 'prom-client';
15
15
  import { ToolMessage, AIMessage } from '@langchain/core/messages';
16
16
  import * as LangGraph from '@langchain/langgraph';
17
+ import { AsyncLocalStorage } from 'async_hooks';
17
18
  import { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';
18
19
  import { DynamicStructuredTool } from '@langchain/core/tools';
19
20
  import { z } from 'zod';
@@ -22,6 +23,7 @@ import { zodToJsonSchema } from 'zod-to-json-schema';
22
23
  import { parseCallbackConfigArg, CallbackManager } from '@langchain/core/callbacks/manager';
23
24
  import { ChatOpenAI, OpenAIEmbeddings } from '@langchain/openai';
24
25
  import { ChatBedrockConverse } from '@langchain/aws';
26
+ import { fetcher } from 'cohere-ai/core';
25
27
  import { ChatAnthropic } from '@langchain/anthropic';
26
28
  import { ChatCohere, CohereRerank } from '@langchain/cohere';
27
29
  import { CohereClient } from 'cohere-ai';
@@ -543,7 +545,7 @@ var init_ui_dispatch_controller = __esm({
543
545
  ApiResponse({ status: 200, description: "Graph manifest" }),
544
546
  ApiResponse({ status: 404, description: "Graph not found" }),
545
547
  __decorateParam(0, Param("graphType")),
546
- __decorateParam(1, Headers("x-user-id"))
548
+ __decorateParam(1, Headers$1("x-user-id"))
547
549
  ], UIDispatchController.prototype, "getGraphManifest", 1);
548
550
  __decorateClass([
549
551
  Get(":graphType/endpoints"),
@@ -554,7 +556,7 @@ var init_ui_dispatch_controller = __esm({
554
556
  type: [String]
555
557
  }),
556
558
  __decorateParam(0, Param("graphType")),
557
- __decorateParam(1, Headers("x-user-id"))
559
+ __decorateParam(1, Headers$1("x-user-id"))
558
560
  ], UIDispatchController.prototype, "listEndpoints", 1);
559
561
  __decorateClass([
560
562
  Get("catalog"),
@@ -563,8 +565,8 @@ var init_ui_dispatch_controller = __esm({
563
565
  status: 200,
564
566
  description: "List of graphs with basic info"
565
567
  }),
566
- __decorateParam(0, Headers("x-user-id")),
567
- __decorateParam(1, Headers("x-company-id"))
568
+ __decorateParam(0, Headers$1("x-user-id")),
569
+ __decorateParam(1, Headers$1("x-company-id"))
568
570
  ], UIDispatchController.prototype, "getGraphCatalog", 1);
569
571
  UIDispatchController = __decorateClass([
570
572
  ApiTags("UI Dispatch"),
@@ -5272,6 +5274,71 @@ var EventProcessor = class {
5272
5274
  EventProcessor = __decorateClass([
5273
5275
  Injectable()
5274
5276
  ], EventProcessor);
5277
+ var als = new AsyncLocalStorage();
5278
+ function withFlutchContext(ctx, fn) {
5279
+ return als.run(ctx, fn);
5280
+ }
5281
+ function getFlutchContext() {
5282
+ return als.getStore();
5283
+ }
5284
+ var HEADER_MAP = {
5285
+ messageId: "x-flutch-message-id",
5286
+ threadId: "x-flutch-thread-id",
5287
+ agentId: "x-flutch-agent-id",
5288
+ userId: "x-flutch-user-id",
5289
+ nodeName: "x-flutch-node"
5290
+ };
5291
+ var flutchFetch = (input, init) => {
5292
+ const ctx = als.getStore();
5293
+ if (!ctx) {
5294
+ return fetch(input, init);
5295
+ }
5296
+ const headers = new Headers(init?.headers);
5297
+ for (const key of Object.keys(HEADER_MAP)) {
5298
+ const value = ctx[key];
5299
+ if (value) {
5300
+ headers.set(HEADER_MAP[key], String(value));
5301
+ }
5302
+ }
5303
+ return fetch(input, { ...init, headers });
5304
+ };
5305
+ function flutchHeaders() {
5306
+ const ctx = als.getStore();
5307
+ if (!ctx) return {};
5308
+ const out = {};
5309
+ for (const key of Object.keys(HEADER_MAP)) {
5310
+ const value = ctx[key];
5311
+ if (value) {
5312
+ out[HEADER_MAP[key]] = String(value);
5313
+ }
5314
+ }
5315
+ return out;
5316
+ }
5317
+ function flutchMistralHook(req) {
5318
+ const extras = flutchHeaders();
5319
+ if (Object.keys(extras).length === 0) {
5320
+ return req;
5321
+ }
5322
+ const headers = new Headers(req.headers);
5323
+ for (const [k, v] of Object.entries(extras)) {
5324
+ headers.set(k, v);
5325
+ }
5326
+ return new Request(req, { headers });
5327
+ }
5328
+ function wrapCohereFetcher(inner) {
5329
+ return ((args) => {
5330
+ const extras = flutchHeaders();
5331
+ if (Object.keys(extras).length === 0) {
5332
+ return inner(args);
5333
+ }
5334
+ return inner({
5335
+ ...args,
5336
+ headers: { ...args.headers ?? {}, ...extras }
5337
+ });
5338
+ });
5339
+ }
5340
+
5341
+ // src/engines/langgraph/langgraph-engine.ts
5275
5342
  process.setMaxListeners(0);
5276
5343
  var LangGraphEngine = class {
5277
5344
  constructor(eventProcessor, configService) {
@@ -5323,29 +5390,42 @@ var LangGraphEngine = class {
5323
5390
  * Method to invoke LangGraph
5324
5391
  */
5325
5392
  async invokeGraph(graph, preparedPayload, signal) {
5326
- this.logger.debug("invokeGraph preparedPayload", preparedPayload);
5327
- if (signal) {
5328
- preparedPayload.signal = signal;
5329
- this.logger.debug("[ENGINE] Signal assigned to preparedPayload.signal");
5330
- }
5331
- const input = await this.deserializeInput(preparedPayload.input || {});
5332
- try {
5333
- const result = await graph.invoke(input, {
5334
- ...preparedPayload.config,
5335
- signal: preparedPayload.signal
5336
- });
5337
- return this.processGraphResult(result);
5338
- } finally {
5339
- const threadId = this.extractThreadId(preparedPayload);
5340
- if (threadId) {
5341
- clearAttachmentDataStore(threadId);
5342
- this.logger.debug(
5343
- `[ENGINE] Cleared attachment data store for thread: ${threadId}`
5344
- );
5393
+ return withFlutchContext(
5394
+ this.extractFlutchContext(preparedPayload),
5395
+ async () => {
5396
+ this.logger.debug("invokeGraph preparedPayload", preparedPayload);
5397
+ if (signal) {
5398
+ preparedPayload.signal = signal;
5399
+ this.logger.debug(
5400
+ "[ENGINE] Signal assigned to preparedPayload.signal"
5401
+ );
5402
+ }
5403
+ const input = await this.deserializeInput(preparedPayload.input || {});
5404
+ try {
5405
+ const result = await graph.invoke(input, {
5406
+ ...preparedPayload.config,
5407
+ signal: preparedPayload.signal
5408
+ });
5409
+ return this.processGraphResult(result);
5410
+ } finally {
5411
+ const threadId = this.extractThreadId(preparedPayload);
5412
+ if (threadId) {
5413
+ clearAttachmentDataStore(threadId);
5414
+ this.logger.debug(
5415
+ `[ENGINE] Cleared attachment data store for thread: ${threadId}`
5416
+ );
5417
+ }
5418
+ }
5345
5419
  }
5346
- }
5420
+ );
5347
5421
  }
5348
5422
  async streamGraph(graph, preparedPayload, onPartial, signal) {
5423
+ return withFlutchContext(
5424
+ this.extractFlutchContext(preparedPayload),
5425
+ () => this.streamGraphInner(graph, preparedPayload, onPartial, signal)
5426
+ );
5427
+ }
5428
+ async streamGraphInner(graph, preparedPayload, onPartial, signal) {
5349
5429
  const acc = this.eventProcessor.createAccumulator();
5350
5430
  let streamError = null;
5351
5431
  this.logger.debug({
@@ -5575,6 +5655,22 @@ var LangGraphEngine = class {
5575
5655
  extractThreadId(preparedPayload) {
5576
5656
  return preparedPayload.configurable?.thread_id || preparedPayload.configurable?.context?.threadId || preparedPayload.config?.configurable?.thread_id || preparedPayload.config?.configurable?.context?.threadId || void 0;
5577
5657
  }
5658
+ /**
5659
+ * Extract Flutch billing/attribution context from the prepared payload.
5660
+ *
5661
+ * Read by `flutchFetch` (in node-sdk/src/models/flutch-context.ts) to
5662
+ * attach X-Flutch-* headers to every router-bound LLM call made during
5663
+ * this graph run.
5664
+ */
5665
+ extractFlutchContext(preparedPayload) {
5666
+ const ctx = preparedPayload?.config?.configurable?.context || preparedPayload?.configurable?.context || {};
5667
+ return {
5668
+ messageId: ctx.messageId,
5669
+ threadId: ctx.threadId || preparedPayload?.config?.configurable?.thread_id,
5670
+ agentId: ctx.agentId,
5671
+ userId: ctx.userId
5672
+ };
5673
+ }
5578
5674
  /**
5579
5675
  * Process graph execution result
5580
5676
  */
@@ -6730,7 +6826,10 @@ var ModelInitializer = class _ModelInitializer {
6730
6826
  );
6731
6827
  const routerURL = resolveRouterURL(baseURL);
6732
6828
  if (routerURL) {
6733
- config.configuration = { baseURL: `${routerURL}/v1` };
6829
+ config.configuration = {
6830
+ baseURL: `${routerURL}/v1`,
6831
+ fetch: flutchFetch
6832
+ };
6734
6833
  }
6735
6834
  return new ChatOpenAI(config);
6736
6835
  },
@@ -6740,15 +6839,19 @@ var ModelInitializer = class _ModelInitializer {
6740
6839
  defaultMaxTokens,
6741
6840
  apiToken,
6742
6841
  baseURL
6743
- }) => new ChatAnthropic({
6744
- modelName,
6745
- temperature: defaultTemperature,
6746
- maxTokens: defaultMaxTokens,
6747
- anthropicApiKey: apiToken || this.resolveApiKey("anthropic" /* ANTHROPIC */),
6748
- ...resolveRouterURL(baseURL) && {
6749
- anthropicApiUrl: resolveRouterURL(baseURL)
6750
- }
6751
- }),
6842
+ }) => {
6843
+ const routerURL = resolveRouterURL(baseURL);
6844
+ return new ChatAnthropic({
6845
+ modelName,
6846
+ temperature: defaultTemperature,
6847
+ maxTokens: defaultMaxTokens,
6848
+ anthropicApiKey: apiToken || this.resolveApiKey("anthropic" /* ANTHROPIC */),
6849
+ ...routerURL && {
6850
+ anthropicApiUrl: routerURL,
6851
+ clientOptions: { fetch: flutchFetch }
6852
+ }
6853
+ });
6854
+ },
6752
6855
  ["cohere" /* COHERE */]: ({
6753
6856
  modelName,
6754
6857
  defaultTemperature,
@@ -6761,7 +6864,13 @@ var ModelInitializer = class _ModelInitializer {
6761
6864
  return routerURL ? new ChatCohere({
6762
6865
  model: modelName,
6763
6866
  temperature: defaultTemperature,
6764
- client: new CohereClient({ token, baseUrl: routerURL })
6867
+ client: new CohereClient({
6868
+ token,
6869
+ baseUrl: routerURL,
6870
+ // Inject X-Flutch-* headers from the ALS context on every
6871
+ // outbound request via the wrapped default fetcher.
6872
+ fetcher: wrapCohereFetcher(fetcher)
6873
+ })
6765
6874
  }) : new ChatCohere({
6766
6875
  model: modelName,
6767
6876
  temperature: defaultTemperature,
@@ -6781,7 +6890,13 @@ var ModelInitializer = class _ModelInitializer {
6781
6890
  temperature: defaultTemperature,
6782
6891
  maxTokens: defaultMaxTokens,
6783
6892
  apiKey: apiToken || this.resolveApiKey("mistral" /* MISTRAL */),
6784
- ...routerURL && { serverURL: `${routerURL}/v1` }
6893
+ ...routerURL && {
6894
+ serverURL: `${routerURL}/v1`,
6895
+ // Mistral SDK doesn't accept a custom fetch directly — its
6896
+ // beforeRequestHooks let us mutate the outgoing Request to add
6897
+ // X-Flutch-* headers from the ALS context.
6898
+ beforeRequestHooks: [flutchMistralHook]
6899
+ }
6785
6900
  });
6786
6901
  },
6787
6902
  ["voyageai" /* VOYAGEAI */]: () => {
@@ -6836,7 +6951,7 @@ var ModelInitializer = class _ModelInitializer {
6836
6951
  model: modelName,
6837
6952
  apiKey: apiToken || this.resolveApiKey("openai" /* OPENAI */),
6838
6953
  ...routerURL && {
6839
- configuration: { baseURL: `${routerURL}/v1` }
6954
+ configuration: { baseURL: `${routerURL}/v1`, fetch: flutchFetch }
6840
6955
  }
6841
6956
  });
6842
6957
  },
@@ -7782,6 +7897,6 @@ var MongoTokenStore = class {
7782
7897
  }
7783
7898
  };
7784
7899
 
7785
- export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, MongoTokenStore, OAuthTokenManager, RetrieverSearchType, RetrieverService, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall };
7900
+ export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, MongoTokenStore, OAuthTokenManager, RetrieverSearchType, RetrieverService, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, flutchFetch, flutchHeaders, flutchMistralHook, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getFlutchContext, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall, withFlutchContext, wrapCohereFetcher };
7786
7901
  //# sourceMappingURL=index.js.map
7787
7902
  //# sourceMappingURL=index.js.map