@vezlo/assistant-server 2.10.0 → 2.11.1
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.
- package/README.md +2 -1
- package/database-schema.sql +48 -0
- package/dist/src/bootstrap/initializeServices.d.ts +5 -0
- package/dist/src/bootstrap/initializeServices.d.ts.map +1 -1
- package/dist/src/bootstrap/initializeServices.js +18 -3
- package/dist/src/bootstrap/initializeServices.js.map +1 -1
- package/dist/src/controllers/ChatController.d.ts +3 -0
- package/dist/src/controllers/ChatController.d.ts.map +1 -1
- package/dist/src/controllers/ChatController.js +75 -15
- package/dist/src/controllers/ChatController.js.map +1 -1
- package/dist/src/controllers/DatabaseToolConfigController.d.ts +81 -0
- package/dist/src/controllers/DatabaseToolConfigController.d.ts.map +1 -0
- package/dist/src/controllers/DatabaseToolConfigController.js +573 -0
- package/dist/src/controllers/DatabaseToolConfigController.js.map +1 -0
- package/dist/src/controllers/KnowledgeController.js +4 -4
- package/dist/src/controllers/KnowledgeController.js.map +1 -1
- package/dist/src/migrations/011_create_database_tool_configs.d.ts +4 -0
- package/dist/src/migrations/011_create_database_tool_configs.d.ts.map +1 -0
- package/dist/src/migrations/011_create_database_tool_configs.js +51 -0
- package/dist/src/migrations/011_create_database_tool_configs.js.map +1 -0
- package/dist/src/server.js +399 -0
- package/dist/src/server.js.map +1 -1
- package/dist/src/services/AIService.d.ts +3 -0
- package/dist/src/services/AIService.d.ts.map +1 -1
- package/dist/src/services/AIService.js +5 -0
- package/dist/src/services/AIService.js.map +1 -1
- package/dist/src/services/DatabaseToolConfigService.d.ts +135 -0
- package/dist/src/services/DatabaseToolConfigService.d.ts.map +1 -0
- package/dist/src/services/DatabaseToolConfigService.js +451 -0
- package/dist/src/services/DatabaseToolConfigService.js.map +1 -0
- package/dist/src/services/DatabaseToolService.d.ts +75 -0
- package/dist/src/services/DatabaseToolService.d.ts.map +1 -0
- package/dist/src/services/DatabaseToolService.js +299 -0
- package/dist/src/services/DatabaseToolService.js.map +1 -0
- package/dist/src/services/IntentService.d.ts +10 -1
- package/dist/src/services/IntentService.d.ts.map +1 -1
- package/dist/src/services/IntentService.js +34 -5
- package/dist/src/services/IntentService.js.map +1 -1
- package/dist/src/services/ResponseGenerationService.d.ts +5 -3
- package/dist/src/services/ResponseGenerationService.d.ts.map +1 -1
- package/dist/src/services/ResponseGenerationService.js +29 -4
- package/dist/src/services/ResponseGenerationService.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* DatabaseToolConfigService
|
|
4
|
+
*
|
|
5
|
+
* Manages external database tool configurations for companies
|
|
6
|
+
* Handles CRUD operations, encryption, and schema introspection
|
|
7
|
+
*/
|
|
8
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
9
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DatabaseToolConfigService = void 0;
|
|
13
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
14
|
+
const logger_1 = __importDefault(require("../config/logger"));
|
|
15
|
+
class DatabaseToolConfigService {
|
|
16
|
+
constructor(supabase) {
|
|
17
|
+
this.algorithm = 'aes-256-cbc';
|
|
18
|
+
this.supabase = supabase;
|
|
19
|
+
// Use JWT_SECRET for encryption
|
|
20
|
+
const key = process.env.JWT_SECRET || 'default-encryption-key-change-this';
|
|
21
|
+
// Ensure key is 32 bytes for aes-256-cbc
|
|
22
|
+
this.encryptionKey = crypto_1.default.createHash('sha256').update(key).digest('hex').substring(0, 32);
|
|
23
|
+
if (!process.env.JWT_SECRET) {
|
|
24
|
+
logger_1.default.warn('⚠️ No JWT_SECRET found - using default (insecure for production)');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Encrypt sensitive data
|
|
29
|
+
*/
|
|
30
|
+
encrypt(text) {
|
|
31
|
+
const iv = crypto_1.default.randomBytes(16);
|
|
32
|
+
const cipher = crypto_1.default.createCipheriv(this.algorithm, this.encryptionKey, iv);
|
|
33
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
34
|
+
encrypted += cipher.final('hex');
|
|
35
|
+
return iv.toString('hex') + ':' + encrypted;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Decrypt sensitive data
|
|
39
|
+
*/
|
|
40
|
+
decrypt(text) {
|
|
41
|
+
const parts = text.split(':');
|
|
42
|
+
const iv = Buffer.from(parts[0], 'hex');
|
|
43
|
+
const encryptedText = parts[1];
|
|
44
|
+
const decipher = crypto_1.default.createDecipheriv(this.algorithm, this.encryptionKey, iv);
|
|
45
|
+
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
|
|
46
|
+
decrypted += decipher.final('utf8');
|
|
47
|
+
return decrypted;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Create a new database tool configuration
|
|
51
|
+
*/
|
|
52
|
+
async createConfig(companyId, dbUrl, dbKey) {
|
|
53
|
+
const encryptedUrl = this.encrypt(dbUrl);
|
|
54
|
+
const encryptedKey = this.encrypt(dbKey);
|
|
55
|
+
const { data, error } = await this.supabase
|
|
56
|
+
.from('vezlo_database_tool_configs')
|
|
57
|
+
.insert({
|
|
58
|
+
company_id: companyId,
|
|
59
|
+
db_url_encrypted: encryptedUrl,
|
|
60
|
+
db_key_encrypted: encryptedKey,
|
|
61
|
+
enabled: true
|
|
62
|
+
})
|
|
63
|
+
.select()
|
|
64
|
+
.single();
|
|
65
|
+
if (error) {
|
|
66
|
+
logger_1.default.error('Failed to create database tool config:', error);
|
|
67
|
+
throw new Error(`Failed to create config: ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
logger_1.default.info(`✅ Created database tool config for company ${companyId}`);
|
|
70
|
+
return data;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Get configuration by company ID
|
|
74
|
+
*/
|
|
75
|
+
async getConfigByCompany(companyId) {
|
|
76
|
+
const { data, error } = await this.supabase
|
|
77
|
+
.from('vezlo_database_tool_configs')
|
|
78
|
+
.select('*')
|
|
79
|
+
.eq('company_id', companyId)
|
|
80
|
+
.eq('enabled', true)
|
|
81
|
+
.single();
|
|
82
|
+
if (error && error.code !== 'PGRST116') { // PGRST116 = not found
|
|
83
|
+
logger_1.default.error('Failed to get database tool config:', error);
|
|
84
|
+
throw new Error(`Failed to get config: ${error.message}`);
|
|
85
|
+
}
|
|
86
|
+
return data || null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Get decrypted credentials for a company
|
|
90
|
+
*/
|
|
91
|
+
async getDecryptedCredentials(companyId) {
|
|
92
|
+
const config = await this.getConfigByCompany(companyId);
|
|
93
|
+
if (!config) {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const url = this.decrypt(config.db_url_encrypted);
|
|
98
|
+
const key = this.decrypt(config.db_key_encrypted);
|
|
99
|
+
return { url, key };
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
logger_1.default.error('Failed to decrypt credentials:', error);
|
|
103
|
+
throw new Error('Failed to decrypt database credentials');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Get decrypted credentials by config UUID
|
|
108
|
+
*/
|
|
109
|
+
async getDecryptedCredentialsByConfigId(configUuid) {
|
|
110
|
+
const { data: config, error } = await this.supabase
|
|
111
|
+
.from('vezlo_database_tool_configs')
|
|
112
|
+
.select('*')
|
|
113
|
+
.eq('uuid', configUuid)
|
|
114
|
+
.single();
|
|
115
|
+
if (error || !config) {
|
|
116
|
+
logger_1.default.error('Failed to get config by UUID:', error);
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
const url = this.decrypt(config.db_url_encrypted);
|
|
121
|
+
const key = this.decrypt(config.db_key_encrypted);
|
|
122
|
+
return { url, key };
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
logger_1.default.error('Failed to decrypt credentials:', error);
|
|
126
|
+
throw new Error('Failed to decrypt database credentials');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Update configuration by UUID
|
|
131
|
+
*/
|
|
132
|
+
async updateConfig(configUuid, dbUrl, dbKey, enabled) {
|
|
133
|
+
const updates = {};
|
|
134
|
+
if (dbUrl) {
|
|
135
|
+
updates.db_url_encrypted = this.encrypt(dbUrl);
|
|
136
|
+
}
|
|
137
|
+
if (dbKey) {
|
|
138
|
+
updates.db_key_encrypted = this.encrypt(dbKey);
|
|
139
|
+
}
|
|
140
|
+
if (enabled !== undefined) {
|
|
141
|
+
updates.enabled = enabled;
|
|
142
|
+
}
|
|
143
|
+
updates.updated_at = new Date().toISOString();
|
|
144
|
+
const { data, error } = await this.supabase
|
|
145
|
+
.from('vezlo_database_tool_configs')
|
|
146
|
+
.update(updates)
|
|
147
|
+
.eq('uuid', configUuid)
|
|
148
|
+
.select()
|
|
149
|
+
.single();
|
|
150
|
+
if (error) {
|
|
151
|
+
logger_1.default.error('Failed to update database tool config:', error);
|
|
152
|
+
throw new Error(`Failed to update config: ${error.message}`);
|
|
153
|
+
}
|
|
154
|
+
logger_1.default.info(`✅ Updated database tool config ${configUuid}`);
|
|
155
|
+
return data;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Delete configuration by UUID
|
|
159
|
+
*/
|
|
160
|
+
async deleteConfig(configUuid) {
|
|
161
|
+
const { error } = await this.supabase
|
|
162
|
+
.from('vezlo_database_tool_configs')
|
|
163
|
+
.delete()
|
|
164
|
+
.eq('uuid', configUuid);
|
|
165
|
+
if (error) {
|
|
166
|
+
logger_1.default.error('Failed to delete database tool config:', error);
|
|
167
|
+
throw new Error(`Failed to delete config: ${error.message}`);
|
|
168
|
+
}
|
|
169
|
+
logger_1.default.info(`✅ Deleted database tool config ${configUuid}`);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Validate database connection and credentials (READ-ONLY)
|
|
173
|
+
*/
|
|
174
|
+
async validateConnection(dbUrl, dbKey) {
|
|
175
|
+
try {
|
|
176
|
+
// Use Supabase REST API to get OpenAPI schema (read-only operation)
|
|
177
|
+
// This doesn't require any functions to be created in the database
|
|
178
|
+
const response = await fetch(`${dbUrl}/rest/v1/`, {
|
|
179
|
+
method: 'GET',
|
|
180
|
+
headers: {
|
|
181
|
+
'apikey': dbKey,
|
|
182
|
+
'Authorization': `Bearer ${dbKey}`
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
return { valid: false, error: `Connection failed: ${response.statusText}` };
|
|
187
|
+
}
|
|
188
|
+
const openApiSpec = await response.json();
|
|
189
|
+
// Extract table names from OpenAPI spec paths
|
|
190
|
+
const tables = [];
|
|
191
|
+
if (openApiSpec.paths) {
|
|
192
|
+
logger_1.default.info(`📋 Found ${Object.keys(openApiSpec.paths).length} paths in OpenAPI spec`);
|
|
193
|
+
for (const path of Object.keys(openApiSpec.paths)) {
|
|
194
|
+
// Paths are like "/table_name" - extract table name
|
|
195
|
+
const match = path.match(/^\/([^\/\?]+)/);
|
|
196
|
+
if (match && match[1] && !match[1].startsWith('rpc')) {
|
|
197
|
+
tables.push(match[1]);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
logger_1.default.warn('⚠️ No paths found in OpenAPI spec - check if tables are exposed to REST API');
|
|
203
|
+
}
|
|
204
|
+
const uniqueTables = [...new Set(tables)];
|
|
205
|
+
logger_1.default.info(`✅ Found ${uniqueTables.length} tables available via REST API`);
|
|
206
|
+
return { valid: true, tables: uniqueTables };
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
return { valid: false, error: error.message || 'Connection failed' };
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Introspect database schema - get all tables (READ-ONLY, no database writes required)
|
|
214
|
+
*/
|
|
215
|
+
async introspectTables(dbUrl, dbKey) {
|
|
216
|
+
try {
|
|
217
|
+
// Use Supabase REST API OpenAPI endpoint (read-only, no setup required)
|
|
218
|
+
const response = await fetch(`${dbUrl}/rest/v1/`, {
|
|
219
|
+
method: 'GET',
|
|
220
|
+
headers: {
|
|
221
|
+
'apikey': dbKey,
|
|
222
|
+
'Authorization': `Bearer ${dbKey}`,
|
|
223
|
+
'Accept': 'application/json'
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
if (!response.ok) {
|
|
227
|
+
throw new Error(`Failed to fetch database schema: ${response.statusText}`);
|
|
228
|
+
}
|
|
229
|
+
const openApiSpec = await response.json();
|
|
230
|
+
// Extract table names from OpenAPI spec
|
|
231
|
+
const tables = [];
|
|
232
|
+
if (openApiSpec.paths) {
|
|
233
|
+
logger_1.default.info(`📋 Found ${Object.keys(openApiSpec.paths).length} paths in OpenAPI spec`);
|
|
234
|
+
for (const path of Object.keys(openApiSpec.paths)) {
|
|
235
|
+
// Paths are like "/table_name" - extract table name
|
|
236
|
+
const match = path.match(/^\/([^\/\?]+)/);
|
|
237
|
+
if (match && match[1] && !match[1].startsWith('rpc')) {
|
|
238
|
+
tables.push(match[1]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
logger_1.default.warn('⚠️ No paths found in OpenAPI spec - tables may not be exposed to REST API');
|
|
244
|
+
}
|
|
245
|
+
const uniqueTables = [...new Set(tables)].sort();
|
|
246
|
+
logger_1.default.info(`✅ Successfully introspected ${uniqueTables.length} tables available via REST API`);
|
|
247
|
+
if (uniqueTables.length === 0) {
|
|
248
|
+
logger_1.default.warn('⚠️ No tables found. Possible reasons:');
|
|
249
|
+
logger_1.default.warn(' 1. Database has no tables');
|
|
250
|
+
logger_1.default.warn(' 2. Tables are not exposed to Supabase REST API');
|
|
251
|
+
logger_1.default.warn(' 3. Check Supabase Dashboard > API Settings > API Docs to see available tables');
|
|
252
|
+
}
|
|
253
|
+
return uniqueTables;
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
logger_1.default.error('Failed to introspect tables:', error);
|
|
257
|
+
throw new Error(`Failed to introspect tables: ${error.message}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Introspect table schema - get columns and types (READ-ONLY, no database writes required)
|
|
262
|
+
*/
|
|
263
|
+
async introspectTableColumns(dbUrl, dbKey, tableName) {
|
|
264
|
+
try {
|
|
265
|
+
// Use Supabase REST API OpenAPI endpoint (read-only, no setup required)
|
|
266
|
+
const response = await fetch(`${dbUrl}/rest/v1/`, {
|
|
267
|
+
method: 'GET',
|
|
268
|
+
headers: {
|
|
269
|
+
'apikey': dbKey,
|
|
270
|
+
'Authorization': `Bearer ${dbKey}`,
|
|
271
|
+
'Accept': 'application/json'
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
if (!response.ok) {
|
|
275
|
+
throw new Error(`Failed to fetch database schema: ${response.statusText}`);
|
|
276
|
+
}
|
|
277
|
+
const openApiSpec = await response.json();
|
|
278
|
+
// Find the schema definition for this table
|
|
279
|
+
const tableDefinition = openApiSpec.definitions?.[tableName];
|
|
280
|
+
if (!tableDefinition || !tableDefinition.properties) {
|
|
281
|
+
throw new Error(`Table "${tableName}" not found or has no accessible columns`);
|
|
282
|
+
}
|
|
283
|
+
// Extract column information
|
|
284
|
+
const columns = [];
|
|
285
|
+
for (const [columnName, columnSchema] of Object.entries(tableDefinition.properties)) {
|
|
286
|
+
const schema = columnSchema;
|
|
287
|
+
let dataType = schema.type || 'unknown';
|
|
288
|
+
// Map OpenAPI types to PostgreSQL types
|
|
289
|
+
if (schema.format === 'uuid')
|
|
290
|
+
dataType = 'uuid';
|
|
291
|
+
else if (schema.format === 'date-time')
|
|
292
|
+
dataType = 'timestamp';
|
|
293
|
+
else if (schema.format === 'date')
|
|
294
|
+
dataType = 'date';
|
|
295
|
+
else if (schema.type === 'integer')
|
|
296
|
+
dataType = 'integer';
|
|
297
|
+
else if (schema.type === 'number')
|
|
298
|
+
dataType = 'numeric';
|
|
299
|
+
else if (schema.type === 'boolean')
|
|
300
|
+
dataType = 'boolean';
|
|
301
|
+
else if (schema.type === 'string')
|
|
302
|
+
dataType = 'text';
|
|
303
|
+
else if (schema.type === 'array')
|
|
304
|
+
dataType = 'array';
|
|
305
|
+
const isNullable = tableDefinition.required?.includes(columnName) ? 'NO' : 'YES';
|
|
306
|
+
columns.push({
|
|
307
|
+
column_name: columnName,
|
|
308
|
+
data_type: dataType,
|
|
309
|
+
is_nullable: isNullable
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
logger_1.default.info(`✅ Successfully introspected ${columns.length} columns for table "${tableName}"`);
|
|
313
|
+
return {
|
|
314
|
+
table_name: tableName,
|
|
315
|
+
columns: columns.sort((a, b) => a.column_name.localeCompare(b.column_name))
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
logger_1.default.error('Failed to introspect table columns:', error);
|
|
320
|
+
throw new Error(`Failed to introspect columns for table "${tableName}": ${error.message}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Create a tool for a specific table (configUuid from API, get internal id)
|
|
325
|
+
*/
|
|
326
|
+
async createTool(configUuid, tableName, toolName, toolDescription, columns, idColumn, idColumnType, requiresUserContext, userFilterColumn, userFilterType, userContextKey) {
|
|
327
|
+
// Get internal config ID from UUID
|
|
328
|
+
const { data: config } = await this.supabase
|
|
329
|
+
.from('vezlo_database_tool_configs')
|
|
330
|
+
.select('id')
|
|
331
|
+
.eq('uuid', configUuid)
|
|
332
|
+
.single();
|
|
333
|
+
if (!config) {
|
|
334
|
+
throw new Error('Config not found');
|
|
335
|
+
}
|
|
336
|
+
// Ensure columns is an array before stringifying
|
|
337
|
+
const columnsArray = Array.isArray(columns) ? columns :
|
|
338
|
+
(typeof columns === 'string' ? JSON.parse(columns) : columns);
|
|
339
|
+
const { data, error } = await this.supabase
|
|
340
|
+
.from('vezlo_database_tools')
|
|
341
|
+
.insert({
|
|
342
|
+
config_id: config.id,
|
|
343
|
+
table_name: tableName,
|
|
344
|
+
tool_name: toolName,
|
|
345
|
+
tool_description: toolDescription,
|
|
346
|
+
columns: JSON.stringify(columnsArray),
|
|
347
|
+
id_column: idColumn,
|
|
348
|
+
id_column_type: idColumnType,
|
|
349
|
+
enabled: true,
|
|
350
|
+
requires_user_context: requiresUserContext || false,
|
|
351
|
+
user_filter_column: userFilterColumn || null,
|
|
352
|
+
user_filter_type: userFilterType || null,
|
|
353
|
+
user_context_key: userContextKey || null
|
|
354
|
+
})
|
|
355
|
+
.select()
|
|
356
|
+
.single();
|
|
357
|
+
if (error) {
|
|
358
|
+
logger_1.default.error('Failed to create database tool:', error);
|
|
359
|
+
throw new Error(`Failed to create tool: ${error.message}`);
|
|
360
|
+
}
|
|
361
|
+
logger_1.default.info(`✅ Created tool ${toolName} for table ${tableName}`);
|
|
362
|
+
// Parse columns before returning
|
|
363
|
+
return {
|
|
364
|
+
...data,
|
|
365
|
+
columns: typeof data.columns === 'string' ? JSON.parse(data.columns) : data.columns
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get all tools for a configuration (by config internal ID)
|
|
370
|
+
*/
|
|
371
|
+
async getToolsByConfigId(configId) {
|
|
372
|
+
const { data, error } = await this.supabase
|
|
373
|
+
.from('vezlo_database_tools')
|
|
374
|
+
.select('*')
|
|
375
|
+
.eq('config_id', configId)
|
|
376
|
+
.order('table_name');
|
|
377
|
+
if (error) {
|
|
378
|
+
logger_1.default.error('Failed to get database tools:', error);
|
|
379
|
+
throw new Error(`Failed to get tools: ${error.message}`);
|
|
380
|
+
}
|
|
381
|
+
// Parse columns JSONB field
|
|
382
|
+
return (data || []).map(tool => ({
|
|
383
|
+
...tool,
|
|
384
|
+
columns: typeof tool.columns === 'string' ? JSON.parse(tool.columns) : tool.columns
|
|
385
|
+
}));
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Get all enabled tools for a company
|
|
389
|
+
*/
|
|
390
|
+
async getEnabledToolsByCompany(companyId) {
|
|
391
|
+
const { data, error } = await this.supabase
|
|
392
|
+
.from('vezlo_database_tools')
|
|
393
|
+
.select('*, vezlo_database_tool_configs!inner(company_id, enabled)')
|
|
394
|
+
.eq('vezlo_database_tool_configs.company_id', companyId)
|
|
395
|
+
.eq('vezlo_database_tool_configs.enabled', true)
|
|
396
|
+
.eq('enabled', true);
|
|
397
|
+
if (error) {
|
|
398
|
+
logger_1.default.error('Failed to get enabled database tools:', error);
|
|
399
|
+
throw new Error(`Failed to get enabled tools: ${error.message}`);
|
|
400
|
+
}
|
|
401
|
+
// Parse columns JSONB field
|
|
402
|
+
return (data || []).map(tool => ({
|
|
403
|
+
...tool,
|
|
404
|
+
columns: typeof tool.columns === 'string' ? JSON.parse(tool.columns) : tool.columns
|
|
405
|
+
}));
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Update a tool by UUID
|
|
409
|
+
*/
|
|
410
|
+
async updateTool(toolUuid, updates) {
|
|
411
|
+
const updateData = { ...updates, updated_at: new Date().toISOString() };
|
|
412
|
+
if (updates.columns) {
|
|
413
|
+
// Ensure columns is an array before stringifying
|
|
414
|
+
const columnsArray = Array.isArray(updates.columns) ? updates.columns :
|
|
415
|
+
(typeof updates.columns === 'string' ? JSON.parse(updates.columns) : updates.columns);
|
|
416
|
+
updateData.columns = JSON.stringify(columnsArray);
|
|
417
|
+
}
|
|
418
|
+
const { data, error } = await this.supabase
|
|
419
|
+
.from('vezlo_database_tools')
|
|
420
|
+
.update(updateData)
|
|
421
|
+
.eq('uuid', toolUuid)
|
|
422
|
+
.select()
|
|
423
|
+
.single();
|
|
424
|
+
if (error) {
|
|
425
|
+
logger_1.default.error('Failed to update database tool:', error);
|
|
426
|
+
throw new Error(`Failed to update tool: ${error.message}`);
|
|
427
|
+
}
|
|
428
|
+
logger_1.default.info(`✅ Updated tool ${toolUuid}`);
|
|
429
|
+
// Parse columns before returning
|
|
430
|
+
return {
|
|
431
|
+
...data,
|
|
432
|
+
columns: typeof data.columns === 'string' ? JSON.parse(data.columns) : data.columns
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Delete a tool by UUID
|
|
437
|
+
*/
|
|
438
|
+
async deleteTool(toolUuid) {
|
|
439
|
+
const { error } = await this.supabase
|
|
440
|
+
.from('vezlo_database_tools')
|
|
441
|
+
.delete()
|
|
442
|
+
.eq('uuid', toolUuid);
|
|
443
|
+
if (error) {
|
|
444
|
+
logger_1.default.error('Failed to delete database tool:', error);
|
|
445
|
+
throw new Error(`Failed to delete tool: ${error.message}`);
|
|
446
|
+
}
|
|
447
|
+
logger_1.default.info(`✅ Deleted tool ${toolUuid}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
exports.DatabaseToolConfigService = DatabaseToolConfigService;
|
|
451
|
+
//# sourceMappingURL=DatabaseToolConfigService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DatabaseToolConfigService.js","sourceRoot":"","sources":["../../../src/services/DatabaseToolConfigService.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;AAGH,oDAA4B;AAC5B,8DAAsC;AAyCtC,MAAa,yBAAyB;IAKpC,YAAY,QAAwB;QAF5B,cAAS,GAAG,aAAa,CAAC;QAGhC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,gCAAgC;QAChC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,oCAAoC,CAAC;QAE3E,yCAAyC;QACzC,IAAI,CAAC,aAAa,GAAG,gBAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,C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CAAC,CAAC,IAAI,CAAC,OAAO;SACpF,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB;QAC/B,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,QAAQ;aAClC,IAAI,CAAC,sBAAsB,CAAC;aAC5B,MAAM,EAAE;aACR,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAExB,IAAI,KAAK,EAAE,CAAC;YACV,gBAAM,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACvD,MAAM,IAAI,KAAK,CAAC,0BAA0B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,gBAAM,CAAC,IAAI,CAAC,kBAAkB,QAAQ,EAAE,CAAC,CAAC;IAC5C,CAAC;CACF;AAzgBD,8DAygBC"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DatabaseToolService - Dynamic External Database Integration
|
|
3
|
+
*
|
|
4
|
+
* This service enables tool-based queries to external databases (e.g., Supabase)
|
|
5
|
+
* Dynamically loads tool configurations from database and executes queries
|
|
6
|
+
*
|
|
7
|
+
* NOTE: This is a separate experimental feature for direct database integration
|
|
8
|
+
* Can be easily removed without affecting core functionality
|
|
9
|
+
*/
|
|
10
|
+
import { SupabaseClient } from '@supabase/supabase-js';
|
|
11
|
+
import { DatabaseToolConfigService } from './DatabaseToolConfigService';
|
|
12
|
+
export interface DatabaseConfig {
|
|
13
|
+
url: string;
|
|
14
|
+
key: string;
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface UserQueryContext {
|
|
18
|
+
userId?: string;
|
|
19
|
+
companyId?: number;
|
|
20
|
+
user_uuid?: string;
|
|
21
|
+
company_uuid?: string;
|
|
22
|
+
[key: string]: any;
|
|
23
|
+
}
|
|
24
|
+
export interface ToolDefinition {
|
|
25
|
+
type: 'function';
|
|
26
|
+
function: {
|
|
27
|
+
name: string;
|
|
28
|
+
description: string;
|
|
29
|
+
parameters: {
|
|
30
|
+
type: 'object';
|
|
31
|
+
properties: Record<string, any>;
|
|
32
|
+
required: string[];
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export declare class DatabaseToolService {
|
|
37
|
+
private configService;
|
|
38
|
+
private mainSupabase;
|
|
39
|
+
private tableSchemas;
|
|
40
|
+
private clientCache;
|
|
41
|
+
constructor(mainSupabase: SupabaseClient, configService: DatabaseToolConfigService);
|
|
42
|
+
/**
|
|
43
|
+
* Get or create external database client for a company
|
|
44
|
+
*/
|
|
45
|
+
private getExternalClient;
|
|
46
|
+
/**
|
|
47
|
+
* Clear client cache (e.g., after config update)
|
|
48
|
+
*/
|
|
49
|
+
clearClientCache(companyId?: number): void;
|
|
50
|
+
/**
|
|
51
|
+
* Get table schema by introspecting the database
|
|
52
|
+
*/
|
|
53
|
+
private getTableSchema;
|
|
54
|
+
/**
|
|
55
|
+
* Get available tools for a company for LLM function calling
|
|
56
|
+
*/
|
|
57
|
+
getToolsForCompany(companyId: number): Promise<ToolDefinition[]>;
|
|
58
|
+
/**
|
|
59
|
+
* Convert database tool config to LLM tool definition
|
|
60
|
+
*/
|
|
61
|
+
private convertToToolDefinition;
|
|
62
|
+
/**
|
|
63
|
+
* Execute a dynamic tool call
|
|
64
|
+
*/
|
|
65
|
+
executeTool(toolName: string, parameters: Record<string, any>, companyId: number, userContext?: UserQueryContext): Promise<any>;
|
|
66
|
+
/**
|
|
67
|
+
* Execute a query for a specific tool
|
|
68
|
+
*/
|
|
69
|
+
private executeToolQuery;
|
|
70
|
+
/**
|
|
71
|
+
* Clear schema cache (useful for testing)
|
|
72
|
+
*/
|
|
73
|
+
clearSchemaCache(): void;
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=DatabaseToolService.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DatabaseToolService.d.ts","sourceRoot":"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