@denizsvnc/ai-rag-engine 0.0.0-stage → 2.2.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 (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -0
  3. package/README.md +115 -2
  4. package/dist/adapters/cache/index.d.ts +1 -0
  5. package/dist/adapters/cache/redis-cache.adapter.d.ts +49 -0
  6. package/dist/adapters/faq/local-faq.adapter.d.ts +29 -0
  7. package/dist/adapters/faq/url-faq.adapter.d.ts +14 -0
  8. package/dist/adapters/llm/custom.adapter.d.ts +42 -0
  9. package/dist/adapters/llm/fallback.adapter.d.ts +10 -0
  10. package/dist/adapters/llm/gemini.adapter.d.ts +9 -0
  11. package/dist/adapters/llm/ollama.adapter.d.ts +30 -0
  12. package/dist/adapters/llm/openai.adapter.d.ts +10 -0
  13. package/dist/adapters/llm/openrouter.adapter.d.ts +6 -0
  14. package/dist/adapters/llm/tiered.adapter.d.ts +22 -0
  15. package/dist/adapters/rules/static-rules.adapter.d.ts +6 -0
  16. package/dist/adapters/vector/memory-vector.adapter.d.ts +33 -0
  17. package/dist/adapters/vector/postgres-vector.adapter.d.ts +51 -0
  18. package/dist/api/auth.d.ts +47 -0
  19. package/dist/api/middleware.d.ts +3 -0
  20. package/dist/api/rate-limit.d.ts +8 -0
  21. package/dist/api/routes.d.ts +9 -0
  22. package/dist/api/server.d.ts +1 -0
  23. package/dist/api/server.js +4433 -0
  24. package/dist/config/default.d.ts +22 -0
  25. package/dist/config/ingestion-runtime.d.ts +11 -0
  26. package/dist/core/cache-manager.d.ts +29 -0
  27. package/dist/core/engine.d.ts +75 -0
  28. package/dist/core/ingestion/ingestion-worker.d.ts +19 -0
  29. package/dist/core/ingestion/postgres-ingestion-store.d.ts +56 -0
  30. package/dist/core/ingestion/queued-ingestion.service.d.ts +35 -0
  31. package/dist/core/metrics/prometheus-exporter.d.ts +12 -0
  32. package/dist/core/metrics/rag-evaluator.d.ts +63 -0
  33. package/dist/core/metrics/token-tracker.d.ts +69 -0
  34. package/dist/core/prompt-builder.d.ts +20 -0
  35. package/dist/core/queue/bullmq-queue.d.ts +39 -0
  36. package/dist/core/queue/in-memory-queue.d.ts +24 -0
  37. package/dist/core/queue/job-queue.interface.d.ts +22 -0
  38. package/dist/core/queue/queue-factory.d.ts +12 -0
  39. package/dist/core/security/confirmation.d.ts +64 -0
  40. package/dist/core/security/injection-detector.d.ts +25 -0
  41. package/dist/core/security/nonce-store.d.ts +21 -0
  42. package/dist/core/security/pii-guard.d.ts +38 -0
  43. package/dist/core/security/sanitizer.d.ts +23 -0
  44. package/dist/core/security/secrets.d.ts +2 -0
  45. package/dist/core/security/security-guard.d.ts +18 -0
  46. package/dist/core/security/security.types.d.ts +38 -0
  47. package/dist/core/sml-engine.d.ts +65 -0
  48. package/dist/core/tool-registry.d.ts +17 -0
  49. package/dist/core/vector/bm25.d.ts +44 -0
  50. package/dist/core/vector/hybrid-search.d.ts +15 -0
  51. package/dist/index.d.ts +51 -0
  52. package/dist/index.js +4509 -0
  53. package/dist/interfaces/cache.interface.d.ts +8 -0
  54. package/dist/interfaces/engine-config.interface.d.ts +73 -0
  55. package/dist/interfaces/faq.interface.d.ts +17 -0
  56. package/dist/interfaces/ingestion.interface.d.ts +14 -0
  57. package/dist/interfaces/llm.interface.d.ts +22 -0
  58. package/dist/interfaces/query-context.interface.d.ts +33 -0
  59. package/dist/interfaces/rules.interface.d.ts +3 -0
  60. package/dist/interfaces/tool.interface.d.ts +50 -0
  61. package/dist/interfaces/vector.interface.d.ts +15 -0
  62. package/dist/scripts/migrate-vector.d.ts +1 -0
  63. package/dist/scripts/migrate-vector.js +627 -0
  64. package/dist/services/document-ingestion.service.d.ts +116 -0
  65. package/dist/utils/http.d.ts +2 -0
  66. package/dist/utils/math.d.ts +3 -0
  67. package/dist/worker.d.ts +1 -0
  68. package/dist/worker.js +1787 -0
  69. package/docs/RELEASING.md +55 -0
  70. package/docs/USAGE.md +148 -0
  71. package/package.json +95 -4
@@ -0,0 +1,38 @@
1
+ export interface PIIPolicy {
2
+ enabled?: boolean;
3
+ maskTCKN?: boolean;
4
+ maskCreditCards?: boolean;
5
+ maskIBAN?: boolean;
6
+ maskEmails?: boolean;
7
+ maskPhones?: boolean;
8
+ allowUnmaskedForLocalLLM?: boolean;
9
+ providerType?: 'cloud' | 'local' | 'custom';
10
+ }
11
+ export interface PIISanitizationResult {
12
+ sanitizedText: string;
13
+ hasPII: boolean;
14
+ detectedEntities: Array<{
15
+ type: 'TCKN' | 'CREDIT_CARD' | 'IBAN' | 'EMAIL' | 'PHONE';
16
+ originalValue: string;
17
+ maskedValue: string;
18
+ }>;
19
+ bypassedForLocalLLM: boolean;
20
+ }
21
+ export declare class PIIGuard {
22
+ /**
23
+ * Validates Turkish Republic Identity Number (TCKN) using official 11-digit checksum rules:
24
+ * 1. 11 digits, cannot start with 0.
25
+ * 2. 10th digit = ((d1+d3+d5+d7+d9)*7 - (d2+d4+d6+d8)) mod 10
26
+ * 3. 11th digit = (d1+d2+...+d10) mod 10
27
+ */
28
+ static isValidTCKN(candidate: string): boolean;
29
+ /**
30
+ * Validates Credit Card number using the Luhn mod-10 algorithm.
31
+ */
32
+ static isValidCreditCard(candidate: string): boolean;
33
+ /**
34
+ * Sanitizes input text, detecting and masking all sensitive PII entities.
35
+ * Respects data sovereignty policies: strictly masks for Cloud LLMs.
36
+ */
37
+ static sanitize(text: string, policy?: PIIPolicy): PIISanitizationResult;
38
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Cleanses and neutralizes raw untrusted visitor input.
3
+ */
4
+ export declare class InputSanitizer {
5
+ /**
6
+ * Regex matching zero-width invisible characters, byte-order marks, and unsafe control chars.
7
+ * Frequently leveraged by attackers to hide prompt injection payloads from simple filters.
8
+ */
9
+ private static readonly INVISIBLE_CHARS_REGEX;
10
+ /**
11
+ * Tags and delimiters commonly used in prompt sandboxing and LLM chat templates.
12
+ */
13
+ private static readonly DELIMITER_ESCAPE_REGEX;
14
+ /**
15
+ * Sanitizes raw visitor input by stripping invisible chars, neutralizing delimiter breakout tags,
16
+ * and bounding input length.
17
+ */
18
+ /**
19
+ * Strips invisible zero-width unicode characters, byte-order marks, and control bytes.
20
+ */
21
+ static stripZeroWidth(rawInput: string): string;
22
+ static sanitize(rawInput: string, maxLength?: number): string;
23
+ }
@@ -0,0 +1,2 @@
1
+ /** Development keys are unpredictable and process-local. Production never falls back. */
2
+ export declare function resolveSecret(name: string, supplied?: string): string;
@@ -0,0 +1,18 @@
1
+ import type { SecurityConfig, InjectionCheckResult } from './security.types.js';
2
+ /**
3
+ * Enterprise Security Guardrail for the RAG Engine.
4
+ * Provides pre-flight input sanitization, heuristic attack detection,
5
+ * PII masking (TCKN, Credit Cards, IBAN), and untrusted visitor boundary formatting.
6
+ */
7
+ export declare class SecurityGuard {
8
+ /**
9
+ * Inspects, sanitizes, redacts PII, and assesses security risk of incoming visitor input.
10
+ */
11
+ static inspect(rawInput: string, config?: SecurityConfig): InjectionCheckResult;
12
+ /**
13
+ * Wraps visitor text into an explicit untrusted XML sandbox tag.
14
+ * Tells the LLM that this text represents unverified data from a website visitor
15
+ * and MUST NOT be treated as system-level instructions or behavioral overrides.
16
+ */
17
+ static frameVisitorMessage(sanitizedText: string): string;
18
+ }
@@ -0,0 +1,38 @@
1
+ import type { PIIPolicy } from './pii-guard.js';
2
+ export type RiskLevel = 'NONE' | 'LOW' | 'MEDIUM' | 'HIGH';
3
+ export interface InjectionCheckResult {
4
+ isRisk: boolean;
5
+ riskLevel: RiskLevel;
6
+ matchedPatterns: string[];
7
+ sanitizedInput: string;
8
+ }
9
+ export interface SecurityConfig {
10
+ /**
11
+ * Whether prompt injection defense and input sanitization are enabled.
12
+ * Defaults to true.
13
+ */
14
+ enabled?: boolean | undefined;
15
+ /**
16
+ * If true, queries detected as high-risk prompt injection attacks are blocked
17
+ * immediately without invoking LLM or tool execution.
18
+ * Defaults to true.
19
+ */
20
+ blockHighRiskInjections?: boolean | undefined;
21
+ /**
22
+ * Maximum character length allowed for user input to prevent token flooding DoS.
23
+ * Defaults to 4000.
24
+ */
25
+ maxInputLength?: number | undefined;
26
+ /**
27
+ * Custom response returned to the visitor when an injection attempt is blocked.
28
+ */
29
+ customRefusalMessage?: string | undefined;
30
+ /**
31
+ * Additional regex patterns to classify as prompt injection attacks.
32
+ */
33
+ customInjectionPatterns?: RegExp[] | undefined;
34
+ /**
35
+ * Data Privacy & Sovereignty policy for masking sensitive PII (TCKN, Credit Cards, IBAN, etc.).
36
+ */
37
+ pii?: PIIPolicy | undefined;
38
+ }
@@ -0,0 +1,65 @@
1
+ /** Stable SDK boundary: transformer implementation types are kept private. */
2
+ export interface EmbeddingExtractor {
3
+ (text: string | string[], options: {
4
+ pooling: 'mean';
5
+ normalize: boolean;
6
+ }): Promise<{
7
+ data: Float32Array;
8
+ dims: number[];
9
+ }>;
10
+ }
11
+ export declare class CircuitBreakerOpenError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ export interface SMLEngineConfig {
15
+ cacheDir?: string | undefined;
16
+ localFilesOnly?: boolean | undefined;
17
+ modelName?: string | undefined;
18
+ cacheSize?: number | undefined;
19
+ dtype?: 'q8' | 'fp32' | 'fp16' | 'q4' | undefined;
20
+ quantized?: boolean | undefined;
21
+ circuitBreakerThreshold?: number | undefined;
22
+ circuitBreakerCooldownMs?: number | undefined;
23
+ }
24
+ export declare class SMLEngine {
25
+ private readonly modelName;
26
+ private readonly cacheDir;
27
+ private readonly localFilesOnly;
28
+ private readonly dtype;
29
+ private extractorPromise;
30
+ private embeddingCache;
31
+ private circuitState;
32
+ private failureCount;
33
+ private lastFailureTime;
34
+ private readonly failureThreshold;
35
+ private readonly cooldownMs;
36
+ constructor(config?: SMLEngineConfig);
37
+ /**
38
+ * Resets the circuit breaker state (useful for testing and recovery).
39
+ */
40
+ resetCircuit(): void;
41
+ getCircuitState(): 'CLOSED' | 'OPEN' | 'HALF_OPEN';
42
+ getFailureCount(): number;
43
+ /**
44
+ * Thread-safe pipeline initializer guarded by a Circuit Breaker.
45
+ */
46
+ init(): Promise<EmbeddingExtractor>;
47
+ /**
48
+ * Generates a normalized embedding vector for a single text input (with LRU caching).
49
+ */
50
+ getEmbedding(text: string): Promise<Float32Array>;
51
+ /**
52
+ * Generates embedding vectors for multiple texts in batch mode.
53
+ */
54
+ getBatchEmbeddings(texts: string[]): Promise<Float32Array[]>;
55
+ /**
56
+ * Compares the query against target embeddings and returns the highest scoring match above the threshold.
57
+ */
58
+ findBestMatch<T extends {
59
+ id: string;
60
+ embedding: number[] | Float32Array;
61
+ }>(query: string, targets: T[], threshold?: number): Promise<{
62
+ target: T;
63
+ score: number;
64
+ } | null>;
65
+ }
@@ -0,0 +1,17 @@
1
+ import type { IAgentTool } from '../interfaces/tool.interface.js';
2
+ import { SMLEngine } from './sml-engine.js';
3
+ export declare class ToolRegistry {
4
+ private smlEngine;
5
+ private registryPath;
6
+ private activeTools;
7
+ private toolEmbeddings;
8
+ constructor(smlEngine: SMLEngine, registryPath?: string);
9
+ initialize(tools: IAgentTool[]): Promise<void>;
10
+ registerTool(tool: IAgentTool): Promise<void>;
11
+ getTool(name: string): IAgentTool | undefined;
12
+ getAllTools(): IAgentTool[];
13
+ /**
14
+ * Routes a user query to the most semantically relevant tool.
15
+ */
16
+ routeQueryToTool(query: string, threshold?: number): Promise<IAgentTool | null>;
17
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Zero-dependency BM25 (Best Matching 25) Sparse Keyword Retrieval.
3
+ * Provides lexical term matching (exact SKU codes, error messages, proper nouns, part numbers)
4
+ * to complement dense semantic vector search.
5
+ */
6
+ export interface BM25Document {
7
+ id: string;
8
+ content: string;
9
+ metadata?: Record<string, any> | undefined;
10
+ }
11
+ export declare class BM25Index {
12
+ private docCount;
13
+ private avgDocLength;
14
+ private docLengths;
15
+ private docTermFreqs;
16
+ private termDocFreqs;
17
+ private documents;
18
+ private readonly k1;
19
+ private readonly b;
20
+ constructor(options?: {
21
+ k1?: number;
22
+ b?: number;
23
+ });
24
+ /**
25
+ * Tokenizes text into lowercase normalized alphanumeric terms.
26
+ */
27
+ private tokenize;
28
+ /**
29
+ * Indexes a collection of documents.
30
+ */
31
+ index(docs: BM25Document[]): void;
32
+ /**
33
+ * Computes the Robertson-Spärck Jones IDF for a query term.
34
+ */
35
+ private computeIDF;
36
+ /**
37
+ * Scores documents against a search query using the Okapi BM25 formula.
38
+ */
39
+ search(query: string, topK?: number, filter?: Record<string, any>): Array<{
40
+ document: BM25Document;
41
+ score: number;
42
+ }>;
43
+ clear(): void;
44
+ }
@@ -0,0 +1,15 @@
1
+ import type { VectorDocument } from '../../interfaces/vector.interface.js';
2
+ export interface HybridScoredDocument extends VectorDocument {
3
+ denseRank?: number | undefined;
4
+ sparseRank?: number | undefined;
5
+ rrfScore: number;
6
+ }
7
+ /**
8
+ * Reciprocal Rank Fusion (RRF) algorithm.
9
+ * Combines dense vector semantic rankings and sparse BM25 lexical rankings into
10
+ * a single high-precision ranking without needing score normalization.
11
+ *
12
+ * Formula: RRF_score(d) = sum_{m in models} 1 / (k + rank_m(d))
13
+ * Standard constant k = 60
14
+ */
15
+ export declare function reciprocalRankFusion(denseResults: VectorDocument[], sparseResults: VectorDocument[], topK?: number, rrfK?: number): HybridScoredDocument[];
@@ -0,0 +1,51 @@
1
+ export * from './interfaces/engine-config.interface.js';
2
+ export * from './interfaces/query-context.interface.js';
3
+ export * from './interfaces/tool.interface.js';
4
+ export * from './interfaces/vector.interface.js';
5
+ export * from './interfaces/faq.interface.js';
6
+ export * from './interfaces/rules.interface.js';
7
+ export * from './interfaces/cache.interface.js';
8
+ export * from './interfaces/llm.interface.js';
9
+ export * from './core/security/security.types.js';
10
+ export { RAGEngine } from './core/engine.js';
11
+ export { SMLEngine, type SMLEngineConfig, type EmbeddingExtractor, CircuitBreakerOpenError } from './core/sml-engine.js';
12
+ export { ToolRegistry } from './core/tool-registry.js';
13
+ export { CacheManager } from './core/cache-manager.js';
14
+ export { PromptBuilder, type PromptContext } from './core/prompt-builder.js';
15
+ export { TokenTracker, type EngineMetricsSummary, type ResponseMetrics, type TokenTrackerOptions } from './core/metrics/token-tracker.js';
16
+ export { PrometheusExporter, type PrometheusMetricOptions } from './core/metrics/prometheus-exporter.js';
17
+ export { RAGEvaluator, type RetrievalEvalResult, type FaithfulnessEvalResult, type FullRAGEvaluationReport } from './core/metrics/rag-evaluator.js';
18
+ export { BM25Index, type BM25Document } from './core/vector/bm25.js';
19
+ export { reciprocalRankFusion, type HybridScoredDocument } from './core/vector/hybrid-search.js';
20
+ export { SecurityGuard } from './core/security/security-guard.js';
21
+ export { InputSanitizer } from './core/security/sanitizer.js';
22
+ export { InjectionDetector, type DetectionResult } from './core/security/injection-detector.js';
23
+ export { PIIGuard, type PIIPolicy, type PIISanitizationResult } from './core/security/pii-guard.js';
24
+ export { ConfirmationService, type ConfirmationTicketPayload } from './core/security/confirmation.js';
25
+ export * from './core/queue/job-queue.interface.js';
26
+ export { InMemoryJobQueue, type InMemoryQueueOptions } from './core/queue/in-memory-queue.js';
27
+ export { BullMQJobQueue, type BullMQQueueOptions } from './core/queue/bullmq-queue.js';
28
+ export { createJobQueue, type QueueConfig } from './core/queue/queue-factory.js';
29
+ export { DocumentIngestionService, type DocumentUploadPayload, type StreamIngestionOptions, type IngestionJobResult, type DocumentIngestionConfig } from './services/document-ingestion.service.js';
30
+ export { RedisCacheAdapter, type IRedisClientLike, type RedisCacheOptions } from './adapters/cache/redis-cache.adapter.js';
31
+ export { createRagMiddleware } from './api/middleware.js';
32
+ export { createApiRoutes, type ApiRouteOptions } from './api/routes.js';
33
+ export { createAuthToken, verifyAuthToken, createAuthMiddleware, requireRoles, type AuthTokenPayload, type AuthMiddlewareOptions } from './api/auth.js';
34
+ export { OpenAIAdapter } from './adapters/llm/openai.adapter.js';
35
+ export { GeminiAdapter } from './adapters/llm/gemini.adapter.js';
36
+ export { OpenRouterAdapter } from './adapters/llm/openrouter.adapter.js';
37
+ export { CustomLLMAdapter, type CustomLLMConfig } from './adapters/llm/custom.adapter.js';
38
+ export { OllamaAdapter, type OllamaConfig } from './adapters/llm/ollama.adapter.js';
39
+ export { FallbackLLMProvider, type FallbackProviderOptions } from './adapters/llm/fallback.adapter.js';
40
+ export { TieredLLMProvider, type TieredLLMConfig } from './adapters/llm/tiered.adapter.js';
41
+ export { MemoryVectorAdapter } from './adapters/vector/memory-vector.adapter.js';
42
+ export { StaticRulesAdapter } from './adapters/rules/static-rules.adapter.js';
43
+ export { UrlFaqAdapter } from './adapters/faq/url-faq.adapter.js';
44
+ export { LocalFaqAdapter, type LocalFaqAdapterOptions } from './adapters/faq/local-faq.adapter.js';
45
+ export { RedisConfirmationNonceStore, MemoryConfirmationNonceStore, type ConfirmationNonceStore } from './core/security/nonce-store.js';
46
+ export { PostgresVectorAdapter, type PostgresVectorOptions, type EmbeddingProvider } from './adapters/vector/postgres-vector.adapter.js';
47
+ export { PostgresIngestionStore, IngestionQuotaError, IngestionConflictError, type StoredUpload } from './core/ingestion/postgres-ingestion-store.js';
48
+ export { QueuedIngestionService, type QueuedIngestionOptions, type IngestionReference } from './core/ingestion/queued-ingestion.service.js';
49
+ export { IngestionWorker } from './core/ingestion/ingestion-worker.js';
50
+ export { createTenantRateLimiter } from './api/rate-limit.js';
51
+ export type { IIngestionBackend, IngestionSettings } from './interfaces/ingestion.interface.js';