@devilsdev/rag-pipeline-utils 2.4.4 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +345 -0
  3. package/README.md +418 -117
  4. package/SECURITY.md +5 -5
  5. package/dist/experimental.cjs +2 -0
  6. package/dist/experimental.d.ts +1 -0
  7. package/dist/experimental.mjs +5 -0
  8. package/dist/index.cjs +4992 -1242
  9. package/dist/index.d.ts +80 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  12. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  13. package/dist/types/agentic/query-planner.d.ts +145 -0
  14. package/dist/types/agentic/self-critique.d.ts +45 -0
  15. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  16. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  17. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  18. package/dist/types/ai/multimodal.d.ts +39 -0
  19. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  20. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  21. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  22. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  23. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  24. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  25. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  26. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  27. package/dist/types/citation/citation-tracker.d.ts +64 -0
  28. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  29. package/dist/types/citation/source-mapper.d.ts +37 -0
  30. package/dist/types/connectors/anthropic-connector.d.ts +92 -0
  31. package/dist/types/connectors/base-connector.d.ts +87 -0
  32. package/dist/types/connectors/cohere-connector.d.ts +89 -0
  33. package/dist/types/connectors/connector-utils.d.ts +110 -0
  34. package/dist/types/connectors/local-embedder.d.ts +86 -0
  35. package/dist/types/connectors/memory-retriever.d.ts +91 -0
  36. package/dist/types/connectors/ollama-connector.d.ts +110 -0
  37. package/dist/types/connectors/openai-connector.d.ts +114 -0
  38. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  39. package/dist/types/cost/cost-calculator.d.ts +152 -0
  40. package/dist/types/cost/cost-tracker.d.ts +126 -0
  41. package/dist/types/cost/token-budget.d.ts +110 -0
  42. package/dist/types/dag/core/error-context.d.ts +239 -0
  43. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  44. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  45. package/dist/types/dag/dag-engine.d.ts +156 -0
  46. package/dist/types/dag/dag-node.d.ts +37 -0
  47. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  48. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  49. package/dist/types/debug/execution-tracer.d.ts +57 -0
  50. package/dist/types/debug/trace-inspector.d.ts +31 -0
  51. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  52. package/dist/types/enterprise/data-governance.d.ts +203 -0
  53. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  54. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  55. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  56. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  57. package/dist/types/evaluate/groundedness.d.ts +60 -0
  58. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  59. package/dist/types/evaluate/relevance.d.ts +21 -0
  60. package/dist/types/evaluate/scoring.d.ts +123 -0
  61. package/dist/types/experimental.d.ts +15 -0
  62. package/dist/types/graph/entity-extractor.d.ts +84 -0
  63. package/dist/types/graph/graph-index.d.ts +49 -0
  64. package/dist/types/graph/graph-retriever.d.ts +81 -0
  65. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  66. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  67. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  68. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  69. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  70. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  71. package/dist/types/mcp/mcp-server.d.ts +85 -0
  72. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  73. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  74. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  75. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  76. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  77. package/dist/types/retrieval/file-vector-store.d.ts +87 -0
  78. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  79. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  80. package/dist/types/security/jwt-config.d.ts +80 -0
  81. package/dist/types/security/jwt-validator.d.ts +195 -0
  82. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  83. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  84. package/dist/types/security/validator.d.ts +5 -0
  85. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  86. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  87. package/dist/types/streaming/stream-router.d.ts +88 -0
  88. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  89. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  90. package/dist/types/templates/scaffold.d.ts +55 -0
  91. package/dist/types/templates/template-registry.d.ts +63 -0
  92. package/dist/types/utils/embed-query.d.ts +20 -0
  93. package/dist/types/utils/logger.d.ts +50 -0
  94. package/dist/types/utils/rate-limiter.d.ts +66 -0
  95. package/dist/types/utils/retry.d.ts +27 -0
  96. package/dist/types/utils/run-abort.d.ts +34 -0
  97. package/dist/types/utils/secure-logging.d.ts +51 -0
  98. package/dist/types/utils/structured-logger.d.ts +126 -0
  99. package/package.json +53 -29
  100. package/src/agentic/agentic-pipeline.js +75 -7
  101. package/src/agentic/iterative-retriever.js +47 -10
  102. package/src/agentic/query-planner.js +329 -78
  103. package/src/citation/citation-tracker.js +6 -4
  104. package/src/citation/hallucination-detector.js +2 -2
  105. package/src/citation/source-mapper.js +15 -28
  106. package/src/cli/commands/ai.js +101 -0
  107. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  108. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  109. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  110. package/src/cli/commands/plugin-hub.js +96 -36
  111. package/src/cli/diagnostics/config-checker.js +76 -63
  112. package/src/cli/diagnostics/environment-checker.js +62 -31
  113. package/src/cli/diagnostics/plugin-checker.js +36 -89
  114. package/src/cli/doctor-command.js +39 -5
  115. package/src/cli/enhanced-cli-commands.js +72 -217
  116. package/src/cli/handlers/ai-handler.js +364 -0
  117. package/src/cli/handlers/diagnostics-handler.js +78 -31
  118. package/src/cli/handlers/ingest-handler.js +28 -22
  119. package/src/cli/handlers/init-handler.js +148 -25
  120. package/src/cli/handlers/query-handler.js +41 -26
  121. package/src/cli/handlers/run-handler.js +16 -167
  122. package/src/cli/handlers/serve-handler.js +60 -0
  123. package/src/cli/services/bench-stats.js +54 -0
  124. package/src/cli/services/benchmark.js +161 -0
  125. package/src/cli/services/feedback.js +155 -0
  126. package/src/cli/services/rag-service.js +322 -0
  127. package/src/cli/shared/cli-utils.js +24 -7
  128. package/src/cli/shared/config-context.js +21 -0
  129. package/src/cli/wizard/config-builder.js +81 -0
  130. package/src/cli/wizard/init-wizard.js +617 -0
  131. package/src/config/component-factory.js +125 -0
  132. package/src/config/load-config.js +29 -10
  133. package/src/config/load-plugin-config.js +46 -2
  134. package/src/connectors/anthropic-connector.js +93 -55
  135. package/src/connectors/base-connector.js +74 -19
  136. package/src/connectors/cohere-connector.js +88 -32
  137. package/src/connectors/connector-utils.js +302 -0
  138. package/src/connectors/local-embedder.js +43 -5
  139. package/src/connectors/memory-retriever.js +108 -15
  140. package/src/connectors/ollama-connector.js +83 -49
  141. package/src/connectors/openai-connector.js +108 -44
  142. package/src/connectors/rag-prompt.js +88 -0
  143. package/src/core/create-pipeline.js +209 -60
  144. package/src/core/plugin-registry.js +87 -11
  145. package/src/cost/cost-calculator.js +205 -32
  146. package/src/dev/dev-server.js +166 -11
  147. package/src/dev/hot-reload.js +40 -1
  148. package/src/ecosystem/plugin-checks.js +181 -0
  149. package/src/ecosystem/plugin-hub.js +50 -125
  150. package/src/ecosystem/plugin-installer.js +298 -0
  151. package/src/ecosystem/plugin-probe.js +127 -0
  152. package/src/ecosystem/plugin-scanner.js +185 -0
  153. package/src/ecosystem/tar-extract.js +114 -0
  154. package/src/enterprise/audit-logging.js +158 -29
  155. package/src/enterprise/sso-integration.js +715 -228
  156. package/src/evaluate/context-metrics.js +28 -16
  157. package/src/evaluate/evaluator.js +3 -3
  158. package/src/evaluate/faithfulness.js +18 -14
  159. package/src/evaluate/groundedness.js +43 -12
  160. package/src/evaluate/pipeline-evaluator.js +35 -8
  161. package/src/evaluate/scoring.js +251 -3
  162. package/src/experimental.js +71 -0
  163. package/src/guardrails/guardrails-pipeline.js +69 -7
  164. package/src/guardrails/injection-detector.js +283 -0
  165. package/src/guardrails/post-generation-guard.js +19 -0
  166. package/src/guardrails/pre-retrieval-guard.js +36 -36
  167. package/src/guardrails/retrieval-guard.js +58 -8
  168. package/src/index.js +36 -1
  169. package/src/loader/document-reader.js +91 -0
  170. package/src/reranker/cascade-reranker.js +3 -0
  171. package/src/reranker/embedding-reranker.js +136 -21
  172. package/src/reranker/llm-reranker.js +79 -12
  173. package/src/reranker/scoring-reranker.js +3 -0
  174. package/src/retrieval/bm25-search.js +12 -6
  175. package/src/retrieval/file-vector-store.js +212 -0
  176. package/src/retrieval/hybrid-retriever.js +22 -19
  177. package/src/security/jwt-config.js +13 -2
  178. package/src/security/jwt-validator.js +134 -30
  179. package/src/security/plugin-sandbox.js +18 -1
  180. package/src/security/plugin-signature-verifier.js +245 -70
  181. package/src/utils/deprecate.js +69 -0
  182. package/src/utils/embed-query.js +33 -0
  183. package/src/utils/input-sanitizer.js +19 -4
  184. package/src/utils/logger.js +34 -4
  185. package/src/utils/run-abort.js +102 -0
  186. package/src/ai/federated-learning.js +0 -211
  187. package/src/ai/federation.js +0 -71
  188. package/src/ai/index.js +0 -22
  189. package/src/ai/model-trainer.js +0 -217
  190. package/src/ai/model-training.js +0 -202
  191. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  192. package/src/ai/orchestrator.js +0 -65
  193. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  194. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  195. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  196. package/src/cli/commands/ai-ml/index.js +0 -17
  197. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  198. package/src/cli/commands/ai-ml/shared.js +0 -51
  199. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  200. package/src/cli/commands/ai-ml.js +0 -386
  201. package/src/cli/commands/docs.js +0 -228
  202. package/src/cli/commands/dx.js +0 -538
  203. package/src/cli/commands/wizard.js +0 -627
  204. package/src/cli/input-sanitization-middleware.js +0 -356
  205. package/src/cli/interactive-wizard.js +0 -373
  206. package/src/cli/templates/development.template.json +0 -64
  207. package/src/cli/templates/minimal.template.json +0 -33
  208. package/src/cli/templates/production.template.json +0 -104
  209. package/src/cli/templates/testing.template.json +0 -45
  210. package/src/cli/wizard/configuration.js +0 -148
  211. package/src/cli/wizard/observability.js +0 -79
  212. package/src/cli/wizard/performance.js +0 -76
  213. package/src/cli/wizard/plugin-selection.js +0 -297
  214. package/src/cli/wizard/preview-save.js +0 -172
  215. package/src/cli/wizard/project-setup.js +0 -66
  216. package/src/core/pipeline-factory.js +0 -59
  217. package/src/dag/enhanced-dag-engine.js +0 -894
  218. package/src/dx/index.js +0 -40
  219. package/src/dx/integration-templates.js +0 -662
  220. package/src/dx/performance-profiler.js +0 -968
  221. package/src/dx/realtime-debugger.js +0 -755
  222. package/src/dx/visual-pipeline-builder.js +0 -578
  223. package/src/ingest.js +0 -59
  224. package/src/pipeline/pipeline.js +0 -18
  225. package/src/query.js +0 -117
@@ -0,0 +1,420 @@
1
+ export class SSOManager extends EventEmitter<[never]> {
2
+ constructor(_options?: {});
3
+ _config: any;
4
+ sessions: Map<any, any>;
5
+ providers: Map<any, any>;
6
+ userCache: Map<any, any>;
7
+ /**
8
+ * Build the full SSO configuration from user-supplied options.
9
+ * @param {Object} _options - User-supplied configuration options
10
+ * @returns {Object} Complete SSO configuration
11
+ * @private
12
+ */
13
+ private _buildConfig;
14
+ /**
15
+ * Create and configure the rate limiter for login attempt throttling.
16
+ * @private
17
+ */
18
+ private _initializeRateLimiter;
19
+ rateLimiter: RateLimiter;
20
+ /**
21
+ * Create and configure the hardened JWT validator for token operations.
22
+ * @param {Object} _options - Original user-supplied options for JWT settings
23
+ * @private
24
+ */
25
+ private _initializeJWTValidator;
26
+ jwtValidator: JWTValidator;
27
+ /**
28
+ * Forward JWT validator events to the SSOManager for audit logging.
29
+ * @private
30
+ */
31
+ private _wireJWTEvents;
32
+ /**
33
+ * Initialize SSO providers
34
+ */
35
+ _initializeProviders(): void;
36
+ /**
37
+ * Initiate SSO login
38
+ */
39
+ initiateLogin(tenantId: any, provider: any, _redirectUrl: any): Promise<{
40
+ authUrl: any;
41
+ state: `${string}-${string}-${string}-${string}-${string}`;
42
+ expiresAt: number;
43
+ }>;
44
+ /**
45
+ * Handle SSO callback
46
+ */
47
+ handleCallback(provider: any, _callbackData: any): Promise<{
48
+ session: {
49
+ id: `${string}-${string}-${string}-${string}-${string}`;
50
+ tenantId: any;
51
+ userId: any;
52
+ provider: any;
53
+ user: {
54
+ id: any;
55
+ email: any;
56
+ name: any;
57
+ roles: any;
58
+ groups: any;
59
+ attributes: any;
60
+ };
61
+ tokens: {
62
+ _accessToken: string;
63
+ refreshToken: string;
64
+ externalTokens: {
65
+ accessToken: any;
66
+ refreshToken: any;
67
+ expiresAt: any;
68
+ };
69
+ };
70
+ metadata: {
71
+ createdAt: number;
72
+ lastActivity: number;
73
+ expiresAt: any;
74
+ ipAddress: any;
75
+ userAgent: any;
76
+ };
77
+ };
78
+ user: any;
79
+ redirectUrl: any;
80
+ }>;
81
+ /**
82
+ * Create user session with JWT tokens
83
+ */
84
+ _createUserSession(tenantId: any, userInfo: any, provider: any, tokenData: any): Promise<{
85
+ id: `${string}-${string}-${string}-${string}-${string}`;
86
+ tenantId: any;
87
+ userId: any;
88
+ provider: any;
89
+ user: {
90
+ id: any;
91
+ email: any;
92
+ name: any;
93
+ roles: any;
94
+ groups: any;
95
+ attributes: any;
96
+ };
97
+ tokens: {
98
+ _accessToken: string;
99
+ refreshToken: string;
100
+ externalTokens: {
101
+ accessToken: any;
102
+ refreshToken: any;
103
+ expiresAt: any;
104
+ };
105
+ };
106
+ metadata: {
107
+ createdAt: number;
108
+ lastActivity: number;
109
+ expiresAt: any;
110
+ ipAddress: any;
111
+ userAgent: any;
112
+ };
113
+ }>;
114
+ /**
115
+ * Validate and refresh session
116
+ */
117
+ validateSession(sessionId: any, tenantId: any): Promise<any>;
118
+ /**
119
+ * Renew session tokens
120
+ */
121
+ _renewSession(session: any): Promise<void>;
122
+ /**
123
+ * Logout user and invalidate session
124
+ */
125
+ logout(sessionId: any, tenantId: any, _options?: {}): Promise<{
126
+ success: boolean;
127
+ reason: string;
128
+ } | {
129
+ success: boolean;
130
+ reason?: undefined;
131
+ }>;
132
+ /**
133
+ * Get user information from session
134
+ */
135
+ getUser(sessionId: any, tenantId: any): Promise<any>;
136
+ /**
137
+ * List active sessions for a tenant
138
+ */
139
+ getActiveSessions(tenantId: any, _options?: {}): Promise<{
140
+ id: any;
141
+ userId: any;
142
+ provider: any;
143
+ user: any;
144
+ metadata: any;
145
+ }[]>;
146
+ /**
147
+ * Revoke all sessions for a user
148
+ */
149
+ revokeUserSessions(tenantId: any, userId: any, excludeSessionId?: any): Promise<{
150
+ revokedSessions: number;
151
+ }>;
152
+ /**
153
+ * Generate JWT token using hardened JWT validator
154
+ * @param {object} payload - JWT payload
155
+ * @returns {string} Signed JWT token
156
+ */
157
+ _generateJWT(payload: object): string;
158
+ /**
159
+ * Verify and decode JWT token using hardened validator
160
+ * @param {string} token - JWT token to verify
161
+ * @returns {object} Decoded payload
162
+ */
163
+ _verifyJWT(token: string): object;
164
+ /**
165
+ * Generate refresh token
166
+ */
167
+ _generateRefreshToken(): string;
168
+ /**
169
+ * Cleanup expired sessions
170
+ */
171
+ cleanupExpiredSessions(): Promise<{
172
+ cleanedSessions: number;
173
+ }>;
174
+ /**
175
+ * Reset rate limit for a specific tenant/provider
176
+ * @param {string} tenantId - Tenant identifier
177
+ * @param {string} provider - Provider name
178
+ */
179
+ resetRateLimit(tenantId: string, provider: string): void;
180
+ /**
181
+ * Get rate limit status for a tenant/provider
182
+ * @param {string} tenantId - Tenant identifier
183
+ * @param {string} provider - Provider name
184
+ * @returns {Object} Rate limit status
185
+ */
186
+ getRateLimitStatus(tenantId: string, provider: string): any;
187
+ /**
188
+ * Get rate limiter statistics
189
+ * @returns {Object} Statistics about rate limiting
190
+ */
191
+ getRateLimiterStats(): any;
192
+ /**
193
+ * Get JWT validator statistics
194
+ * @returns {Object} JWT validation statistics
195
+ */
196
+ getJWTStats(): any;
197
+ /**
198
+ * Destroy SSO manager and cleanup resources
199
+ */
200
+ destroy(): void;
201
+ }
202
+ export class SAMLProvider {
203
+ /**
204
+ * SAML 2.0 provider.
205
+ *
206
+ * Real SAML authentication is NOT supported: verifying SAML assertions
207
+ * requires XML canonicalization and XML-signature verification, which
208
+ * must come from a vetted library rather than hand-written code. Every
209
+ * authentication method throws unless the explicit development bypass is
210
+ * active (devBypass: true and NODE_ENV !== 'production').
211
+ *
212
+ * @param {Object} _config - Provider configuration
213
+ */
214
+ constructor(_config?: any);
215
+ _config: any;
216
+ getAuthorizationUrl(state: any, _redirectUrl: any): Promise<string>;
217
+ exchangeCodeForTokens(_callbackData: any): Promise<{
218
+ _accessToken: `${string}-${string}-${string}-${string}-${string}`;
219
+ assertion: {
220
+ sessionIndex: `${string}-${string}-${string}-${string}-${string}`;
221
+ nameID: string;
222
+ attributes: {
223
+ email: string;
224
+ displayName: string;
225
+ roles: string[];
226
+ };
227
+ notOnOrAfter: number;
228
+ };
229
+ refreshToken: any;
230
+ expiresAt: number;
231
+ }>;
232
+ getUserInfo(_accessToken: any, tokenData?: {}): Promise<{
233
+ id: any;
234
+ email: any;
235
+ name: any;
236
+ roles: any;
237
+ groups: any;
238
+ }>;
239
+ _buildSAMLRequest(state: any): string;
240
+ _validateSAMLResponse(response: any): {
241
+ sessionIndex: `${string}-${string}-${string}-${string}-${string}`;
242
+ nameID: string;
243
+ attributes: {
244
+ email: string;
245
+ displayName: string;
246
+ roles: string[];
247
+ };
248
+ notOnOrAfter: number;
249
+ };
250
+ }
251
+ export class OAuth2Provider {
252
+ /**
253
+ * OAuth 2.0 authorization-code provider with PKCE (S256).
254
+ *
255
+ * @param {Object} _config - clientId, clientSecret (optional for public
256
+ * clients), authorizationUrl, tokenUrl, userInfoUrl, redirectUri,
257
+ * scopes, devBypass
258
+ */
259
+ constructor(_config?: any);
260
+ _config: any;
261
+ /**
262
+ * @param {string} state - Opaque state bound to the login request
263
+ * @param {string} [_redirectUrl] - Fallback redirect_uri when none is configured
264
+ * @param {Object} [loginContext] - { codeChallenge, redirectUri } from SSOManager
265
+ */
266
+ getAuthorizationUrl(state: string, _redirectUrl?: string, loginContext?: any): Promise<string>;
267
+ /**
268
+ * Exchange the authorization code. redirect_uri is taken from provider
269
+ * configuration (or the server-side login request), never from
270
+ * callbackData, and the PKCE code_verifier from the login request.
271
+ *
272
+ * @param {Object} callbackData - { code, state }
273
+ * @param {Object} [loginContext] - { codeVerifier, redirectUri }
274
+ */
275
+ exchangeCodeForTokens(callbackData: any, loginContext?: any): Promise<{
276
+ _accessToken: string;
277
+ refreshToken: string;
278
+ expiresAt: number;
279
+ tokenType?: undefined;
280
+ } | {
281
+ _accessToken: any;
282
+ refreshToken: any;
283
+ expiresAt: number;
284
+ tokenType: any;
285
+ }>;
286
+ getUserInfo(accessToken: any): Promise<{
287
+ id: string;
288
+ email: string;
289
+ name: string;
290
+ roles: string[];
291
+ attributes?: undefined;
292
+ } | {
293
+ id: any;
294
+ email: any;
295
+ name: any;
296
+ roles: any;
297
+ attributes: any;
298
+ }>;
299
+ refreshTokens(refreshToken: any): Promise<{
300
+ _accessToken: any;
301
+ refreshToken: any;
302
+ expiresAt: number;
303
+ }>;
304
+ }
305
+ export class ActiveDirectoryProvider {
306
+ /**
307
+ * Active Directory provider. Only the development bypass is implemented;
308
+ * for AD FS / Entra ID use the OIDC provider, which both support.
309
+ * @param {Object} _config - Provider configuration
310
+ */
311
+ constructor(_config?: any);
312
+ _config: any;
313
+ getAuthorizationUrl(state: any, _redirectUrl: any, loginContext?: {}): Promise<string>;
314
+ exchangeCodeForTokens(callbackData: any): Promise<{
315
+ _accessToken: string;
316
+ refreshToken: string;
317
+ expiresAt: number;
318
+ }>;
319
+ getUserInfo(_accessToken: any): Promise<{
320
+ id: string;
321
+ email: string;
322
+ name: string;
323
+ roles: string[];
324
+ groups: string[];
325
+ }>;
326
+ }
327
+ export class OIDCProvider {
328
+ /**
329
+ * OpenID Connect provider (authorization code + PKCE, validated id_token).
330
+ *
331
+ * Endpoints and keys come from discovery
332
+ * (`<issuer>/.well-known/openid-configuration`) unless configured:
333
+ * authorizationUrl, tokenUrl, userInfoUrl, jwksUri, or `jwks` (a JWK Set
334
+ * `{ keys: [...] }` or an array of JWKs) to avoid fetching keys.
335
+ *
336
+ * The id_token must be signed by a key from the provider JWKS (selected
337
+ * by `kid`) with an asymmetric algorithm (`idTokenAlgorithms`, default
338
+ * RS/PS/ES 256-512), and its iss, aud (clientId), exp and nonce are
339
+ * checked.
340
+ *
341
+ * @param {Object} _config - issuer, clientId, clientSecret, redirectUri,
342
+ * scopes, jwks, jwksUri, authorizationUrl, tokenUrl, userInfoUrl,
343
+ * idTokenAlgorithms, clockTolerance (seconds, default 60), devBypass
344
+ */
345
+ constructor(_config?: any);
346
+ _config: any;
347
+ _metadata: {};
348
+ _jwks: any;
349
+ /**
350
+ * Resolve provider metadata (configured values override discovery).
351
+ * @returns {Promise<Object>}
352
+ */
353
+ getMetadata(): Promise<any>;
354
+ getAuthorizationUrl(state: any, _redirectUrl: any, loginContext?: {}): Promise<string>;
355
+ /**
356
+ * Exchange the code and validate the returned id_token.
357
+ * @param {Object} callbackData - { code, state }
358
+ * @param {Object} [loginContext] - { codeVerifier, nonce, redirectUri }
359
+ */
360
+ exchangeCodeForTokens(callbackData: any, loginContext?: any): Promise<{
361
+ _accessToken: string;
362
+ refreshToken: string;
363
+ idToken: string;
364
+ expiresAt: number;
365
+ claims?: undefined;
366
+ } | {
367
+ _accessToken: any;
368
+ refreshToken: any;
369
+ idToken: any;
370
+ claims: any;
371
+ expiresAt: number;
372
+ }>;
373
+ /**
374
+ * Validate an id_token: signature (provider JWKS), iss, aud, exp, nonce.
375
+ * @param {string} idToken - Compact JWS
376
+ * @param {Object} options - { nonce } expected nonce (required)
377
+ * @returns {Promise<Object>} Verified claims
378
+ */
379
+ validateIdToken(idToken: string, { nonce }?: any): Promise<any>;
380
+ /**
381
+ * Pick the verification key for a token header from the JWKS.
382
+ * Refetches the JWKS once when the kid is unknown (key rotation).
383
+ * @private
384
+ */
385
+ private _selectJwk;
386
+ /** @private */
387
+ private _getJwks;
388
+ /**
389
+ * @param {string} accessToken - Access token for the userinfo endpoint
390
+ * @param {Object} [tokenData] - Result of exchangeCodeForTokens; when it
391
+ * carries validated id_token claims, the userinfo `sub` must match.
392
+ */
393
+ getUserInfo(accessToken: string, tokenData?: any): Promise<{
394
+ id: string;
395
+ email: string;
396
+ name: string;
397
+ roles: string[];
398
+ groups?: undefined;
399
+ attributes?: undefined;
400
+ } | {
401
+ id: any;
402
+ email: any;
403
+ name: any;
404
+ roles: any;
405
+ groups: any;
406
+ attributes: any;
407
+ }>;
408
+ _generateMockIdToken(): string;
409
+ }
410
+ /**
411
+ * Create a PKCE (RFC 7636, S256) verifier/challenge pair.
412
+ * @returns {{codeVerifier: string, codeChallenge: string}}
413
+ */
414
+ export function createPkcePair(): {
415
+ codeVerifier: string;
416
+ codeChallenge: string;
417
+ };
418
+ import { EventEmitter } from "events";
419
+ import RateLimiter = require("../utils/rate-limiter");
420
+ import { JWTValidator } from "../security/jwt-validator";
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Compute context precision: the fraction of retrieved documents that are relevant to the query.
3
+ *
4
+ * @param {string} query - The user query
5
+ * @param {Array<{content: string}>} retrievedDocs - Array of retrieved documents
6
+ * @param {object} [options={}] - Configuration options
7
+ * @param {number} [options.threshold=0.2] - Minimum share of query content terms a doc must contain to be considered relevant
8
+ * @returns {{ score: number, relevantDocs: number, totalDocs: number, perDocScores: Array<{ index: number, score: number, isRelevant: boolean }> }}
9
+ */
10
+ export function computeContextPrecision(query: string, retrievedDocs: Array<{
11
+ content: string;
12
+ }>, options?: {
13
+ threshold?: number;
14
+ }): {
15
+ score: number;
16
+ relevantDocs: number;
17
+ totalDocs: number;
18
+ perDocScores: Array<{
19
+ index: number;
20
+ score: number;
21
+ isRelevant: boolean;
22
+ }>;
23
+ };
24
+ /**
25
+ * Compute context recall: the fraction of the claims in a REFERENCE
26
+ * (ground-truth) answer that the retrieved documents support. It measures
27
+ * whether retrieval found everything needed to answer correctly; pass the
28
+ * expected answer, not the generated one (scoring the generated answer
29
+ * against the documents is faithfulness).
30
+ *
31
+ * A claim is one sentence of the reference answer. It is supported when some
32
+ * document scores at least `threshold` with computeSupportScore, including
33
+ * the numeric consistency check.
34
+ *
35
+ * @param {string} referenceAnswer - The reference (ground-truth) answer text
36
+ * @param {Array<{content: string}>} retrievedDocs - Array of retrieved documents
37
+ * @param {object} [options={}] - Configuration options
38
+ * @param {number} [options.threshold=0.5] - Minimum share of a claim's content terms a doc must contain to support it
39
+ * @returns {{ score: number, supportedClaims: number, totalClaims: number, details: Array<{ claim: string, score: number, isSupported: boolean, bestDocIndex: number }> }}
40
+ */
41
+ export function computeContextRecall(referenceAnswer: string, retrievedDocs: Array<{
42
+ content: string;
43
+ }>, options?: {
44
+ threshold?: number;
45
+ }): {
46
+ score: number;
47
+ supportedClaims: number;
48
+ totalClaims: number;
49
+ details: Array<{
50
+ claim: string;
51
+ score: number;
52
+ isSupported: boolean;
53
+ bestDocIndex: number;
54
+ }>;
55
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Compute faithfulness score for an answer against retrieved documents.
3
+ * Measures how well each sentence in the answer is supported by the retrieved context.
4
+ *
5
+ * @param {string} answer - The generated answer text
6
+ * @param {Array<{content: string}>} retrievedDocs - Array of retrieved documents with content
7
+ * @param {object} [options={}] - Configuration options
8
+ * @param {number} [options.threshold=0.5] - Minimum similarity score to consider a sentence faithful
9
+ * @returns {{ score: number, faithfulSentences: number, totalSentences: number, details: Array<{ sentence: string, score: number, isFaithful: boolean, bestSource: number }> }}
10
+ */
11
+ export function computeFaithfulness(answer: string, retrievedDocs: Array<{
12
+ content: string;
13
+ }>, options?: {
14
+ threshold?: number;
15
+ }): {
16
+ score: number;
17
+ faithfulSentences: number;
18
+ totalSentences: number;
19
+ details: Array<{
20
+ sentence: string;
21
+ score: number;
22
+ isFaithful: boolean;
23
+ bestSource: number;
24
+ }>;
25
+ };
26
+ /**
27
+ * Derive faithfulness score from an existing citation result.
28
+ * Shortcut that reuses citation analysis data rather than recomputing.
29
+ *
30
+ * @param {object} citationResult - Result from citation analysis
31
+ * @param {number} citationResult.groundednessScore - Pre-computed groundedness score
32
+ * @param {Array} [citationResult.citations] - Array of citation details
33
+ * @returns {{ score: number, details: Array }}
34
+ */
35
+ export function computeFaithfulnessFromCitations(citationResult: {
36
+ groundednessScore: number;
37
+ citations?: any[];
38
+ }): {
39
+ score: number;
40
+ details: any[];
41
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Compute a composite groundedness score from faithfulness, context precision
3
+ * and (when a reference answer is given) context recall.
4
+ *
5
+ * Formula: a weighted mean over the components that are available,
6
+ *
7
+ * score = sum(w_i * m_i) / sum(w_i)
8
+ *
9
+ * With a reference answer and the default weights this is
10
+ * 0.4 * faithfulness + 0.3 * contextPrecision + 0.3 * contextRecall.
11
+ * Without one, context recall is left out and the remaining weights are
12
+ * renormalised:
13
+ * (0.4 * faithfulness + 0.3 * contextPrecision) / 0.7.
14
+ * If every available weight is 0 the score is 0.
15
+ *
16
+ * @param {string} query - The user query
17
+ * @param {string} answer - The generated answer text
18
+ * @param {Array<{content: string}>} retrievedDocs - Array of retrieved documents
19
+ * @param {object} [options={}] - Configuration options
20
+ * @param {{ faithfulness: number, contextPrecision: number, contextRecall: number }} [options.weights] - Custom weights for each component
21
+ * @param {number} [options.threshold=0.5] - Similarity threshold passed to component metrics
22
+ * @param {string} [options.referenceAnswer] - Reference (ground-truth) answer used for context recall
23
+ * @returns {{ score: number, components: { faithfulness: object, contextPrecision: object, contextRecall: object }, weights: { faithfulness: number, contextPrecision: number, contextRecall: number } }}
24
+ * `components.contextRecall` is `{ score: null, skipped: true, reason }`
25
+ * when no reference answer was given.
26
+ */
27
+ export function computeGroundedness(query: string, answer: string, retrievedDocs: Array<{
28
+ content: string;
29
+ }>, options?: {
30
+ weights?: {
31
+ faithfulness: number;
32
+ contextPrecision: number;
33
+ contextRecall: number;
34
+ };
35
+ threshold?: number;
36
+ referenceAnswer?: string;
37
+ }): {
38
+ score: number;
39
+ components: {
40
+ faithfulness: object;
41
+ contextPrecision: object;
42
+ contextRecall: object;
43
+ };
44
+ weights: {
45
+ faithfulness: number;
46
+ contextPrecision: number;
47
+ contextRecall: number;
48
+ };
49
+ };
50
+ /**
51
+ * Default weights for the groundedness composite score.
52
+ * @type {{ faithfulness: number, contextPrecision: number, contextRecall: number }}
53
+ */
54
+ export const DEFAULT_WEIGHTS: {
55
+ faithfulness: number;
56
+ contextPrecision: number;
57
+ contextRecall: number;
58
+ };
59
+ /** Reason reported when context recall cannot be computed. */
60
+ export const NO_REFERENCE_REASON: string;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Evaluates RAG pipeline outputs using multiple quality metrics.
3
+ * Emits an 'evaluated' event after each evaluation with the full result.
4
+ *
5
+ * @extends EventEmitter
6
+ *
7
+ * @example
8
+ * const evaluator = new PipelineEvaluator({ metrics: ['faithfulness', 'relevance'] });
9
+ * evaluator.on('evaluated', (result) => console.log(result.scores));
10
+ * const result = evaluator.evaluate({ query: 'What is RAG?', answer: '...', results: [...] });
11
+ */
12
+ export class PipelineEvaluator extends EventEmitter<[never]> {
13
+ /**
14
+ * Create a new PipelineEvaluator.
15
+ * @param {object} [options={}] - Configuration options
16
+ * @param {string[]} [options.metrics] - List of metrics to compute
17
+ * @param {number} [options.threshold] - Similarity threshold for metrics
18
+ * @param {boolean} [options.includeBLEU] - Whether to include BLEU score when reference answer is provided
19
+ * @param {boolean} [options.includeROUGE] - Whether to include ROUGE score when reference answer is provided
20
+ */
21
+ constructor(options?: {
22
+ metrics?: string[];
23
+ threshold?: number;
24
+ includeBLEU?: boolean;
25
+ includeROUGE?: boolean;
26
+ });
27
+ config: {
28
+ metrics: string[];
29
+ threshold: number;
30
+ includeBLEU: boolean;
31
+ includeROUGE: boolean;
32
+ };
33
+ /**
34
+ * Evaluate a pipeline result across all configured metrics.
35
+ *
36
+ * @param {object} pipelineResult - The pipeline output to evaluate
37
+ * @param {string} pipelineResult.query - The original user query
38
+ * @param {string} pipelineResult.answer - The generated answer
39
+ * @param {Array<{content: string}>} pipelineResult.results - Retrieved documents
40
+ * @param {object} [options={}] - Additional evaluation options
41
+ * @param {object} [options.citationResult] - Pre-computed citation result for faithfulness shortcut
42
+ * @param {string} [options.referenceAnswer] - Reference (ground-truth)
43
+ * answer. Required for context recall (how much of it the retrieved
44
+ * documents support) and used for BLEU/ROUGE. Without it, contextRecall is
45
+ * left out of `scores`, `details.contextRecall` is
46
+ * `{ score: null, skipped: true, reason }`, it is listed in
47
+ * `metadata.metricsSkipped`, and groundedness renormalises over
48
+ * faithfulness and context precision.
49
+ * @returns {{ scores: Object<string, number>, details: Object<string, object>, metadata: { metricsComputed: string[], metricsSkipped: Array<{metric: string, reason: string}>, threshold: number, timestamp: string } }}
50
+ */
51
+ evaluate(pipelineResult: {
52
+ query: string;
53
+ answer: string;
54
+ results: Array<{
55
+ content: string;
56
+ }>;
57
+ }, options?: {
58
+ citationResult?: object;
59
+ referenceAnswer?: string;
60
+ }): {
61
+ scores: {
62
+ [x: string]: number;
63
+ };
64
+ details: {
65
+ [x: string]: object;
66
+ };
67
+ metadata: {
68
+ metricsComputed: string[];
69
+ metricsSkipped: Array<{
70
+ metric: string;
71
+ reason: string;
72
+ }>;
73
+ threshold: number;
74
+ timestamp: string;
75
+ };
76
+ };
77
+ }
78
+ /**
79
+ * Default configuration for PipelineEvaluator.
80
+ * @type {{ metrics: string[], threshold: number, includeBLEU: boolean, includeROUGE: boolean }}
81
+ */
82
+ export const DEFAULT_CONFIG: {
83
+ metrics: string[];
84
+ threshold: number;
85
+ includeBLEU: boolean;
86
+ includeROUGE: boolean;
87
+ };
88
+ import { EventEmitter } from "events";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Compute answer relevance score measuring how well the answer addresses the query.
3
+ * Combines Jaccard similarity with query token coverage for a balanced metric.
4
+ *
5
+ * @param {string} query - The user query
6
+ * @param {string} answer - The generated answer text
7
+ * @param {object} [options={}] - Configuration options
8
+ * @param {number} [options.jaccardWeight=0.5] - Weight for Jaccard similarity component
9
+ * @param {number} [options.coverageWeight=0.5] - Weight for query token coverage component
10
+ * @returns {{ score: number, jaccardSimilarity: number, queryTokensCovered: number, totalQueryTokens: number, missingQueryTerms: string[] }}
11
+ */
12
+ export function computeAnswerRelevance(query: string, answer: string, options?: {
13
+ jaccardWeight?: number;
14
+ coverageWeight?: number;
15
+ }): {
16
+ score: number;
17
+ jaccardSimilarity: number;
18
+ queryTokensCovered: number;
19
+ totalQueryTokens: number;
20
+ missingQueryTerms: string[];
21
+ };