@devilsdev/rag-pipeline-utils 2.4.5 → 2.6.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 (258) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +431 -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 +6442 -1355
  9. package/dist/index.d.ts +129 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/testing.cjs +2 -0
  12. package/dist/testing.d.ts +1 -0
  13. package/dist/testing.mjs +5 -0
  14. package/dist/types/adapters/ai-sdk.d.ts +53 -0
  15. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  16. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  17. package/dist/types/agentic/query-planner.d.ts +145 -0
  18. package/dist/types/agentic/self-critique.d.ts +45 -0
  19. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  20. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  21. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  22. package/dist/types/ai/multimodal.d.ts +39 -0
  23. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  24. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  25. package/dist/types/cache/component-keys.d.ts +7 -0
  26. package/dist/types/cache/memory-cache.d.ts +54 -0
  27. package/dist/types/cache/pipeline-cache.d.ts +66 -0
  28. package/dist/types/cache/redis-cache.d.ts +46 -0
  29. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  30. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  31. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  32. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  33. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  34. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  35. package/dist/types/citation/citation-tracker.d.ts +64 -0
  36. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  37. package/dist/types/citation/source-mapper.d.ts +37 -0
  38. package/dist/types/connectors/anthropic-connector.d.ts +97 -0
  39. package/dist/types/connectors/base-connector.d.ts +87 -0
  40. package/dist/types/connectors/cohere-connector.d.ts +94 -0
  41. package/dist/types/connectors/connector-utils.d.ts +110 -0
  42. package/dist/types/connectors/local-embedder.d.ts +95 -0
  43. package/dist/types/connectors/memory-retriever.d.ts +99 -0
  44. package/dist/types/connectors/ollama-connector.d.ts +115 -0
  45. package/dist/types/connectors/openai-connector.d.ts +129 -0
  46. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  47. package/dist/types/core/create-pipeline.d.ts +8 -0
  48. package/dist/types/core/plugin-registry.d.ts +136 -0
  49. package/dist/types/core/stage-contracts.d.ts +36 -0
  50. package/dist/types/core/validate-plugin.d.ts +45 -0
  51. package/dist/types/cost/cost-calculator.d.ts +152 -0
  52. package/dist/types/cost/cost-tracker.d.ts +126 -0
  53. package/dist/types/cost/token-budget.d.ts +110 -0
  54. package/dist/types/dag/core/error-context.d.ts +239 -0
  55. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  56. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  57. package/dist/types/dag/dag-engine.d.ts +156 -0
  58. package/dist/types/dag/dag-node.d.ts +37 -0
  59. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  60. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  61. package/dist/types/debug/execution-tracer.d.ts +57 -0
  62. package/dist/types/debug/trace-inspector.d.ts +31 -0
  63. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  64. package/dist/types/enterprise/data-governance.d.ts +203 -0
  65. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  66. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  67. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  68. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  69. package/dist/types/evaluate/groundedness.d.ts +60 -0
  70. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  71. package/dist/types/evaluate/relevance.d.ts +21 -0
  72. package/dist/types/evaluate/scoring.d.ts +123 -0
  73. package/dist/types/evaluate/semantic-similarity.d.ts +14 -0
  74. package/dist/types/experimental.d.ts +15 -0
  75. package/dist/types/graph/entity-extractor.d.ts +84 -0
  76. package/dist/types/graph/graph-index.d.ts +49 -0
  77. package/dist/types/graph/graph-retriever.d.ts +81 -0
  78. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  79. package/dist/types/grounding/check-answer.d.ts +101 -0
  80. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  81. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  82. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  83. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  84. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  85. package/dist/types/mcp/mcp-server.d.ts +85 -0
  86. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  87. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  88. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  89. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  90. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  91. package/dist/types/retrieval/file-vector-store.d.ts +99 -0
  92. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  93. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  94. package/dist/types/security/jwt-config.d.ts +80 -0
  95. package/dist/types/security/jwt-validator.d.ts +195 -0
  96. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  97. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  98. package/dist/types/security/validator.d.ts +5 -0
  99. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  100. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  101. package/dist/types/streaming/stream-router.d.ts +88 -0
  102. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  103. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  104. package/dist/types/templates/scaffold.d.ts +55 -0
  105. package/dist/types/templates/template-registry.d.ts +63 -0
  106. package/dist/types/testing.d.ts +168 -0
  107. package/dist/types/utils/embed-query.d.ts +20 -0
  108. package/dist/types/utils/logger.d.ts +50 -0
  109. package/dist/types/utils/rate-limiter.d.ts +66 -0
  110. package/dist/types/utils/retry.d.ts +27 -0
  111. package/dist/types/utils/run-abort.d.ts +34 -0
  112. package/dist/types/utils/secure-logging.d.ts +51 -0
  113. package/dist/types/utils/structured-logger.d.ts +126 -0
  114. package/package.json +72 -33
  115. package/src/adapters/ai-sdk.js +215 -0
  116. package/src/agentic/agentic-pipeline.js +75 -7
  117. package/src/agentic/iterative-retriever.js +47 -10
  118. package/src/agentic/query-planner.js +329 -78
  119. package/src/cache/component-keys.js +38 -0
  120. package/src/cache/memory-cache.js +87 -0
  121. package/src/cache/pipeline-cache.js +260 -0
  122. package/src/cache/redis-cache.js +83 -0
  123. package/src/citation/citation-tracker.js +6 -4
  124. package/src/citation/hallucination-detector.js +2 -2
  125. package/src/citation/source-mapper.js +15 -28
  126. package/src/cli/commands/ai.js +106 -0
  127. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  128. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  129. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  130. package/src/cli/commands/plugin-hub.js +114 -49
  131. package/src/cli/diagnostics/config-checker.js +76 -63
  132. package/src/cli/diagnostics/environment-checker.js +62 -31
  133. package/src/cli/diagnostics/plugin-checker.js +36 -89
  134. package/src/cli/doctor-command.js +39 -5
  135. package/src/cli/enhanced-cli-commands.js +104 -233
  136. package/src/cli/handlers/ai-handler.js +364 -0
  137. package/src/cli/handlers/diagnostics-handler.js +78 -31
  138. package/src/cli/handlers/ingest-handler.js +28 -22
  139. package/src/cli/handlers/init-handler.js +148 -25
  140. package/src/cli/handlers/query-handler.js +203 -25
  141. package/src/cli/handlers/run-handler.js +16 -167
  142. package/src/cli/handlers/serve-handler.js +60 -0
  143. package/src/cli/services/bench-stats.js +54 -0
  144. package/src/cli/services/benchmark.js +161 -0
  145. package/src/cli/services/feedback.js +155 -0
  146. package/src/cli/services/instrument.js +83 -0
  147. package/src/cli/services/rag-service.js +361 -0
  148. package/src/cli/shared/cli-utils.js +24 -7
  149. package/src/cli/shared/config-context.js +21 -0
  150. package/src/cli/wizard/config-builder.js +81 -0
  151. package/src/cli/wizard/init-wizard.js +602 -0
  152. package/src/config/component-factory.js +125 -0
  153. package/src/config/enhanced-ragrc-schema.js +0 -2
  154. package/src/config/load-config.js +29 -10
  155. package/src/config/load-plugin-config.js +46 -2
  156. package/src/config/validate-schema.js +4 -1
  157. package/src/connectors/anthropic-connector.js +115 -57
  158. package/src/connectors/base-connector.js +74 -19
  159. package/src/connectors/cohere-connector.js +108 -34
  160. package/src/connectors/connector-utils.js +302 -0
  161. package/src/connectors/local-embedder.js +63 -5
  162. package/src/connectors/memory-retriever.js +125 -14
  163. package/src/connectors/ollama-connector.js +112 -51
  164. package/src/connectors/openai-connector.js +153 -44
  165. package/src/connectors/rag-prompt.js +88 -0
  166. package/src/core/create-pipeline.js +307 -61
  167. package/src/core/performance/parallel-processor.js +62 -1
  168. package/src/core/plugin-registry.js +125 -26
  169. package/src/core/stage-contracts.js +36 -0
  170. package/src/core/validate-plugin.js +85 -0
  171. package/src/cost/cost-calculator.js +205 -32
  172. package/src/debug/execution-tracer.js +14 -4
  173. package/src/dev/dev-server.js +173 -11
  174. package/src/dev/hot-reload.js +44 -4
  175. package/src/ecosystem/plugin-checks.js +181 -0
  176. package/src/ecosystem/plugin-hub.js +50 -125
  177. package/src/ecosystem/plugin-installer.js +298 -0
  178. package/src/ecosystem/plugin-probe.js +127 -0
  179. package/src/ecosystem/plugin-scanner.js +185 -0
  180. package/src/ecosystem/tar-extract.js +114 -0
  181. package/src/enterprise/audit-logging.js +158 -29
  182. package/src/enterprise/sso-integration.js +716 -228
  183. package/src/evaluate/context-metrics.js +28 -16
  184. package/src/evaluate/evaluator.js +3 -3
  185. package/src/evaluate/faithfulness.js +18 -14
  186. package/src/evaluate/groundedness.js +43 -12
  187. package/src/evaluate/pipeline-evaluator.js +35 -8
  188. package/src/evaluate/scoring.js +251 -3
  189. package/src/evaluate/semantic-similarity.js +79 -0
  190. package/src/experimental.js +71 -0
  191. package/src/grounding/check-answer.js +173 -0
  192. package/src/guardrails/guardrails-pipeline.js +69 -7
  193. package/src/guardrails/injection-detector.js +283 -0
  194. package/src/guardrails/post-generation-guard.js +19 -0
  195. package/src/guardrails/pre-retrieval-guard.js +36 -36
  196. package/src/guardrails/retrieval-guard.js +58 -8
  197. package/src/index.js +58 -1
  198. package/src/loader/csv-loader.js +3 -2
  199. package/src/loader/document-reader.js +91 -0
  200. package/src/loader/html-loader.js +3 -1
  201. package/src/loader/markdown-loader.js +3 -2
  202. package/src/reranker/cascade-reranker.js +3 -0
  203. package/src/reranker/embedding-reranker.js +136 -21
  204. package/src/reranker/llm-reranker.js +79 -12
  205. package/src/reranker/scoring-reranker.js +3 -0
  206. package/src/retrieval/bm25-search.js +12 -6
  207. package/src/retrieval/file-vector-store.js +241 -0
  208. package/src/retrieval/hybrid-retriever.js +22 -19
  209. package/src/security/jwt-config.js +13 -2
  210. package/src/security/jwt-validator.js +139 -34
  211. package/src/security/plugin-sandbox.js +18 -1
  212. package/src/security/plugin-signature-verifier.js +245 -70
  213. package/src/testing.js +254 -0
  214. package/src/utils/deprecate.js +69 -0
  215. package/src/utils/embed-query.js +33 -0
  216. package/src/utils/input-sanitizer.js +19 -4
  217. package/src/utils/logger.js +34 -4
  218. package/src/utils/run-abort.js +102 -0
  219. package/src/ai/federated-learning.js +0 -211
  220. package/src/ai/federation.js +0 -71
  221. package/src/ai/index.js +0 -22
  222. package/src/ai/model-trainer.js +0 -217
  223. package/src/ai/model-training.js +0 -202
  224. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  225. package/src/ai/orchestrator.js +0 -65
  226. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  227. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  228. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  229. package/src/cli/commands/ai-ml/index.js +0 -17
  230. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  231. package/src/cli/commands/ai-ml/shared.js +0 -51
  232. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  233. package/src/cli/commands/ai-ml.js +0 -386
  234. package/src/cli/commands/docs.js +0 -228
  235. package/src/cli/commands/dx.js +0 -538
  236. package/src/cli/commands/wizard.js +0 -627
  237. package/src/cli/input-sanitization-middleware.js +0 -356
  238. package/src/cli/interactive-wizard.js +0 -373
  239. package/src/cli/templates/development.template.json +0 -64
  240. package/src/cli/templates/minimal.template.json +0 -33
  241. package/src/cli/templates/production.template.json +0 -104
  242. package/src/cli/templates/testing.template.json +0 -45
  243. package/src/cli/wizard/configuration.js +0 -148
  244. package/src/cli/wizard/observability.js +0 -79
  245. package/src/cli/wizard/performance.js +0 -76
  246. package/src/cli/wizard/plugin-selection.js +0 -297
  247. package/src/cli/wizard/preview-save.js +0 -172
  248. package/src/cli/wizard/project-setup.js +0 -66
  249. package/src/core/pipeline-factory.js +0 -59
  250. package/src/dag/enhanced-dag-engine.js +0 -894
  251. package/src/dx/index.js +0 -40
  252. package/src/dx/integration-templates.js +0 -662
  253. package/src/dx/performance-profiler.js +0 -968
  254. package/src/dx/realtime-debugger.js +0 -755
  255. package/src/dx/visual-pipeline-builder.js +0 -578
  256. package/src/ingest.js +0 -59
  257. package/src/pipeline/pipeline.js +0 -18
  258. package/src/query.js +0 -117
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Adapts an AsyncGenerator to the Server-Sent Events protocol.
3
+ *
4
+ * Writes well-formed SSE frames to an HTTP response, manages heartbeat
5
+ * keep-alive comments, and handles client disconnects gracefully.
6
+ *
7
+ * @extends EventEmitter
8
+ *
9
+ * @example
10
+ * const adapter = new SSEAdapter({ heartbeatIntervalMs: 10000 });
11
+ * adapter.on('token', (t) => console.log('sent', t));
12
+ * await adapter.stream(asyncTokenGenerator, res);
13
+ */
14
+ export class SSEAdapter extends EventEmitter<[never]> {
15
+ /**
16
+ * @param {Object} [options] - Configuration overrides
17
+ * @param {string} [options.eventName='token'] - SSE event name for token frames
18
+ * @param {string} [options.doneEvent='[DONE]'] - Sentinel value for the final data frame
19
+ * @param {number} [options.heartbeatIntervalMs=15000] - Heartbeat interval in milliseconds
20
+ */
21
+ constructor(options?: {
22
+ eventName?: string;
23
+ doneEvent?: string;
24
+ heartbeatIntervalMs?: number;
25
+ });
26
+ config: any;
27
+ /**
28
+ * Stream tokens from an AsyncGenerator to an HTTP response as SSE.
29
+ *
30
+ * Sets the required SSE headers, starts a heartbeat timer, and iterates
31
+ * over the generator. Each yielded value should be an object with at least
32
+ * a `token` property and an optional `done` boolean.
33
+ *
34
+ * @param {AsyncGenerator<{token: string, done?: boolean}>} asyncGenerator - Token source
35
+ * @param {import('http').ServerResponse} httpResponse - Writable HTTP response
36
+ * @returns {Promise<void>} Resolves when the stream ends or the client disconnects
37
+ */
38
+ stream(asyncGenerator: AsyncGenerator<{
39
+ token: string;
40
+ done?: boolean;
41
+ }>, httpResponse: import("http").ServerResponse): Promise<void>;
42
+ /**
43
+ * Format a single SSE event string.
44
+ *
45
+ * Multi-line data is split so each line is prefixed with `data: ` as
46
+ * required by the SSE specification.
47
+ *
48
+ * @param {string} eventName - The SSE event type
49
+ * @param {*} data - Payload (will be JSON-stringified)
50
+ * @returns {string} Fully formatted SSE frame including trailing blank line
51
+ */
52
+ formatEvent(eventName: string, data: any): string;
53
+ }
54
+ /**
55
+ * Default configuration for SSE streaming
56
+ * @type {Object}
57
+ */
58
+ export const DEFAULT_CONFIG: any;
59
+ import { EventEmitter } from "events";
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Routes pipeline streaming output to SSE or WebSocket transports.
3
+ *
4
+ * Provides both an Express/Node-HTTP-compatible request handler via
5
+ * {@link StreamRouter#createHandler} and lower-level convenience methods
6
+ * ({@link StreamRouter#streamSSE}, {@link StreamRouter#streamWS}) for
7
+ * manual integration.
8
+ *
9
+ * @extends EventEmitter
10
+ *
11
+ * @example
12
+ * const router = new StreamRouter({ enableCORS: true });
13
+ * const handler = router.createHandler(pipeline);
14
+ * app.post('/api/query', handler);
15
+ */
16
+ export class StreamRouter extends EventEmitter<[never]> {
17
+ /**
18
+ * @param {Object} [options] - Configuration overrides
19
+ * @param {string} [options.defaultTransport='sse'] - Fallback transport type
20
+ * @param {boolean} [options.enableCORS=true] - Enable CORS headers
21
+ * @param {string} [options.corsOrigin='*'] - CORS origin value
22
+ * @param {Object} [options.sseOptions] - Options forwarded to SSEAdapter
23
+ * @param {Object} [options.wsOptions] - Options forwarded to WebSocketAdapter
24
+ */
25
+ constructor(options?: {
26
+ defaultTransport?: string;
27
+ enableCORS?: boolean;
28
+ corsOrigin?: string;
29
+ sseOptions?: any;
30
+ wsOptions?: any;
31
+ });
32
+ config: any;
33
+ sseAdapter: SSEAdapter;
34
+ wsAdapter: WebSocketAdapter;
35
+ /**
36
+ * Create an HTTP request handler that runs the pipeline in streaming mode
37
+ * and routes output to the appropriate transport.
38
+ *
39
+ * The returned function is compatible with Node's `http.createServer`,
40
+ * Express, and similar frameworks.
41
+ *
42
+ * Transport detection:
43
+ * - `Accept: text/event-stream` header selects SSE
44
+ * - `Upgrade: websocket` header selects WebSocket (note: actual upgrade
45
+ * negotiation is typically handled at a higher level)
46
+ * - Otherwise falls back to {@link DEFAULT_CONFIG.defaultTransport}
47
+ *
48
+ * @param {Object} pipeline - A pipeline object with a `.run()` method
49
+ * @returns {Function} Async request handler `(req, res) => Promise<void>`
50
+ */
51
+ createHandler(pipeline: any): Function;
52
+ /**
53
+ * Run the pipeline in streaming mode and pipe tokens to an HTTP response
54
+ * via Server-Sent Events.
55
+ *
56
+ * If the pipeline returns a non-iterable result, it is sent as a single
57
+ * SSE data frame followed by the done sentinel.
58
+ *
59
+ * @param {Object} pipeline - Pipeline with a `.run()` method
60
+ * @param {string} query - User query string
61
+ * @param {import('http').ServerResponse} httpResponse - Writable HTTP response
62
+ * @param {Object} [options={}] - Additional pipeline run options
63
+ * @returns {Promise<void>}
64
+ */
65
+ streamSSE(pipeline: any, query: string, httpResponse: import("http").ServerResponse, options?: any): Promise<void>;
66
+ /**
67
+ * Run the pipeline in streaming mode and pipe tokens over a WebSocket
68
+ * connection.
69
+ *
70
+ * If the pipeline returns a non-iterable result, it is sent as a single
71
+ * `result` message followed by a `done` message.
72
+ *
73
+ * @param {Object} pipeline - Pipeline with a `.run()` method
74
+ * @param {string} query - User query string
75
+ * @param {Object} wsConnection - WebSocket-like connection with `.send()`
76
+ * @param {Object} [options={}] - Additional pipeline run options
77
+ * @returns {Promise<void>}
78
+ */
79
+ streamWS(pipeline: any, query: string, wsConnection: any, options?: any): Promise<void>;
80
+ }
81
+ /**
82
+ * Default configuration for the stream router
83
+ * @type {Object}
84
+ */
85
+ export const DEFAULT_CONFIG: any;
86
+ import { EventEmitter } from "events";
87
+ import { SSEAdapter } from "./sse-adapter";
88
+ import { WebSocketAdapter } from "./websocket-adapter";
@@ -0,0 +1,99 @@
1
+ /**
2
+ * EventEmitter-based wrapper around {@link createEmbeddingStream}.
3
+ *
4
+ * @extends EventEmitter
5
+ *
6
+ * @fires StreamingEmbedder#start
7
+ * @fires StreamingEmbedder#embedding
8
+ * @fires StreamingEmbedder#batch
9
+ * @fires StreamingEmbedder#backpressure
10
+ * @fires StreamingEmbedder#done
11
+ * @fires StreamingEmbedder#error
12
+ *
13
+ * @example
14
+ * const se = new StreamingEmbedder(myEmbedder, { batchSize: 25 });
15
+ * se.on('embedding', (e) => console.log(e.id, e.progress));
16
+ * se.on('done', (stats) => console.log('finished', stats));
17
+ * const all = await se.embedAll(documents);
18
+ */
19
+ export class StreamingEmbedder extends EventEmitter<[never]> {
20
+ /**
21
+ * @param {Object} embedder - Embedder instance with `.embed()` or `.embedQuery()`
22
+ * @param {Object} [options] - Override any key from {@link DEFAULT_CONFIG}
23
+ */
24
+ constructor(embedder: any, options?: any);
25
+ /** @type {Object} */
26
+ embedder: any;
27
+ /** @type {Object} */
28
+ config: any;
29
+ /** @type {{ processed: number, failed: number, totalTime: number }} */
30
+ stats: {
31
+ processed: number;
32
+ failed: number;
33
+ totalTime: number;
34
+ };
35
+ /**
36
+ * Async generator that yields embeddings while emitting lifecycle events.
37
+ *
38
+ * @param {Array<{id: string, content: string}>} documents - Documents to embed
39
+ * @yields {{ id: string, vector: number[], index: number, progress: number }}
40
+ *
41
+ * @fires StreamingEmbedder#start
42
+ * @fires StreamingEmbedder#embedding
43
+ * @fires StreamingEmbedder#batch
44
+ * @fires StreamingEmbedder#backpressure
45
+ * @fires StreamingEmbedder#done
46
+ * @fires StreamingEmbedder#error
47
+ */
48
+ embedStream(documents: Array<{
49
+ id: string;
50
+ content: string;
51
+ }>): AsyncGenerator<{
52
+ backpressure?: boolean;
53
+ id: string;
54
+ vector: any;
55
+ index: number;
56
+ progress: number;
57
+ error?: undefined;
58
+ } | {
59
+ id: string;
60
+ error: any;
61
+ index: number;
62
+ progress: number;
63
+ }, void, unknown>;
64
+ /**
65
+ * Convenience method that collects all embeddings into an array.
66
+ *
67
+ * @param {Array<{id: string, content: string}>} documents - Documents to embed
68
+ * @returns {Promise<Array<{ id: string, vector: number[], index: number, progress: number }>>}
69
+ */
70
+ embedAll(documents: Array<{
71
+ id: string;
72
+ content: string;
73
+ }>): Promise<Array<{
74
+ id: string;
75
+ vector: number[];
76
+ index: number;
77
+ progress: number;
78
+ }>>;
79
+ /**
80
+ * Returns a snapshot of the cumulative statistics.
81
+ *
82
+ * @returns {{ processed: number, failed: number, totalTime: number }}
83
+ */
84
+ getStats(): {
85
+ processed: number;
86
+ failed: number;
87
+ totalTime: number;
88
+ };
89
+ /**
90
+ * Resets the cumulative statistics to zero.
91
+ */
92
+ resetStats(): void;
93
+ }
94
+ /**
95
+ * Default configuration for the StreamingEmbedder
96
+ * @type {Object}
97
+ */
98
+ export const DEFAULT_CONFIG: any;
99
+ import { EventEmitter } from "events";
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Adapts an AsyncGenerator to a WebSocket connection.
3
+ *
4
+ * Sends JSON-framed messages for each token, a completion message when
5
+ * the generator is exhausted, and an error message on failure. Handles
6
+ * premature connection closure gracefully.
7
+ *
8
+ * @extends EventEmitter
9
+ *
10
+ * @example
11
+ * const adapter = new WebSocketAdapter();
12
+ * adapter.on('done', () => console.log('stream complete'));
13
+ * await adapter.stream(asyncTokenGenerator, ws);
14
+ */
15
+ export class WebSocketAdapter extends EventEmitter<[never]> {
16
+ /**
17
+ * @param {Object} [options] - Configuration overrides
18
+ * @param {string} [options.messageType='token'] - Type field for token messages
19
+ * @param {string} [options.doneType='done'] - Type field for completion message
20
+ * @param {string} [options.errorType='error'] - Type field for error messages
21
+ */
22
+ constructor(options?: {
23
+ messageType?: string;
24
+ doneType?: string;
25
+ errorType?: string;
26
+ });
27
+ config: any;
28
+ /**
29
+ * Stream tokens from an AsyncGenerator over a WebSocket connection.
30
+ *
31
+ * Each yielded value should be an object with at least a `token` property
32
+ * and an optional `done` boolean. Messages are sent as JSON strings via
33
+ * `wsConnection.send()`.
34
+ *
35
+ * @param {AsyncGenerator<{token: string, done?: boolean}>} asyncGenerator - Token source
36
+ * @param {Object} wsConnection - WebSocket-like object with a `send(data)` method
37
+ * @param {Function} wsConnection.send - Sends a string message over the socket
38
+ * @param {number} [wsConnection.readyState] - Optional W3C readyState property
39
+ * @returns {Promise<void>} Resolves when the stream ends or the connection closes
40
+ * @throws {TypeError} If wsConnection lacks a send method
41
+ */
42
+ stream(asyncGenerator: AsyncGenerator<{
43
+ token: string;
44
+ done?: boolean;
45
+ }>, wsConnection: {
46
+ send: Function;
47
+ readyState?: number;
48
+ }): Promise<void>;
49
+ /**
50
+ * Check whether the WebSocket connection is still open.
51
+ *
52
+ * @param {Object} wsConnection
53
+ * @returns {boolean}
54
+ * @private
55
+ */
56
+ private _isOpen;
57
+ /**
58
+ * Send a JSON-serialised message over the WebSocket.
59
+ *
60
+ * @param {Object} wsConnection
61
+ * @param {Object} payload
62
+ * @private
63
+ */
64
+ private _send;
65
+ }
66
+ /**
67
+ * Default configuration for WebSocket streaming
68
+ * @type {Object}
69
+ */
70
+ export const DEFAULT_CONFIG: any;
71
+ import { EventEmitter } from "events";
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Creates complete project directories from registered templates.
3
+ *
4
+ * @extends EventEmitter
5
+ * @fires ProjectScaffolder#created
6
+ *
7
+ * @example
8
+ * const scaffolder = new ProjectScaffolder();
9
+ * const result = scaffolder.create('document-qa', '/path/to/my-project');
10
+ * console.log(result.files); // list of created files
11
+ */
12
+ export class ProjectScaffolder extends EventEmitter<[never]> {
13
+ /**
14
+ * @param {Object} [options={}] - Scaffolder configuration
15
+ * @param {boolean} [options.installDependencies=false] - Whether to auto-run npm install
16
+ * @param {boolean} [options.overwrite=false] - Allow overwriting existing directories
17
+ */
18
+ constructor(options?: {
19
+ installDependencies?: boolean;
20
+ overwrite?: boolean;
21
+ });
22
+ config: any;
23
+ registry: TemplateRegistry;
24
+ /**
25
+ * Create a new project from a template.
26
+ *
27
+ * @param {string} templateKey - Key of the template to use
28
+ * @param {string} projectDir - Target directory for the new project
29
+ * @param {Object} [options={}] - Per-call overrides
30
+ * @param {boolean} [options.overwrite] - Override the instance-level overwrite setting
31
+ * @returns {{projectDir: string, files: string[], template: string}} Creation result
32
+ * @throws {Error} If template is not found or directory already exists
33
+ */
34
+ create(templateKey: string, projectDir: string, options?: {
35
+ overwrite?: boolean;
36
+ }): {
37
+ projectDir: string;
38
+ files: string[];
39
+ template: string;
40
+ };
41
+ /**
42
+ * List all available templates.
43
+ *
44
+ * @returns {Array<{key: string, name: string, description: string}>} Available templates
45
+ */
46
+ listTemplates(): Array<{
47
+ key: string;
48
+ name: string;
49
+ description: string;
50
+ }>;
51
+ }
52
+ /** @type {Object} Default configuration for the project scaffolder */
53
+ export const DEFAULT_CONFIG: any;
54
+ import { EventEmitter } from "events";
55
+ import { TemplateRegistry } from "./template-registry";
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Registry of built-in and custom project templates.
3
+ *
4
+ * @example
5
+ * const registry = new TemplateRegistry();
6
+ * const templates = registry.list();
7
+ * const template = registry.get('document-qa');
8
+ */
9
+ export class TemplateRegistry {
10
+ /** @type {Map<string, Object>} */
11
+ templates: Map<string, any>;
12
+ /**
13
+ * List all available templates.
14
+ *
15
+ * @returns {Array<{key: string, name: string, description: string}>} Summary of each template
16
+ */
17
+ list(): Array<{
18
+ key: string;
19
+ name: string;
20
+ description: string;
21
+ }>;
22
+ /**
23
+ * Get a full template definition by key.
24
+ *
25
+ * @param {string} templateKey - Template identifier
26
+ * @returns {Object|null} Full template object, or null if not found
27
+ */
28
+ get(templateKey: string): any | null;
29
+ /**
30
+ * Register a custom template.
31
+ *
32
+ * @param {string} key - Template identifier
33
+ * @param {Object} template - Template definition
34
+ * @param {string} template.name - Display name
35
+ * @param {string} template.description - Short description
36
+ * @param {Object} template.dependencies - npm dependencies
37
+ * @param {Object} template.config - Pipeline configuration
38
+ * @param {Object} template.files - Map of filename to file content
39
+ * @returns {void}
40
+ */
41
+ register(key: string, template: {
42
+ name: string;
43
+ description: string;
44
+ dependencies: any;
45
+ config: any;
46
+ files: any;
47
+ }): void;
48
+ /**
49
+ * Check if a template exists.
50
+ *
51
+ * @param {string} key - Template identifier
52
+ * @returns {boolean} Whether the template is registered
53
+ */
54
+ has(key: string): boolean;
55
+ }
56
+ /**
57
+ * @module templates/template-registry
58
+ * @description Registry of built-in project templates for RAG pipeline scaffolding.
59
+ */
60
+ /** @type {Object<string, Object>} Built-in template definitions */
61
+ export const TEMPLATES: {
62
+ [x: string]: any;
63
+ };
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Deterministic embedder: hashed bag of words, L2-normalised. Texts that
3
+ * share words get similar vectors, so retrieval ranks sensibly in tests.
4
+ */
5
+ export class HashEmbedder {
6
+ /**
7
+ * @param {Object} [options]
8
+ * @param {number} [options.dimensions=256] - Vector length
9
+ */
10
+ constructor({ dimensions }?: {
11
+ dimensions?: number;
12
+ });
13
+ dimensions: number;
14
+ metadata: {
15
+ name: string;
16
+ version: string;
17
+ type: string;
18
+ };
19
+ /**
20
+ * Cache identity for createRagPipeline({ cache }).
21
+ * @param {string} role
22
+ * @returns {string|null}
23
+ */
24
+ getCacheKey(role: string): string | null;
25
+ /** @private */
26
+ private _vector;
27
+ /**
28
+ * @param {string} text
29
+ * @param {{ signal?: AbortSignal }} [options]
30
+ * @returns {Promise<number[]>}
31
+ */
32
+ embed(text: string, { signal }?: {
33
+ signal?: AbortSignal;
34
+ }): Promise<number[]>;
35
+ /**
36
+ * Same as embed().
37
+ * @param {string} text
38
+ * @param {{ signal?: AbortSignal }} [options]
39
+ * @returns {Promise<number[]>}
40
+ */
41
+ embedQuery(text: string, options?: {
42
+ signal?: AbortSignal;
43
+ }): Promise<number[]>;
44
+ /**
45
+ * @param {string[]} texts
46
+ * @param {{ signal?: AbortSignal }} [options]
47
+ * @returns {Promise<number[][]>}
48
+ */
49
+ embedBatch(texts: string[], { signal }?: {
50
+ signal?: AbortSignal;
51
+ }): Promise<number[][]>;
52
+ }
53
+ /**
54
+ * LLM stand-in. Answers with `answer` (a string, or a function of the query
55
+ * and documents), or else with the top document's content. Every call is
56
+ * recorded in `calls`, so tests can assert on what the pipeline sent.
57
+ */
58
+ export class EchoLLM {
59
+ /**
60
+ * @param {Object} [options]
61
+ * @param {string|function(string, Array<Object>): string} [options.answer]
62
+ * @param {string} [options.fallback='No information found.'] - Answer when
63
+ * there are no documents and no `answer`
64
+ */
65
+ constructor({ answer, fallback }?: {
66
+ answer?: string | ((arg0: string, arg1: Array<any>) => string);
67
+ fallback?: string;
68
+ });
69
+ answer: string | ((arg0: string, arg1: Array<any>) => string);
70
+ fallback: string;
71
+ /** @type {Array<{query: string, docs: Array<Object>, options: Object}>} */
72
+ calls: Array<{
73
+ query: string;
74
+ docs: Array<any>;
75
+ options: any;
76
+ }>;
77
+ metadata: {
78
+ name: string;
79
+ version: string;
80
+ type: string;
81
+ };
82
+ /**
83
+ * Cache identity for createRagPipeline({ cache }); none when `answer` is a
84
+ * function, since its output cannot be identified.
85
+ * @param {string} role
86
+ * @returns {string|null}
87
+ */
88
+ getCacheKey(role: string): string | null;
89
+ /** @private */
90
+ private _answer;
91
+ /**
92
+ * @param {string} query
93
+ * @param {Array<Object>} [docs]
94
+ * @param {{ signal?: AbortSignal }} [options]
95
+ * @returns {Promise<string>}
96
+ */
97
+ generate(query: string, docs?: Array<any>, options?: {
98
+ signal?: AbortSignal;
99
+ }): Promise<string>;
100
+ /**
101
+ * Streams the same answer word by word, then a done chunk.
102
+ * @param {string} query
103
+ * @param {Array<Object>} [docs]
104
+ * @param {{ signal?: AbortSignal }} [options]
105
+ * @yields {{ token: string, done: boolean }}
106
+ */
107
+ generateStream(query: string, docs?: Array<any>, options?: {
108
+ signal?: AbortSignal;
109
+ }): AsyncGenerator<{
110
+ token: string;
111
+ done: boolean;
112
+ }, void, unknown>;
113
+ }
114
+ /** Short documents for tests and examples. */
115
+ export const fixtures: Readonly<{
116
+ documents: readonly (Readonly<{
117
+ id: "vacation";
118
+ content: "Full-time employees receive twenty days of paid vacation per year. Unused days carry over to March.";
119
+ metadata: Readonly<{
120
+ source: "vacation.md";
121
+ }>;
122
+ }> | Readonly<{
123
+ id: "remote-work";
124
+ content: "Employees may work remotely up to three days per week with manager approval.";
125
+ metadata: Readonly<{
126
+ source: "remote-work.md";
127
+ }>;
128
+ }> | Readonly<{
129
+ id: "expenses";
130
+ content: "Submit receipts within thirty days. Travel above 500 EUR needs pre-approval from finance.";
131
+ metadata: Readonly<{
132
+ source: "expenses.md";
133
+ }>;
134
+ }>)[];
135
+ }>;
136
+ /**
137
+ * A pipeline with HashEmbedder, a MemoryRetriever already holding
138
+ * `documents`, and EchoLLM (or the llm you pass).
139
+ *
140
+ * @example
141
+ * const { createTestPipeline } = require('@devilsdev/rag-pipeline-utils/testing');
142
+ * const { pipeline, llm } = await createTestPipeline();
143
+ * const result = await pipeline.run({ query: 'How many vacation days?' });
144
+ * // result.results[0].id === 'vacation'; llm.calls.length === 1
145
+ *
146
+ * @param {Object} [options]
147
+ * @param {Array<{id: string, content: string, metadata?: Object}>} [options.documents=fixtures.documents]
148
+ * @param {Object} [options.embedder] - Defaults to a new HashEmbedder
149
+ * @param {Object|null} [options.llm] - Defaults to a new EchoLLM; null for retrieval only
150
+ * @param {Object} [options.pipeline] - Extra createRagPipeline options (e.g. reranker)
151
+ * @returns {Promise<{ pipeline: Object, embedder: Object, retriever: MemoryRetriever, llm: Object|null }>}
152
+ */
153
+ export function createTestPipeline({ documents, embedder, llm, pipeline: pipelineOptions, }?: {
154
+ documents?: Array<{
155
+ id: string;
156
+ content: string;
157
+ metadata?: any;
158
+ }>;
159
+ embedder?: any;
160
+ llm?: any | null;
161
+ pipeline?: any;
162
+ }): Promise<{
163
+ pipeline: any;
164
+ embedder: any;
165
+ retriever: MemoryRetriever;
166
+ llm: any | null;
167
+ }>;
168
+ import { MemoryRetriever } from "./connectors/memory-retriever";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Embed a single query string with any supported embedder shape.
3
+ *
4
+ * Prefers embedQuery(); falls back to embed(). Accepts the common return
5
+ * shapes: a vector, a list of vectors, or [{ values | vector | embedding }].
6
+ *
7
+ * @param {object} embedder - Object with embedQuery() or embed()
8
+ * @param {string} query - Text to embed
9
+ * @param {{ signal?: AbortSignal }} [options] - Passed to the embedder as its
10
+ * second argument (only when given, so embedders keep their usual arity)
11
+ * @returns {Promise<number[]|undefined>} The query vector
12
+ */
13
+ export function embedQuery(embedder: object, query: string, options?: {
14
+ signal?: AbortSignal;
15
+ }): Promise<number[] | undefined>;
16
+ /**
17
+ * @param {object} [embedder]
18
+ * @returns {boolean} Whether embedQuery() can use this embedder
19
+ */
20
+ export function canEmbed(embedder?: object): boolean;
@@ -0,0 +1,50 @@
1
+ export const logger: StructuredLogger;
2
+ /**
3
+ * Create a logger with correlation ID for request tracing
4
+ */
5
+ export function createLogger(correlationId: any, context?: {}): StructuredLogger;
6
+ /**
7
+ * Middleware function for Express.js to add correlation IDs to requests
8
+ */
9
+ export function correlationMiddleware(req: any, res: any, next: any): void;
10
+ /**
11
+ * Enhanced logger with correlation ID support and structured context
12
+ */
13
+ export class StructuredLogger {
14
+ constructor(baseLogger: any);
15
+ logger: any;
16
+ correlationId: any;
17
+ context: {};
18
+ /**
19
+ * Create a child logger with correlation ID and context
20
+ */
21
+ child(context?: {}): StructuredLogger;
22
+ /**
23
+ * Set correlation ID for distributed tracing
24
+ */
25
+ setCorrelationId(correlationId: any): this;
26
+ /**
27
+ * Add persistent context to all log messages
28
+ */
29
+ setContext(context: any): this;
30
+ /**
31
+ * Log with automatic correlation ID and context injection
32
+ */
33
+ _log(level: any, message: any, meta?: {}): void;
34
+ info(message: any, meta: any): void;
35
+ error(message: any, meta: any): void;
36
+ warn(message: any, meta: any): void;
37
+ debug(message: any, meta: any): void;
38
+ /**
39
+ * Security audit logging with enhanced metadata
40
+ */
41
+ audit(action: any, meta?: {}): void;
42
+ /**
43
+ * Performance logging with timing information
44
+ */
45
+ performance(operation: any, duration: any, meta?: {}): void;
46
+ /**
47
+ * Tenant-specific logging for multi-tenant applications
48
+ */
49
+ tenant(tenantId: any, message: any, meta?: {}): void;
50
+ }