@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,64 @@
1
+ /**
2
+ * Tracks citations between an LLM-generated answer and retrieved source documents.
3
+ * Emits a 'tracked' event when citation analysis completes.
4
+ *
5
+ * @extends EventEmitter
6
+ */
7
+ export class CitationTracker extends EventEmitter<[never]> {
8
+ /**
9
+ * @param {object} [options] - Override default configuration
10
+ * @param {number} [options.similarityThreshold=0.5] - Minimum similarity for a citation match
11
+ * @param {number} [options.maxCitationsPerSentence=3] - Max citations per sentence
12
+ * @param {boolean} [options.useIDFWeighting=true] - Whether to apply IDF weighting
13
+ */
14
+ constructor(options?: {
15
+ similarityThreshold?: number;
16
+ maxCitationsPerSentence?: number;
17
+ useIDFWeighting?: boolean;
18
+ });
19
+ config: any;
20
+ /**
21
+ * Normalize a document object to ensure it has a usable text content string.
22
+ * Looks for .content, .text, or .chunk fields. If .chunk is a function, calls it and joins the result.
23
+ * @param {object} doc
24
+ * @returns {object} Normalized doc with .content field
25
+ * @private
26
+ */
27
+ private _normalizeDoc;
28
+ /**
29
+ * Track citations for an answer against retrieved documents.
30
+ *
31
+ * @param {string} answer - The LLM-generated answer text
32
+ * @param {Array<object>} retrievedDocs - Array of source documents (each should have .content, .text, or .chunk)
33
+ * @returns {{
34
+ * citations: Array<{sentence: string, sources: Array<{docId: string|undefined, docIndex: number, score: number}>}>,
35
+ * groundednessScore: number,
36
+ * hallucinationReport: object,
37
+ * metadata: {sentenceCount: number, docCount: number, config: object}
38
+ * }}
39
+ * @fires CitationTracker#tracked
40
+ */
41
+ track(answer: string, retrievedDocs: Array<object>): {
42
+ citations: Array<{
43
+ sentence: string;
44
+ sources: Array<{
45
+ docId: string | undefined;
46
+ docIndex: number;
47
+ score: number;
48
+ }>;
49
+ }>;
50
+ groundednessScore: number;
51
+ hallucinationReport: object;
52
+ metadata: {
53
+ sentenceCount: number;
54
+ docCount: number;
55
+ config: object;
56
+ };
57
+ };
58
+ }
59
+ /**
60
+ * Default configuration for the CitationTracker.
61
+ * @type {object}
62
+ */
63
+ export const DEFAULT_CONFIG: object;
64
+ import { EventEmitter } from "events";
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Detect hallucinations by analyzing citation results and classifying each sentence.
3
+ *
4
+ * Classification:
5
+ * - 'definite_hallucination': bestScore === 0 (no overlap with any source)
6
+ * - 'likely_hallucination': bestScore > 0 but below threshold
7
+ * - 'grounded': bestScore >= threshold
8
+ *
9
+ * @param {Array<{sentence: string, sources: Array<{docId: string|undefined, docIndex: number, score: number}>}>} citationResults
10
+ * @param {object} [options]
11
+ * @param {number} [options.threshold=0.5] - Score threshold for grounded classification
12
+ * @returns {{
13
+ * hallucinationRate: number,
14
+ * sentences: Array<{text: string, classification: string, bestScore: number, bestSource: object|null}>,
15
+ * summary: {grounded: number, likely_hallucination: number, definite_hallucination: number}
16
+ * }}
17
+ */
18
+ export function detectHallucinations(citationResults: Array<{
19
+ sentence: string;
20
+ sources: Array<{
21
+ docId: string | undefined;
22
+ docIndex: number;
23
+ score: number;
24
+ }>;
25
+ }>, options?: {
26
+ threshold?: number;
27
+ }): {
28
+ hallucinationRate: number;
29
+ sentences: Array<{
30
+ text: string;
31
+ classification: string;
32
+ bestScore: number;
33
+ bestSource: object | null;
34
+ }>;
35
+ summary: {
36
+ grounded: number;
37
+ likely_hallucination: number;
38
+ definite_hallucination: number;
39
+ };
40
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Map a sentence to its most relevant source documents by how much of the
3
+ * sentence each document supports (see computeSupportScore).
4
+ * @param {string} sentence - The sentence to map
5
+ * @param {Array<{content?: string, text?: string, id?: string}>} docs - Source documents
6
+ * @param {object} [options] - Configuration options
7
+ * @param {number} [options.maxCitations=3] - Maximum number of citations to return
8
+ * @param {number} [options.threshold=0.5] - Minimum similarity threshold
9
+ * @param {Map<string, number>|null} [options.idfWeights=null] - Optional IDF weights for weighted similarity
10
+ * @returns {Array<{docIndex: number, docId: string|undefined, score: number, matchedTokens: string[]}>}
11
+ */
12
+ export function mapSentenceToSources(sentence: string, docs: Array<{
13
+ content?: string;
14
+ text?: string;
15
+ id?: string;
16
+ }>, options?: {
17
+ maxCitations?: number;
18
+ threshold?: number;
19
+ idfWeights?: Map<string, number> | null;
20
+ }): Array<{
21
+ docIndex: number;
22
+ docId: string | undefined;
23
+ score: number;
24
+ matchedTokens: string[];
25
+ }>;
26
+ /**
27
+ * Build IDF (Inverse Document Frequency) weights from a collection of documents.
28
+ * IDF = log(1 + totalDocs / docsContainingToken). The +1 keeps weights
29
+ * positive, so tokens found in every document (and every token when only one
30
+ * document was retrieved) still count instead of weighing zero.
31
+ * @param {Array<{content?: string, text?: string}>} docs - Array of document objects
32
+ * @returns {Map<string, number>} Map of token to IDF weight
33
+ */
34
+ export function buildIDFWeights(docs: Array<{
35
+ content?: string;
36
+ text?: string;
37
+ }>): Map<string, number>;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * LLM connector for the Anthropic Claude API.
3
+ * Uses axios for HTTP calls and supports streaming via SSE.
4
+ *
5
+ * @extends BaseConnector
6
+ */
7
+ export class AnthropicConnector extends BaseConnector {
8
+ /**
9
+ * @param {Object} [options]
10
+ * @param {string} [options.model='claude-3-5-sonnet-20241022'] - Claude model to use
11
+ * @param {string} [options.apiKey] - Anthropic API key (defaults to ANTHROPIC_API_KEY at construction)
12
+ * @param {string} [options.baseURL='https://api.anthropic.com'] - API base URL
13
+ * @param {string} [options.apiVersion='2023-06-01'] - API version header
14
+ * @param {number} [options.maxTokens=4096] - Max tokens in response
15
+ * @param {number} [options.temperature=0.7] - Sampling temperature
16
+ * @param {number} [options.maxRetries=3] - Retries for transient failures
17
+ * @param {number} [options.retryDelay=1000] - Base backoff delay in ms
18
+ * @param {string} [options.systemPrompt] - System prompt used when RAG context is supplied
19
+ */
20
+ constructor(options?: {
21
+ model?: string;
22
+ apiKey?: string;
23
+ baseURL?: string;
24
+ apiVersion?: string;
25
+ maxTokens?: number;
26
+ temperature?: number;
27
+ maxRetries?: number;
28
+ retryDelay?: number;
29
+ systemPrompt?: string;
30
+ });
31
+ /**
32
+ * Cache identity for createRagPipeline({ cache }).
33
+ * @param {'llm'} role
34
+ * @returns {string|null}
35
+ */
36
+ getCacheKey(role: "llm"): string | null;
37
+ config: any;
38
+ client: import("axios").AxiosInstance;
39
+ /**
40
+ * @throws {Error} code MISSING_API_KEY when no key is configured
41
+ * @private
42
+ */
43
+ private _requireApiKey;
44
+ /**
45
+ * Build the Messages API request body. Retrieved context goes into the
46
+ * user message as delimited, untrusted reference data; the system prompt
47
+ * only carries instructions.
48
+ * @private
49
+ */
50
+ private _buildBody;
51
+ /**
52
+ * Generate a response from Claude using the provided query and optional RAG context.
53
+ *
54
+ * @param {string} query - The user query / prompt
55
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
56
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
57
+ * @param {AbortSignal} [options.signal] - Cancels the request
58
+ * @returns {Promise<string>} The generated text
59
+ */
60
+ generate(query: string, context?: Array<any | string>, options?: {
61
+ signal?: AbortSignal;
62
+ }): Promise<string>;
63
+ /**
64
+ * Stream a response from Claude token-by-token via SSE.
65
+ *
66
+ * @param {string} query - The user query / prompt
67
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
68
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
69
+ * @param {AbortSignal} [options.signal] - Cancels the stream
70
+ * @yields {{ token: string, done: boolean }}
71
+ */
72
+ generateStream(query: string, context?: Array<any | string>, options?: {
73
+ signal?: AbortSignal;
74
+ }): AsyncGenerator<{
75
+ token: any;
76
+ done: boolean;
77
+ }, void, unknown>;
78
+ /**
79
+ * Build a single prompt string that includes RAG context when available.
80
+ * Kept for backward compatibility; the context is delimited and labelled
81
+ * as untrusted reference data.
82
+ *
83
+ * @param {string} query - User query
84
+ * @param {Array<Object|string>} context - RAG context documents
85
+ * @returns {string} Combined prompt
86
+ * @private
87
+ */
88
+ private _buildPrompt;
89
+ }
90
+ /**
91
+ * Default configuration for the Anthropic connector.
92
+ * `apiKey` is a getter so the environment is read when a connector is
93
+ * constructed, not when this module is first required.
94
+ * @type {Object}
95
+ */
96
+ export const DEFAULT_CONFIG: any;
97
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Abstract base class for all connectors.
3
+ * Provides connection lifecycle, health checking, and retry logic.
4
+ * @extends EventEmitter
5
+ */
6
+ export class BaseConnector extends EventEmitter<[never]> {
7
+ /**
8
+ * @param {Object} options
9
+ * @param {string} [options.name] - Connector display name
10
+ */
11
+ constructor(options?: {
12
+ name?: string;
13
+ });
14
+ options: {
15
+ name?: string;
16
+ };
17
+ connected: boolean;
18
+ name: string;
19
+ /**
20
+ * Establish the connection.
21
+ * Override in subclass for custom connection logic.
22
+ * @returns {Promise<void>}
23
+ */
24
+ connect(): Promise<void>;
25
+ /**
26
+ * Tear down the connection.
27
+ * Override in subclass for custom disconnection logic.
28
+ * @returns {Promise<void>}
29
+ */
30
+ disconnect(): Promise<void>;
31
+ /**
32
+ * Check whether the connector is healthy and operational.
33
+ * Override in subclass for custom health checks.
34
+ * @returns {Promise<boolean>}
35
+ */
36
+ isHealthy(): Promise<boolean>;
37
+ /**
38
+ * Retry wrapper for transient failures.
39
+ *
40
+ * Only retryable errors are retried: network errors and HTTP
41
+ * 408/409/425/429/5xx (see {@link isRetryableError}). Other errors
42
+ * (400, 401, 403, 404, aborts, errors with no status or network code) are
43
+ * thrown immediately. Backoff is exponential with full jitter, starting at
44
+ * `delay` and capped at `opts.maxDelay`; a Retry-After header on the error
45
+ * is honoured (capped at `opts.maxDelay`). Emits a 'retry' event before
46
+ * each retry.
47
+ *
48
+ * @param {Function} fn - Async function to execute; receives the attempt number
49
+ * @param {number} [retries=3] - Maximum number of retry attempts
50
+ * @param {number} [delay=1000] - Base backoff delay in ms
51
+ * @param {object} [opts]
52
+ * @param {AbortSignal} [opts.signal] - Aborts the call and any pending backoff
53
+ * @param {number} [opts.maxDelay=30000] - Upper bound for a single backoff delay
54
+ * @param {(err: *) => boolean} [opts.shouldRetry] - Override retry classification
55
+ * @returns {Promise<*>} Result of the function
56
+ * @throws {Error} The first non-retryable error, or the last error once retries are exhausted
57
+ */
58
+ withRetry(fn: Function, retries?: number, delay?: number, opts?: {
59
+ signal?: AbortSignal;
60
+ maxDelay?: number;
61
+ shouldRetry?: (err: any) => boolean;
62
+ }): Promise<any>;
63
+ /**
64
+ * Wait between retries. Overridable in tests.
65
+ * @param {number} ms
66
+ * @param {AbortSignal} [signal]
67
+ * @returns {Promise<void>}
68
+ * @protected
69
+ */
70
+ protected _sleep(ms: number, signal?: AbortSignal): Promise<void>;
71
+ /**
72
+ * Jitter source for retry backoff. Overridable in tests.
73
+ * @returns {number} Value in [0, 1)
74
+ * @protected
75
+ */
76
+ protected _random(): number;
77
+ /**
78
+ * Return basic information about the connector.
79
+ * @returns {{ name: string, connected: boolean, type: string }}
80
+ */
81
+ getInfo(): {
82
+ name: string;
83
+ connected: boolean;
84
+ type: string;
85
+ };
86
+ }
87
+ import { EventEmitter } from "events";
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Embedder + reranker connector for the Cohere API.
3
+ * Provides text embeddings (with separate document/query input types) and
4
+ * document reranking capabilities.
5
+ *
6
+ * @extends BaseConnector
7
+ */
8
+ export class CohereConnector extends BaseConnector {
9
+ /**
10
+ * @param {Object} [options]
11
+ * @param {string} [options.apiKey] - Cohere API key
12
+ * @param {string} [options.baseURL='https://api.cohere.ai/v1'] - API base URL
13
+ * @param {string} [options.embeddingModel='embed-english-v3.0'] - Embedding model
14
+ * @param {string} [options.rerankModel='rerank-english-v3.0'] - Reranking model
15
+ * @param {string} [options.inputType='search_document'] - Input type for document embeddings
16
+ * @param {string} [options.queryInputType='search_query'] - Input type for query embeddings
17
+ */
18
+ constructor(options?: {
19
+ apiKey?: string;
20
+ baseURL?: string;
21
+ embeddingModel?: string;
22
+ rerankModel?: string;
23
+ inputType?: string;
24
+ queryInputType?: string;
25
+ });
26
+ /**
27
+ * Cache identity for createRagPipeline({ cache }).
28
+ * @param {'embedder'} role
29
+ * @returns {string|null}
30
+ */
31
+ getCacheKey(role: "embedder"): string | null;
32
+ config: any;
33
+ client: import("axios").AxiosInstance;
34
+ /**
35
+ * @throws {Error} code MISSING_API_KEY when no key is configured
36
+ * @private
37
+ */
38
+ private _requireApiKey;
39
+ /**
40
+ * POST with the connector's retry policy and cancellation.
41
+ * @param {string} path
42
+ * @param {object} body
43
+ * @param {AbortSignal} [signal]
44
+ * @returns {Promise<object>} Response data
45
+ * @private
46
+ */
47
+ private _post;
48
+ /**
49
+ * Generate an embedding vector for document text.
50
+ * Uses the document input type by default.
51
+ *
52
+ * @param {string} text - Input text to embed
53
+ * @param {Object} [options={}]
54
+ * @param {AbortSignal} [options.signal] - Cancels the request
55
+ * @returns {Promise<number[]>} Embedding vector
56
+ */
57
+ embed(text: string, options?: {
58
+ signal?: AbortSignal;
59
+ }): Promise<number[]>;
60
+ /**
61
+ * Generate an embedding vector for a search query.
62
+ * Uses the query input type for better retrieval accuracy.
63
+ *
64
+ * @param {string} query - Query text to embed
65
+ * @param {Object} [options={}]
66
+ * @param {AbortSignal} [options.signal] - Cancels the request
67
+ * @returns {Promise<number[]>} Embedding vector
68
+ */
69
+ embedQuery(query: string, options?: {
70
+ signal?: AbortSignal;
71
+ }): Promise<number[]>;
72
+ /**
73
+ * Rerank documents by relevance to a query using Cohere's reranker.
74
+ *
75
+ * @param {string} query - The search query
76
+ * @param {Array<Object|string>} documents - Documents to rerank
77
+ * @param {Object} [options={}]
78
+ * @param {number} [options.topK] - Number of top results to return (defaults to all)
79
+ * @param {AbortSignal} [options.signal] - Cancels the request
80
+ * @returns {Promise<Array<Object>>} Reranked documents with relevance scores
81
+ */
82
+ rerank(query: string, documents: Array<any | string>, options?: {
83
+ topK?: number;
84
+ signal?: AbortSignal;
85
+ }): Promise<Array<any>>;
86
+ }
87
+ /**
88
+ * Default configuration for the Cohere connector.
89
+ * `apiKey` is a getter so the environment is read when a connector is
90
+ * constructed, not when this module is first required.
91
+ * @type {Object}
92
+ */
93
+ export const DEFAULT_CONFIG: any;
94
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Create an AbortError for the given signal.
3
+ * Reuses signal.reason when it already is an AbortError.
4
+ *
5
+ * @param {AbortSignal} [signal]
6
+ * @returns {Error} Error with name 'AbortError' and code 'ABORT_ERR'
7
+ */
8
+ export function createAbortError(signal?: AbortSignal): Error;
9
+ /**
10
+ * @param {*} err
11
+ * @returns {boolean} True when err represents a cancellation.
12
+ */
13
+ export function isAbortError(err: any): boolean;
14
+ /**
15
+ * Throw an AbortError when the signal is already aborted.
16
+ * @param {AbortSignal} [signal]
17
+ */
18
+ export function throwIfAborted(signal?: AbortSignal): void;
19
+ /**
20
+ * Race a promise against an AbortSignal so callers reject promptly even when
21
+ * the underlying SDK or HTTP client ignores the signal. The abort listener is
22
+ * removed once the promise settles.
23
+ *
24
+ * @template T
25
+ * @param {Promise<T>|(() => Promise<T>)} work - Promise or function returning one
26
+ * @param {AbortSignal} [signal]
27
+ * @returns {Promise<T>}
28
+ */
29
+ export function raceAbort<T>(work: Promise<T> | (() => Promise<T>), signal?: AbortSignal): Promise<T>;
30
+ /**
31
+ * Sleep that rejects with AbortError as soon as the signal aborts.
32
+ * @param {number} ms
33
+ * @param {AbortSignal} [signal]
34
+ * @returns {Promise<void>}
35
+ */
36
+ export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void>;
37
+ /**
38
+ * Extract the HTTP status from an openai SDK error or an axios error.
39
+ * @param {*} err
40
+ * @returns {number|undefined}
41
+ */
42
+ export function getErrorStatus(err: any): number | undefined;
43
+ /**
44
+ * Parse Retry-After / retry-after-ms from an error's response headers.
45
+ *
46
+ * @param {*} err
47
+ * @param {number} [now=Date.now()]
48
+ * @returns {number|undefined} Delay in milliseconds, or undefined when absent
49
+ */
50
+ export function getRetryAfterMs(err: any, now?: number): number | undefined;
51
+ /**
52
+ * Default retry classification: network failures and HTTP
53
+ * 408/409/425/429/5xx are retried; aborts, other 4xx (400, 401, 403, 404,
54
+ * 422, ...) and errors without a status or network code are not.
55
+ *
56
+ * @param {*} err
57
+ * @returns {boolean}
58
+ */
59
+ export function isRetryableError(err: any): boolean;
60
+ /**
61
+ * Compute the delay before the next retry attempt.
62
+ * Honours Retry-After (capped at maxDelay); otherwise uses exponential backoff
63
+ * with full jitter: random() * min(maxDelay, baseDelay * 2^attempt).
64
+ *
65
+ * @param {*} err - The error that triggered the retry
66
+ * @param {number} attempt - Zero-based retry attempt
67
+ * @param {object} [opts]
68
+ * @param {number} [opts.baseDelay=1000]
69
+ * @param {number} [opts.maxDelay=30000]
70
+ * @param {() => number} [opts.random=Math.random]
71
+ * @returns {number} Delay in milliseconds
72
+ */
73
+ export function computeRetryDelay(err: any, attempt: number, opts?: {
74
+ baseDelay?: number;
75
+ maxDelay?: number;
76
+ random?: () => number;
77
+ }): number;
78
+ /**
79
+ * Resolve an API key at construction time. An explicit option (even '')
80
+ * wins over the environment variable.
81
+ *
82
+ * @param {object} options - Connector options
83
+ * @param {string} envVar - Environment variable name
84
+ * @returns {string}
85
+ */
86
+ export function resolveApiKey(options: object, envVar: string): string;
87
+ /**
88
+ * Error thrown when a provider call is attempted without an API key.
89
+ * @param {string} provider - Display name, e.g. 'OpenAI'
90
+ * @param {string} envVar - Environment variable name
91
+ * @returns {Error}
92
+ */
93
+ export function missingApiKeyError(provider: string, envVar: string): Error;
94
+ /**
95
+ * Build request options carrying the signal only when one was supplied, so
96
+ * calls without a signal look exactly as before.
97
+ * @param {AbortSignal} [signal]
98
+ * @returns {object}
99
+ */
100
+ export function signalOptions(signal?: AbortSignal): object;
101
+ /**
102
+ * Shared helpers for the built-in connectors: AbortSignal handling, retry
103
+ * classification and backoff, and API key resolution.
104
+ *
105
+ * Everything here must run on Node 18 (no AbortSignal.any, no crypto.hash).
106
+ */
107
+ /** HTTP status codes that are worth retrying. */
108
+ export const RETRYABLE_STATUS: Set<number>;
109
+ /** Error codes produced by Node, axios and undici for transient network failures. */
110
+ export const RETRYABLE_CODES: Set<string>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * TF-IDF based embedder for fully offline use.
3
+ * No external API required -- builds a vocabulary from training documents
4
+ * and produces sparse TF-IDF vectors.
5
+ * @extends BaseConnector
6
+ */
7
+ export class LocalEmbedder extends BaseConnector {
8
+ /**
9
+ * @param {Object} options
10
+ * @param {number} [options.maxVocabularySize=10000] - Maximum vocabulary size
11
+ * @param {number} [options.minDocFrequency=1] - Minimum document frequency for a token to be included
12
+ */
13
+ constructor(options?: {
14
+ maxVocabularySize?: number;
15
+ minDocFrequency?: number;
16
+ });
17
+ config: any;
18
+ /** @type {Map<string, number>} token -> vocabulary index */
19
+ vocabulary: Map<string, number>;
20
+ /** @type {Map<string, number>} token -> IDF weight */
21
+ idf: Map<string, number>;
22
+ /** @type {number} */
23
+ docCount: number;
24
+ /**
25
+ * Build vocabulary and IDF weights from a corpus of documents.
26
+ * @param {Array<string|{ content?: string, text?: string }>} documents - Training documents
27
+ */
28
+ train(documents: Array<string | {
29
+ content?: string;
30
+ text?: string;
31
+ }>): void;
32
+ _fingerprint: string;
33
+ /**
34
+ * Compute a TF-IDF vector for the given text.
35
+ * The vector length equals the vocabulary size. Synchronous; when
36
+ * options.signal is already aborted it throws an AbortError (which an
37
+ * awaiting caller sees as a rejection).
38
+ * @param {string} text - Text to embed
39
+ * @param {Object} [options={}]
40
+ * @param {AbortSignal} [options.signal] - Cancellation signal
41
+ * @returns {number[]} L2-normalized TF-IDF vector
42
+ */
43
+ embed(text: string, options?: {
44
+ signal?: AbortSignal;
45
+ }): number[];
46
+ /**
47
+ * Compute a TF-IDF vector for a query string.
48
+ * Alias for {@link embed}.
49
+ * @param {string} query - Query text to embed
50
+ * @param {Object} [options={}] - Same as embed()
51
+ * @returns {number[]} L2-normalized TF-IDF vector
52
+ */
53
+ embedQuery(query: string, options?: any): number[];
54
+ /**
55
+ * Serializable vocabulary and IDF weights, so a trained embedder can be
56
+ * restored in another process (e.g. by FileVectorStore-backed CLI queries).
57
+ *
58
+ * @returns {{docCount: number, vocabulary: Array<[string, number]>, idf: Array<[string, number]>}}
59
+ */
60
+ getState(): {
61
+ docCount: number;
62
+ vocabulary: Array<[string, number]>;
63
+ idf: Array<[string, number]>;
64
+ };
65
+ /**
66
+ * Restore state produced by getState().
67
+ * @param {{docCount: number, vocabulary: Array<[string, number]>, idf: Array<[string, number]>}} state
68
+ */
69
+ setState(state: {
70
+ docCount: number;
71
+ vocabulary: Array<[string, number]>;
72
+ idf: Array<[string, number]>;
73
+ }): void;
74
+ /**
75
+ * Cache identity for createRagPipeline({ cache }): a fingerprint of the
76
+ * trained vocabulary and IDF weights, so retraining invalidates cached
77
+ * query vectors (also across processes sharing a Redis cache).
78
+ * @param {'embedder'} role
79
+ * @returns {string|null}
80
+ */
81
+ getCacheKey(role: "embedder"): string | null;
82
+ /** @returns {number} Vector length produced by embed() once trained */
83
+ get dimensions(): number;
84
+ /**
85
+ * Get the current vocabulary size.
86
+ * @returns {number}
87
+ */
88
+ getVocabularySize(): number;
89
+ }
90
+ /**
91
+ * Default configuration for the local TF-IDF embedder.
92
+ * @type {Object}
93
+ */
94
+ export const DEFAULT_CONFIG: any;
95
+ import { BaseConnector } from "./base-connector";