@retrivora-ai/rag-engine 2.4.3 → 2.4.6

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 (142) hide show
  1. package/README.md +22 -0
  2. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-BGslIR5l.d.mts} +65 -4
  3. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-C3gY6kZ0.d.ts} +65 -4
  4. package/dist/handlers/index.js +668 -837
  5. package/dist/handlers/index.mjs +678 -837
  6. package/dist/index.css +5 -0
  7. package/dist/index.d.mts +4 -28
  8. package/dist/index.d.ts +4 -28
  9. package/dist/index.js +91 -43
  10. package/dist/index.min.css +1 -1
  11. package/dist/index.mjs +91 -43
  12. package/dist/server.d.mts +21 -7
  13. package/dist/server.d.ts +21 -7
  14. package/dist/server.js +731 -875
  15. package/dist/server.mjs +741 -875
  16. package/package.json +11 -4
  17. package/src/LicensedRetrivora.ts +0 -278
  18. package/src/app/api/chat/route.ts +0 -4
  19. package/src/app/api/health/route.ts +0 -5
  20. package/src/app/api/ingest/route.ts +0 -27
  21. package/src/app/api/suggestions/route.ts +0 -5
  22. package/src/app/api/upload/route.ts +0 -5
  23. package/src/app/constants.tsx +0 -270
  24. package/src/app/favicon.ico +0 -0
  25. package/src/app/globals.css +0 -449
  26. package/src/app/layout.tsx +0 -22
  27. package/src/app/page.tsx +0 -64
  28. package/src/app/types.ts +0 -30
  29. package/src/browser.tsx +0 -127
  30. package/src/components/ChatWidget.tsx +0 -393
  31. package/src/components/ChatWindow.tsx +0 -952
  32. package/src/components/CodeViewer.tsx +0 -56
  33. package/src/components/ConfigProvider.tsx +0 -141
  34. package/src/components/DocumentUpload.tsx +0 -354
  35. package/src/components/DynamicChart.tsx +0 -297
  36. package/src/components/HourglassLoader.tsx +0 -87
  37. package/src/components/MarkdownComponents.tsx +0 -186
  38. package/src/components/MessageBubble.tsx +0 -498
  39. package/src/components/ObservabilityPanel.tsx +0 -374
  40. package/src/components/ProductCard.tsx +0 -107
  41. package/src/components/ProductCarousel.tsx +0 -97
  42. package/src/components/SourceCard.tsx +0 -61
  43. package/src/components/ThemeProvider.tsx +0 -8
  44. package/src/components/ThemeToggle.tsx +0 -29
  45. package/src/components/ThinkingBlock.tsx +0 -75
  46. package/src/components/UIDispatcher.tsx +0 -342
  47. package/src/components/VisualizationRenderer.tsx +0 -621
  48. package/src/components/constants.tsx +0 -503
  49. package/src/config/ConfigBuilder.ts +0 -285
  50. package/src/config/EmbeddingStrategy.ts +0 -148
  51. package/src/config/LicenseConfigResolver.ts +0 -298
  52. package/src/config/RagConfig.ts +0 -328
  53. package/src/config/UniversalProfiles.ts +0 -82
  54. package/src/config/constants.ts +0 -64
  55. package/src/config/serverConfig.ts +0 -378
  56. package/src/config/uiConstants.ts +0 -47
  57. package/src/core/BatchProcessor.ts +0 -385
  58. package/src/core/CircuitBreaker.ts +0 -118
  59. package/src/core/ConfigFetcher.ts +0 -220
  60. package/src/core/ConfigResolver.ts +0 -165
  61. package/src/core/ConfigValidator.ts +0 -197
  62. package/src/core/DatabaseStorage.ts +0 -526
  63. package/src/core/FreeTierLimitsGuard.ts +0 -281
  64. package/src/core/LLMRouter.ts +0 -79
  65. package/src/core/LangChainAgent.ts +0 -132
  66. package/src/core/LicenseValidator.ts +0 -284
  67. package/src/core/LicenseVerifier.ts +0 -261
  68. package/src/core/MultiAgentCoordinator.ts +0 -239
  69. package/src/core/Pipeline.ts +0 -1279
  70. package/src/core/PluginManager.ts +0 -277
  71. package/src/core/ProjectSettings.ts +0 -247
  72. package/src/core/ProviderHealthCheck.ts +0 -133
  73. package/src/core/ProviderInterfaces.ts +0 -37
  74. package/src/core/ProviderRegistry.ts +0 -156
  75. package/src/core/QueryProcessor.ts +0 -399
  76. package/src/core/Retrivora.ts +0 -98
  77. package/src/core/VectorPlugin.ts +0 -193
  78. package/src/core/mcp.ts +0 -261
  79. package/src/exceptions/index.ts +0 -131
  80. package/src/handlers/index.ts +0 -1625
  81. package/src/hooks/useHydrated.ts +0 -13
  82. package/src/hooks/useProjectSettings.ts +0 -105
  83. package/src/hooks/useRagChat.ts +0 -436
  84. package/src/hooks/useStoredMessages.ts +0 -64
  85. package/src/index.css +0 -4269
  86. package/src/index.ts +0 -137
  87. package/src/lib/plugin.ts +0 -24
  88. package/src/llm/ILLMProvider.ts +0 -60
  89. package/src/llm/LLMFactory.ts +0 -141
  90. package/src/llm/providers/AnthropicProvider.ts +0 -215
  91. package/src/llm/providers/GeminiProvider.ts +0 -311
  92. package/src/llm/providers/GroqProvider.ts +0 -184
  93. package/src/llm/providers/OllamaProvider.ts +0 -232
  94. package/src/llm/providers/OpenAIProvider.ts +0 -188
  95. package/src/llm/providers/QwenProvider.ts +0 -199
  96. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  97. package/src/llm/utils.ts +0 -46
  98. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  99. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  100. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  101. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  102. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  103. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  104. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  105. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  106. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  107. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  108. package/src/providers/vectordb/RedisProvider.ts +0 -105
  109. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  110. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  111. package/src/rag/DocumentChunker.ts +0 -144
  112. package/src/rag/EntityExtractor.ts +0 -90
  113. package/src/rag/LlamaIndexIngestor.ts +0 -60
  114. package/src/rag/Reranker.ts +0 -106
  115. package/src/rendering/IntentClassifier.ts +0 -167
  116. package/src/rendering/RendererRegistry.ts +0 -164
  117. package/src/rendering/RuleEngine.ts +0 -67
  118. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  119. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  120. package/src/rendering/index.ts +0 -12
  121. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  122. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  123. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  124. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  125. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  126. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  127. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  128. package/src/rendering/types.ts +0 -96
  129. package/src/server.ts +0 -156
  130. package/src/tailwind.css +0 -194
  131. package/src/telemetry/TelemetryService.ts +0 -330
  132. package/src/types/chat.ts +0 -89
  133. package/src/types/index.ts +0 -278
  134. package/src/types/pdf-parse.d.ts +0 -13
  135. package/src/types/props.ts +0 -169
  136. package/src/utils/DocumentParser.ts +0 -111
  137. package/src/utils/ProductExtractor.ts +0 -350
  138. package/src/utils/SchemaMapper.ts +0 -176
  139. package/src/utils/UITransformer.ts +0 -1812
  140. package/src/utils/synonyms.ts +0 -80
  141. package/src/utils/templateUtils.ts +0 -78
  142. package/src/version.ts +0 -6
@@ -1,526 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as os from 'os';
4
- import { RagConfig } from '../config/RagConfig';
5
- import { LicenseVerifier } from './LicenseVerifier';
6
-
7
- export interface HistoryMessage {
8
- id: string;
9
- role: string;
10
- content: string;
11
- sources?: any;
12
- uiTransformation?: any;
13
- trace?: any;
14
- createdAt?: string;
15
- }
16
-
17
- export interface FeedbackItem {
18
- id: string;
19
- messageId: string;
20
- sessionId: string;
21
- rating: string;
22
- comment?: string;
23
- createdAt?: string;
24
- }
25
-
26
- export class DatabaseStorage {
27
- private config: RagConfig;
28
- private provider: string;
29
- // Dynamic PG Pool
30
- private pgPool: any = null;
31
- // Dynamic MongoDB Client
32
- private mongoClient: any = null;
33
- private mongoDbName = '';
34
-
35
- private historyTableName: string;
36
- private feedbackTableName: string;
37
-
38
- // Filesystem fallback configuration
39
- private isServerless = Boolean(process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.LAMBDA_TASK_ROOT);
40
- private fallbackDir = this.isServerless
41
- ? path.join(os.tmpdir(), '.retrivora')
42
- : path.join(process.cwd(), '.retrivora');
43
- private historyFile = path.join(this.fallbackDir, 'history.json');
44
- private feedbackFile = path.join(this.fallbackDir, 'feedback.json');
45
-
46
- constructor(config: RagConfig) {
47
- this.config = config;
48
- this.provider = config.vectorDb?.provider || 'fs';
49
-
50
- // Retrieve and sanitize table/collection names (alphanumeric + underscores only)
51
- const rawHistoryTable = config.rag?.history?.tableName || 'retrivora_history';
52
- const rawFeedbackTable = config.rag?.feedback?.tableName || 'retrivora_feedback';
53
- this.historyTableName = rawHistoryTable.replace(/[^a-zA-Z0-9_]/g, '_');
54
- this.feedbackTableName = rawFeedbackTable.replace(/[^a-zA-Z0-9_]/g, '_');
55
- }
56
-
57
- /**
58
- * Asserts the user is running a valid Premium/Enterprise license in production.
59
- * In non-production (development / test) environments this is a complete no-op —
60
- * all History and Feedback features are freely accessible for local development.
61
- */
62
- private async checkPremiumSubscription() {
63
- // ── Development / test: fully open, no checks ────────────────────────────
64
- if (process.env.NODE_ENV !== 'production') {
65
- return;
66
- }
67
-
68
- // ── Production: license key required ────────────────────────────────────
69
- if (!this.config.licenseKey) {
70
- throw new Error(
71
- '[Retrivora SDK] Chat History and Feedback features require a Premium or Enterprise license key in production.'
72
- );
73
- }
74
-
75
- try {
76
- const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
77
- const tier = (payload.tier || '').toLowerCase();
78
- if (
79
- tier !== 'premium' &&
80
- tier !== 'enterprise' &&
81
- tier !== 'growth' &&
82
- tier !== 'pro' &&
83
- tier !== 'developer_pro' &&
84
- tier !== 'free_trial' &&
85
- tier !== 'free_tier' &&
86
- tier !== 'free' &&
87
- tier !== 'hobby'
88
- ) {
89
- throw new Error(
90
- `[Retrivora SDK] Chat History and Feedback features are not available on the "${tier}" tier. ` +
91
- `Please upgrade to a Developer Pro or Enterprise plan.`
92
- );
93
- }
94
- } catch (err) {
95
- throw new Error(
96
- `[Retrivora SDK] Subscription check failed: ${err instanceof Error ? err.message : String(err)}`
97
- );
98
- }
99
- }
100
-
101
- private async checkHistoryEnabled() {
102
- await this.checkPremiumSubscription();
103
- if (this.config.rag?.history?.enabled === false) {
104
- throw new Error('[Retrivora SDK] Chat History is disabled in RagConfig.');
105
- }
106
- }
107
-
108
- private async checkFeedbackEnabled() {
109
- await this.checkPremiumSubscription();
110
- if (this.config.rag?.feedback?.enabled === false) {
111
- throw new Error('[Retrivora SDK] User Feedback is disabled in RagConfig.');
112
- }
113
- }
114
-
115
- private async getPGPool() {
116
- const globalKey = `__retrivora_pg_pool_${this.config.projectId}`;
117
- const _g = global as any;
118
- if (_g[globalKey]) {
119
- this.pgPool = _g[globalKey];
120
- return this.pgPool;
121
- }
122
- const opts = this.config.vectorDb.options as Record<string, any>;
123
- if (!opts.connectionString) {
124
- throw new Error('[DatabaseStorage] pg connectionString option is missing.');
125
- }
126
- const { Pool } = await import('pg');
127
- this.pgPool = new Pool({ connectionString: opts.connectionString });
128
- _g[globalKey] = this.pgPool;
129
-
130
- // Initialize tables using dynamic sanitized table names
131
- const client = await this.pgPool.connect();
132
- try {
133
- await client.query(`
134
- CREATE TABLE IF NOT EXISTS ${this.historyTableName} (
135
- id TEXT PRIMARY KEY,
136
- session_id TEXT NOT NULL,
137
- role TEXT NOT NULL,
138
- content TEXT NOT NULL,
139
- sources JSONB,
140
- ui_transformation JSONB,
141
- trace JSONB,
142
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
143
- )
144
- `);
145
- await client.query(`
146
- CREATE TABLE IF NOT EXISTS ${this.feedbackTableName} (
147
- id TEXT PRIMARY KEY,
148
- message_id TEXT NOT NULL UNIQUE,
149
- session_id TEXT NOT NULL,
150
- rating TEXT NOT NULL,
151
- comment TEXT,
152
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
153
- )
154
- `);
155
- } finally {
156
- client.release();
157
- }
158
- return this.pgPool;
159
- }
160
-
161
- private async getMongoClient() {
162
- const globalKey = `__retrivora_mongo_client_${this.config.projectId}`;
163
- const _g = global as any;
164
- if (_g[globalKey]) {
165
- this.mongoClient = _g[globalKey];
166
- this.mongoDbName = (this.config.vectorDb.options as any).database;
167
- return this.mongoClient;
168
- }
169
- const opts = this.config.vectorDb.options as Record<string, any>;
170
- if (!opts.uri || !opts.database) {
171
- throw new Error('[DatabaseStorage] mongo uri and database options are missing.');
172
- }
173
- const { MongoClient } = await import('mongodb');
174
- this.mongoClient = new MongoClient(opts.uri);
175
- await this.mongoClient.connect();
176
- _g[globalKey] = this.mongoClient;
177
- this.mongoDbName = opts.database;
178
- return this.mongoClient;
179
- }
180
-
181
- private getMongoDb() {
182
- return this.mongoClient.db(this.mongoDbName);
183
- }
184
-
185
- // Helper for FS fallback reads
186
- private readLocalFile(filePath: string): any[] {
187
- if (!fs.existsSync(filePath)) return [];
188
- try {
189
- const raw = fs.readFileSync(filePath, 'utf-8');
190
- return JSON.parse(raw) || [];
191
- } catch {
192
- return [];
193
- }
194
- }
195
-
196
- // Helper for FS fallback writes
197
- private writeLocalFile(filePath: string, data: any[]): void {
198
- try {
199
- const dir = path.dirname(filePath);
200
- if (!fs.existsSync(dir)) {
201
- fs.mkdirSync(dir, { recursive: true });
202
- }
203
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
204
- } catch (err: any) {
205
- if (err.code === 'EROFS') {
206
- try {
207
- const tmpDir = path.join(os.tmpdir(), '.retrivora');
208
- if (!fs.existsSync(tmpDir)) {
209
- fs.mkdirSync(tmpDir, { recursive: true });
210
- }
211
- const tmpFilePath = path.join(tmpDir, path.basename(filePath));
212
- fs.writeFileSync(tmpFilePath, JSON.stringify(data, null, 2), 'utf-8');
213
- } catch {
214
- /* ignore write failure in read-only environment */
215
- }
216
- } else {
217
- console.warn(`[DatabaseStorage] Failed to write local fallback file: ${err.message}`);
218
- }
219
- }
220
- }
221
-
222
- // ─── Message History Operations ──────────────────────────────────────────
223
-
224
- async saveMessage(
225
- sessionId: string,
226
- message: Omit<HistoryMessage, 'createdAt'>
227
- ): Promise<void> {
228
- await this.checkHistoryEnabled();
229
- const createdAt = new Date().toISOString();
230
- const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
231
-
232
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
233
- const pool = await this.getPGPool();
234
- await pool.query(
235
- `INSERT INTO ${this.historyTableName} (id, session_id, role, content, sources, ui_transformation, trace, created_at)
236
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
237
- ON CONFLICT (id) DO UPDATE
238
- SET content = EXCLUDED.content, sources = EXCLUDED.sources, ui_transformation = EXCLUDED.ui_transformation, trace = EXCLUDED.trace`,
239
- [
240
- msgId,
241
- sessionId,
242
- message.role,
243
- message.content,
244
- message.sources ? JSON.stringify(message.sources) : null,
245
- message.uiTransformation ? JSON.stringify(message.uiTransformation) : null,
246
- message.trace ? JSON.stringify(message.trace) : null,
247
- createdAt,
248
- ]
249
- );
250
- } else if (this.provider === 'mongodb') {
251
- await this.getMongoClient();
252
- const db = this.getMongoDb();
253
- const col = db.collection(this.historyTableName);
254
- await col.updateOne(
255
- { id: msgId },
256
- {
257
- $set: {
258
- id: msgId,
259
- session_id: sessionId,
260
- role: message.role,
261
- content: message.content,
262
- sources: message.sources || null,
263
- ui_transformation: message.uiTransformation || null,
264
- trace: message.trace || null,
265
- created_at: createdAt,
266
- },
267
- },
268
- { upsert: true }
269
- );
270
- } else {
271
- // Local FS fallback
272
- const history = this.readLocalFile(this.historyFile);
273
- const index = history.findIndex((h) => h.id === msgId);
274
- const item = {
275
- id: msgId,
276
- session_id: sessionId,
277
- role: message.role,
278
- content: message.content,
279
- sources: message.sources || null,
280
- ui_transformation: message.uiTransformation || null,
281
- trace: message.trace || null,
282
- created_at: createdAt,
283
- };
284
-
285
- if (index !== -1) {
286
- history[index] = item;
287
- } else {
288
- history.push(item);
289
- }
290
- this.writeLocalFile(this.historyFile, history);
291
- }
292
- }
293
-
294
- async getHistory(sessionId: string, projectIds?: string[]): Promise<HistoryMessage[]> {
295
- await this.checkHistoryEnabled();
296
- if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
297
- return [];
298
- }
299
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
300
- const pool = await this.getPGPool();
301
- const res = await pool.query(
302
- `SELECT id, role, content, sources, ui_transformation as "uiTransformation", trace, created_at as "createdAt"
303
- FROM ${this.historyTableName}
304
- WHERE session_id = $1
305
- ORDER BY created_at ASC`,
306
- [sessionId]
307
- );
308
- return res.rows;
309
- } else if (this.provider === 'mongodb') {
310
- await this.getMongoClient();
311
- const db = this.getMongoDb();
312
- const col = db.collection(this.historyTableName);
313
- const items = await col
314
- .find({ session_id: sessionId })
315
- .sort({ created_at: 1 })
316
- .toArray();
317
- return items.map((item: any) => ({
318
- id: item.id,
319
- role: item.role,
320
- content: item.content,
321
- sources: item.sources,
322
- uiTransformation: item.ui_transformation,
323
- trace: item.trace,
324
- createdAt: item.created_at,
325
- }));
326
- } else {
327
- const history = this.readLocalFile(this.historyFile);
328
- return history
329
- .filter((h) => h.session_id === sessionId)
330
- .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
331
- }
332
- }
333
-
334
- async clearHistory(sessionId: string, projectIds?: string[]): Promise<void> {
335
- await this.checkHistoryEnabled();
336
- if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
337
- return;
338
- }
339
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
340
- const pool = await this.getPGPool();
341
- await pool.query(`DELETE FROM ${this.historyTableName} WHERE session_id = $1`, [sessionId]);
342
- await pool.query(`DELETE FROM ${this.feedbackTableName} WHERE session_id = $1`, [sessionId]);
343
- } else if (this.provider === 'mongodb') {
344
- await this.getMongoClient();
345
- const db = this.getMongoDb();
346
- await db.collection(this.historyTableName).deleteMany({ session_id: sessionId });
347
- await db.collection(this.feedbackTableName).deleteMany({ session_id: sessionId });
348
- } else {
349
- const history = this.readLocalFile(this.historyFile);
350
- const filteredHistory = history.filter((h) => h.session_id !== sessionId);
351
- this.writeLocalFile(this.historyFile, filteredHistory);
352
-
353
- const feedback = this.readLocalFile(this.feedbackFile);
354
- const filteredFeedback = feedback.filter((f) => f.session_id !== sessionId);
355
- this.writeLocalFile(this.feedbackFile, filteredFeedback);
356
- }
357
- }
358
-
359
- /**
360
- * Return true when `sessionId` falls into the allowed `projectIds` scope.
361
- * When `projectIds` is empty / undefined we allow the call (legacy behavior
362
- * for non-multi-tenant consumers). Session ids typically begin with the
363
- * project id they were created for, so we prefix-match as well as contains-match
364
- * to catch sharded / suffix-style ids used by some integrations.
365
- */
366
- private sessionInScope(sessionId: string, projectIds?: string[]): boolean {
367
- if (!projectIds || projectIds.length === 0) return true;
368
- return projectIds.some(
369
- (pid) => pid && (sessionId === pid || sessionId.startsWith(pid) || sessionId.includes(pid))
370
- );
371
- }
372
-
373
- async listSessions(projectIds?: string[]): Promise<string[]> {
374
- await this.checkHistoryEnabled();
375
- let raw: string[] = [];
376
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
377
- const pool = await this.getPGPool();
378
- const res = await pool.query(`SELECT DISTINCT session_id FROM ${this.historyTableName}`);
379
- raw = res.rows.map((r: any) => r.session_id);
380
- } else if (this.provider === 'mongodb') {
381
- await this.getMongoClient();
382
- const db = this.getMongoDb();
383
- raw = await db.collection(this.historyTableName).distinct('session_id');
384
- } else {
385
- const history = this.readLocalFile(this.historyFile);
386
- raw = Array.from(new Set<string>(history.map((h) => h.session_id)));
387
- }
388
- if (!projectIds || projectIds.length === 0) return raw;
389
- return raw.filter((sid) => this.sessionInScope(sid, projectIds));
390
- }
391
-
392
- // ─── Feedback Operations ──────────────────────────────────────────────────
393
-
394
- async saveFeedback(feedback: Omit<FeedbackItem, 'id' | 'createdAt'>): Promise<void> {
395
- await this.checkFeedbackEnabled();
396
- const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
397
- const createdAt = new Date().toISOString();
398
-
399
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
400
- const pool = await this.getPGPool();
401
- await pool.query(
402
- `INSERT INTO ${this.feedbackTableName} (id, message_id, session_id, rating, comment, created_at)
403
- VALUES ($1, $2, $3, $4, $5, $6)
404
- ON CONFLICT (message_id) DO UPDATE
405
- SET rating = EXCLUDED.rating, comment = EXCLUDED.comment`,
406
- [id, feedback.messageId, feedback.sessionId, feedback.rating, feedback.comment || null, createdAt]
407
- );
408
- } else if (this.provider === 'mongodb') {
409
- await this.getMongoClient();
410
- const db = this.getMongoDb();
411
- const col = db.collection(this.feedbackTableName);
412
- await col.updateOne(
413
- { message_id: feedback.messageId },
414
- {
415
- $set: {
416
- id,
417
- message_id: feedback.messageId,
418
- session_id: feedback.sessionId,
419
- rating: feedback.rating,
420
- comment: feedback.comment || null,
421
- created_at: createdAt,
422
- },
423
- },
424
- { upsert: true }
425
- );
426
- } else {
427
- const list = this.readLocalFile(this.feedbackFile);
428
- const index = list.findIndex((f) => f.message_id === feedback.messageId);
429
- const item = {
430
- id,
431
- message_id: feedback.messageId,
432
- session_id: feedback.sessionId,
433
- rating: feedback.rating,
434
- comment: feedback.comment || null,
435
- created_at: createdAt,
436
- };
437
-
438
- if (index !== -1) {
439
- list[index] = item;
440
- } else {
441
- list.push(item);
442
- }
443
- this.writeLocalFile(this.feedbackFile, list);
444
- }
445
- }
446
-
447
- async getFeedback(messageId: string, projectIds?: string[]): Promise<FeedbackItem | null> {
448
- await this.checkFeedbackEnabled();
449
- let item: FeedbackItem | null = null;
450
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
451
- const pool = await this.getPGPool();
452
- const res = await pool.query(
453
- `SELECT id, message_id as "messageId", session_id as "sessionId", rating, comment, created_at as "createdAt"
454
- FROM ${this.feedbackTableName}
455
- WHERE message_id = $1`,
456
- [messageId]
457
- );
458
- item = res.rows[0] || null;
459
- } else if (this.provider === 'mongodb') {
460
- await this.getMongoClient();
461
- const db = this.getMongoDb();
462
- const col = db.collection(this.feedbackTableName);
463
- const raw = await col.findOne({ message_id: messageId });
464
- if (raw) {
465
- item = {
466
- id: raw.id,
467
- messageId: raw.message_id,
468
- sessionId: raw.session_id,
469
- rating: raw.rating,
470
- comment: raw.comment,
471
- createdAt: raw.created_at,
472
- };
473
- }
474
- } else {
475
- const list = this.readLocalFile(this.feedbackFile);
476
- item = list.find((f) => f.message_id === messageId) || null;
477
- }
478
- if (item && projectIds && projectIds.length > 0) {
479
- return this.sessionInScope(item.sessionId, projectIds) ? item : null;
480
- }
481
- return item;
482
- }
483
-
484
- async listFeedback(projectIds?: string[]): Promise<FeedbackItem[]> {
485
- await this.checkFeedbackEnabled();
486
- let raw: FeedbackItem[] = [];
487
- if (this.provider === 'postgresql' || this.provider === 'pgvector') {
488
- const pool = await this.getPGPool();
489
- const res = await pool.query(
490
- `SELECT id, message_id as "messageId", session_id as "sessionId", rating, comment, created_at as "createdAt"
491
- FROM ${this.feedbackTableName}
492
- ORDER BY created_at DESC`
493
- );
494
- raw = res.rows;
495
- } else if (this.provider === 'mongodb') {
496
- await this.getMongoClient();
497
- const db = this.getMongoDb();
498
- const col = db.collection(this.feedbackTableName);
499
- const items = await col.find({}).sort({ created_at: -1 }).toArray();
500
- raw = items.map((item: any) => ({
501
- id: item.id,
502
- messageId: item.message_id,
503
- sessionId: item.session_id,
504
- rating: item.rating,
505
- comment: item.comment,
506
- createdAt: item.created_at,
507
- }));
508
- } else {
509
- const list = this.readLocalFile(this.feedbackFile);
510
- raw = [...list].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
511
- }
512
- if (!projectIds || projectIds.length === 0) return raw;
513
- return raw.filter((f) => this.sessionInScope(f.sessionId, projectIds));
514
- }
515
-
516
- async disconnect() {
517
- if (this.pgPool) {
518
- await this.pgPool.end();
519
- this.pgPool = null;
520
- }
521
- if (this.mongoClient) {
522
- await this.mongoClient.close();
523
- this.mongoClient = null;
524
- }
525
- }
526
- }