@resolveio/server-lib 22.1.14 → 22.1.16
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/methods/ai-terminal.js +230 -96
- package/methods/ai-terminal.js.map +1 -1
- package/package.json +1 -1
package/methods/ai-terminal.js
CHANGED
|
@@ -551,6 +551,7 @@ var AI_ASSISTANT_SYSTEM_PROMPT = [
|
|
|
551
551
|
'- Do not modify files, run destructive commands, or access databases directly.',
|
|
552
552
|
'- Read-only data access is allowed only via the REPORT_BUILDER_READ/REPORT_BUILDER_AGG directives (see below).',
|
|
553
553
|
'- Do not access secrets, credentials, or user data.',
|
|
554
|
+
'- If asked about the underlying AI/model/provider/runtime (including Codex/OpenAI/local-vs-hosted/version details), refuse. This information is not available to users, including admins and super admins.',
|
|
554
555
|
'- If the user has a customer portal scope (other.id_customer), only discuss that customer\'s data and what is visible in their customer portal. Never reference other customers or internal/admin-only data. If asked for anything outside the portal, say it isn\'t available.',
|
|
555
556
|
'- Do not assist with hacking, bypassing security, or abuse.',
|
|
556
557
|
'Accuracy & tools:',
|
|
@@ -1254,7 +1255,7 @@ function loadAiTerminalMethods(methodManager) {
|
|
|
1254
1255
|
}
|
|
1255
1256
|
function executeAiTerminalRun(payload, context) {
|
|
1256
1257
|
return __awaiter(this, void 0, void 0, function () {
|
|
1257
|
-
var input, message, requestId, isSuperAdmin, guardrailsEnabled, guardrail,
|
|
1258
|
+
var input, message, requestId, identityGuardrail, conversation_1, now_1, userMsg, assistantMsg, isSuperAdmin, guardrailsEnabled, guardrail, conversation_2, now_2, userMsg, assistantMsg, conversation, now, attachments, attachmentData, config, systemPrompt, userPromptTemplate, userPrompt, historyLimit, history, _a, messages, openaiSettings, client, response, usage, idClient, userDoc, assistantDoc, insertResult;
|
|
1258
1259
|
return __generator(this, function (_b) {
|
|
1259
1260
|
switch (_b.label) {
|
|
1260
1261
|
case 0:
|
|
@@ -1264,15 +1265,10 @@ function executeAiTerminalRun(payload, context) {
|
|
|
1264
1265
|
throw new Error('Message is required.');
|
|
1265
1266
|
}
|
|
1266
1267
|
requestId = normalizeOptionalString(input.request_id);
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
isSuperAdmin = _b.sent();
|
|
1270
|
-
guardrailsEnabled = input.guardrails !== false && !isSuperAdmin;
|
|
1271
|
-
if (!guardrailsEnabled) return [3 /*break*/, 6];
|
|
1272
|
-
guardrail = evaluateGuardrails(message);
|
|
1273
|
-
if (!(guardrail === null || guardrail === void 0 ? void 0 : guardrail.blocked)) return [3 /*break*/, 6];
|
|
1268
|
+
identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(message);
|
|
1269
|
+
if (!(identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked)) return [3 /*break*/, 5];
|
|
1274
1270
|
return [4 /*yield*/, ensureConversation(input, 'openai', context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1275
|
-
case
|
|
1271
|
+
case 1:
|
|
1276
1272
|
conversation_1 = _b.sent();
|
|
1277
1273
|
now_1 = new Date();
|
|
1278
1274
|
userMsg = {
|
|
@@ -1286,47 +1282,88 @@ function executeAiTerminalRun(payload, context) {
|
|
|
1286
1282
|
assistantMsg = {
|
|
1287
1283
|
id_conversation: conversation_1._id,
|
|
1288
1284
|
role: 'assistant',
|
|
1289
|
-
content:
|
|
1290
|
-
metadata: __assign({ blocked: true, reason:
|
|
1285
|
+
content: identityGuardrail.response,
|
|
1286
|
+
metadata: __assign({ blocked: true, reason: identityGuardrail.reason }, (requestId ? { request_id: requestId } : {})),
|
|
1291
1287
|
createdAt: now_1,
|
|
1292
1288
|
updatedAt: now_1
|
|
1293
1289
|
};
|
|
1294
1290
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(userMsg)];
|
|
1295
|
-
case
|
|
1291
|
+
case 2:
|
|
1296
1292
|
_b.sent();
|
|
1297
1293
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(assistantMsg)];
|
|
1298
|
-
case
|
|
1294
|
+
case 3:
|
|
1299
1295
|
_b.sent();
|
|
1300
1296
|
return [4 /*yield*/, touchConversation(conversation_1._id, now_1)];
|
|
1301
|
-
case
|
|
1297
|
+
case 4:
|
|
1302
1298
|
_b.sent();
|
|
1303
1299
|
return [2 /*return*/, {
|
|
1304
1300
|
conversation: conversation_1,
|
|
1305
1301
|
message: assistantMsg,
|
|
1306
|
-
guardrails: { blocked: true, reason:
|
|
1302
|
+
guardrails: { blocked: true, reason: identityGuardrail.reason }
|
|
1307
1303
|
}];
|
|
1308
|
-
case
|
|
1304
|
+
case 5: return [4 /*yield*/, resolveIsSuperAdmin(context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1305
|
+
case 6:
|
|
1306
|
+
isSuperAdmin = _b.sent();
|
|
1307
|
+
guardrailsEnabled = input.guardrails !== false && !isSuperAdmin;
|
|
1308
|
+
if (!guardrailsEnabled) return [3 /*break*/, 11];
|
|
1309
|
+
guardrail = evaluateGuardrails(message);
|
|
1310
|
+
if (!(guardrail === null || guardrail === void 0 ? void 0 : guardrail.blocked)) return [3 /*break*/, 11];
|
|
1311
|
+
return [4 /*yield*/, ensureConversation(input, 'openai', context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1309
1312
|
case 7:
|
|
1313
|
+
conversation_2 = _b.sent();
|
|
1314
|
+
now_2 = new Date();
|
|
1315
|
+
userMsg = {
|
|
1316
|
+
id_conversation: conversation_2._id,
|
|
1317
|
+
role: 'user',
|
|
1318
|
+
content: message,
|
|
1319
|
+
metadata: requestId ? { request_id: requestId } : undefined,
|
|
1320
|
+
createdAt: now_2,
|
|
1321
|
+
updatedAt: now_2
|
|
1322
|
+
};
|
|
1323
|
+
assistantMsg = {
|
|
1324
|
+
id_conversation: conversation_2._id,
|
|
1325
|
+
role: 'assistant',
|
|
1326
|
+
content: guardrail.response,
|
|
1327
|
+
metadata: __assign({ blocked: true, reason: guardrail.reason }, (requestId ? { request_id: requestId } : {})),
|
|
1328
|
+
createdAt: now_2,
|
|
1329
|
+
updatedAt: now_2
|
|
1330
|
+
};
|
|
1331
|
+
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(userMsg)];
|
|
1332
|
+
case 8:
|
|
1333
|
+
_b.sent();
|
|
1334
|
+
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(assistantMsg)];
|
|
1335
|
+
case 9:
|
|
1336
|
+
_b.sent();
|
|
1337
|
+
return [4 /*yield*/, touchConversation(conversation_2._id, now_2)];
|
|
1338
|
+
case 10:
|
|
1339
|
+
_b.sent();
|
|
1340
|
+
return [2 /*return*/, {
|
|
1341
|
+
conversation: conversation_2,
|
|
1342
|
+
message: assistantMsg,
|
|
1343
|
+
guardrails: { blocked: true, reason: guardrail.reason }
|
|
1344
|
+
}];
|
|
1345
|
+
case 11: return [4 /*yield*/, ensureConversation(input, 'openai', context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1346
|
+
case 12:
|
|
1310
1347
|
conversation = _b.sent();
|
|
1311
1348
|
now = new Date();
|
|
1312
1349
|
attachments = Array.isArray(input.attachments) ? input.attachments : [];
|
|
1313
1350
|
return [4 /*yield*/, readAttachmentContents(attachments)];
|
|
1314
|
-
case
|
|
1351
|
+
case 13:
|
|
1315
1352
|
attachmentData = _b.sent();
|
|
1316
1353
|
config = sanitizeConfig(input.config || {});
|
|
1317
1354
|
systemPrompt = normalizeOptionalString(config.system_prompt) || '';
|
|
1318
1355
|
userPromptTemplate = normalizeOptionalString(config.user_prompt_template);
|
|
1319
1356
|
userPrompt = buildUserPrompt(userPromptTemplate, message, attachmentData.promptText);
|
|
1320
1357
|
historyLimit = normalizeHistoryLimit(input.max_history);
|
|
1321
|
-
if (!(historyLimit > 0)) return [3 /*break*/,
|
|
1358
|
+
if (!(historyLimit > 0)) return [3 /*break*/, 15];
|
|
1322
1359
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.find({ id_conversation: conversation._id, role: { $in: ['user', 'assistant'] } }, { sort: { createdAt: 1 }, limit: historyLimit * 2 })];
|
|
1323
|
-
case
|
|
1360
|
+
case 14:
|
|
1324
1361
|
_a = _b.sent();
|
|
1325
|
-
return [3 /*break*/,
|
|
1326
|
-
case
|
|
1362
|
+
return [3 /*break*/, 16];
|
|
1363
|
+
case 15:
|
|
1327
1364
|
_a = [];
|
|
1328
|
-
_b.label =
|
|
1329
|
-
case
|
|
1365
|
+
_b.label = 16;
|
|
1366
|
+
case 16:
|
|
1330
1367
|
history = _a;
|
|
1331
1368
|
messages = [];
|
|
1332
1369
|
if (systemPrompt) {
|
|
@@ -1345,13 +1382,13 @@ function executeAiTerminalRun(payload, context) {
|
|
|
1345
1382
|
openaiSettings = resolveOpenAISettings(config);
|
|
1346
1383
|
client = new openai_client_1.OpenAIClient(openaiSettings);
|
|
1347
1384
|
return [4 /*yield*/, client.chat(messages, { timeoutMs: 60000, responseFormat: config.response_format })];
|
|
1348
|
-
case
|
|
1385
|
+
case 17:
|
|
1349
1386
|
response = _b.sent();
|
|
1350
1387
|
usage = response.usage || estimateUsage(messages, response.content, openaiSettings.model);
|
|
1351
1388
|
return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1352
|
-
case
|
|
1389
|
+
case 18:
|
|
1353
1390
|
idClient = _b.sent();
|
|
1354
|
-
if (!idClient) return [3 /*break*/,
|
|
1391
|
+
if (!idClient) return [3 /*break*/, 20];
|
|
1355
1392
|
return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
|
|
1356
1393
|
id_client: idClient,
|
|
1357
1394
|
model: response.model || openaiSettings.model || 'unknown',
|
|
@@ -1361,10 +1398,10 @@ function executeAiTerminalRun(payload, context) {
|
|
|
1361
1398
|
category: 'ai-terminal',
|
|
1362
1399
|
id_conversation: conversation._id
|
|
1363
1400
|
})];
|
|
1364
|
-
case
|
|
1401
|
+
case 19:
|
|
1365
1402
|
_b.sent();
|
|
1366
|
-
_b.label =
|
|
1367
|
-
case
|
|
1403
|
+
_b.label = 20;
|
|
1404
|
+
case 20:
|
|
1368
1405
|
userDoc = {
|
|
1369
1406
|
id_conversation: conversation._id,
|
|
1370
1407
|
role: 'user',
|
|
@@ -1389,20 +1426,20 @@ function executeAiTerminalRun(payload, context) {
|
|
|
1389
1426
|
updatedAt: now
|
|
1390
1427
|
};
|
|
1391
1428
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(userDoc)];
|
|
1392
|
-
case
|
|
1429
|
+
case 21:
|
|
1393
1430
|
_b.sent();
|
|
1394
1431
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(assistantDoc)];
|
|
1395
|
-
case
|
|
1432
|
+
case 22:
|
|
1396
1433
|
insertResult = _b.sent();
|
|
1397
1434
|
return [4 /*yield*/, touchConversation(conversation._id, now, insertResult._id)];
|
|
1398
|
-
case
|
|
1435
|
+
case 23:
|
|
1399
1436
|
_b.sent();
|
|
1400
|
-
if (!(input.delete_files_after_run !== false)) return [3 /*break*/,
|
|
1437
|
+
if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 25];
|
|
1401
1438
|
return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
|
|
1402
|
-
case
|
|
1439
|
+
case 24:
|
|
1403
1440
|
_b.sent();
|
|
1404
|
-
_b.label =
|
|
1405
|
-
case
|
|
1441
|
+
_b.label = 25;
|
|
1442
|
+
case 25: return [2 /*return*/, {
|
|
1406
1443
|
conversation: conversation,
|
|
1407
1444
|
message: assistantDoc,
|
|
1408
1445
|
usage: assistantDoc.usage
|
|
@@ -1482,7 +1519,7 @@ function executeAiFormPatch(payload, context) {
|
|
|
1482
1519
|
}
|
|
1483
1520
|
function executeAiAssistantCodexRun(payload, context) {
|
|
1484
1521
|
return __awaiter(this, void 0, void 0, function () {
|
|
1485
|
-
var input, message, aiWorkerDebug, requestId, codexModel, codexFallbackModels, guardrail,
|
|
1522
|
+
var input, message, aiWorkerDebug, requestId, codexModel, codexFallbackModels, guardrail, conversation_3, now_3, userMsg, assistantMsg, user, isSuperAdmin, canViewDebug, hasInvoiceAccess, customerId, conversation, now, attachments, navigationFastPath, userMsg, assistantMsg, assistantInsert, assistantMessageId_1, changeHistoryFastPath, userMsg, assistantMsg, assistantInsert, assistantMessageId_2, attachmentData, historyLimit, history, _a, historyLines, recentToolError, userDoc, initialProgress, assistantDoc, insertResult, assistantMessageId;
|
|
1486
1523
|
var _this = this;
|
|
1487
1524
|
var _b, _c, _d;
|
|
1488
1525
|
return __generator(this, function (_e) {
|
|
@@ -1504,23 +1541,23 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1504
1541
|
if (!(guardrail === null || guardrail === void 0 ? void 0 : guardrail.blocked)) return [3 /*break*/, 5];
|
|
1505
1542
|
return [4 /*yield*/, ensureConversation(input, 'codex', context === null || context === void 0 ? void 0 : context.id_user)];
|
|
1506
1543
|
case 1:
|
|
1507
|
-
|
|
1508
|
-
|
|
1544
|
+
conversation_3 = _e.sent();
|
|
1545
|
+
now_3 = new Date();
|
|
1509
1546
|
userMsg = {
|
|
1510
|
-
id_conversation:
|
|
1547
|
+
id_conversation: conversation_3._id,
|
|
1511
1548
|
role: 'user',
|
|
1512
1549
|
content: message,
|
|
1513
1550
|
metadata: requestId ? { request_id: requestId } : undefined,
|
|
1514
|
-
createdAt:
|
|
1515
|
-
updatedAt:
|
|
1551
|
+
createdAt: now_3,
|
|
1552
|
+
updatedAt: now_3
|
|
1516
1553
|
};
|
|
1517
1554
|
assistantMsg = {
|
|
1518
|
-
id_conversation:
|
|
1555
|
+
id_conversation: conversation_3._id,
|
|
1519
1556
|
role: 'assistant',
|
|
1520
1557
|
content: guardrail.response,
|
|
1521
1558
|
metadata: __assign({ blocked: true, reason: guardrail.reason }, (requestId ? { request_id: requestId } : {})),
|
|
1522
|
-
createdAt:
|
|
1523
|
-
updatedAt:
|
|
1559
|
+
createdAt: now_3,
|
|
1560
|
+
updatedAt: now_3
|
|
1524
1561
|
};
|
|
1525
1562
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(userMsg)];
|
|
1526
1563
|
case 2:
|
|
@@ -1528,11 +1565,11 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1528
1565
|
return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.insertOne(assistantMsg)];
|
|
1529
1566
|
case 3:
|
|
1530
1567
|
_e.sent();
|
|
1531
|
-
return [4 /*yield*/, touchConversation(
|
|
1568
|
+
return [4 /*yield*/, touchConversation(conversation_3._id, now_3)];
|
|
1532
1569
|
case 4:
|
|
1533
1570
|
_e.sent();
|
|
1534
1571
|
return [2 /*return*/, {
|
|
1535
|
-
conversation:
|
|
1572
|
+
conversation: conversation_3,
|
|
1536
1573
|
message: assistantMsg,
|
|
1537
1574
|
guardrails: { blocked: true, reason: guardrail.reason }
|
|
1538
1575
|
}];
|
|
@@ -1540,6 +1577,7 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1540
1577
|
case 6:
|
|
1541
1578
|
user = _e.sent();
|
|
1542
1579
|
isSuperAdmin = !!((_b = user === null || user === void 0 ? void 0 : user.roles) === null || _b === void 0 ? void 0 : _b.super_admin);
|
|
1580
|
+
canViewDebug = isAssistantDebugUser(user);
|
|
1543
1581
|
hasInvoiceAccess = userHasInvoiceAccess(user);
|
|
1544
1582
|
customerId = normalizeOptionalString((_c = user === null || user === void 0 ? void 0 : user.other) === null || _c === void 0 ? void 0 : _c.id_customer);
|
|
1545
1583
|
return [4 /*yield*/, ensureConversation(input, 'codex', context === null || context === void 0 ? void 0 : context.id_user)];
|
|
@@ -2408,7 +2446,7 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
2408
2446
|
});
|
|
2409
2447
|
}
|
|
2410
2448
|
finalNow = new Date();
|
|
2411
|
-
if (
|
|
2449
|
+
if (canViewDebug) {
|
|
2412
2450
|
finishedAt = Date.now();
|
|
2413
2451
|
codexMs = timingBreakdown.directiveMs
|
|
2414
2452
|
+ timingBreakdown.plannerMs
|
|
@@ -2671,7 +2709,7 @@ function executeAiAssistantReportIssue(payload, context) {
|
|
|
2671
2709
|
}
|
|
2672
2710
|
function executeAiAssistantMongoRead(payload, context) {
|
|
2673
2711
|
return __awaiter(this, void 0, void 0, function () {
|
|
2674
|
-
var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, strippedClient, clientScopedQuery, scopedQuery, normalized, findOptions, runFindWithRepair, initialRead, documents, executedQuery, probeDocs, dateFallback, fallbackQuery, fallbackRead, fallbackDocs, expanded, fallbackRead, fallbackDocs, nameFallback, fallbackRead, fallbackDocs, _c, chemicalLookup, fallbackRead, fallbackDocs, queryFields, _d, aliases, rewrittenQuery, fallbackRead, fallbackDocs, _e, activeFallback, fallbackRead, fallbackDocs, _f, idLookup, fallbackRead, fallbackDocs, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, hasActiveStatusFilters, crossCollectionCandidates, crossCollectionCandidates_1, crossCollectionCandidates_1_1, candidateCollection, fallbackPayload, fallbackResult, fallbackDocs, existingFallbacks, rejectedQuality, error_5, existingErrors, e_1_1, nameFields, dateFields, diagnostics, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, total, sanitizedDocuments, requestedFields, missingFields, _o, projectionAliases, expandedProjection, refreshedDocs, includeIds, fieldAliases, displayDocs, idLookupDisplay, priorityFields, displayMaxRows, display;
|
|
2712
|
+
var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, canViewDebug, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, strippedClient, clientScopedQuery, scopedQuery, normalized, findOptions, runFindWithRepair, initialRead, documents, executedQuery, probeDocs, dateFallback, fallbackQuery, fallbackRead, fallbackDocs, expanded, fallbackRead, fallbackDocs, nameFallback, fallbackRead, fallbackDocs, _c, chemicalLookup, fallbackRead, fallbackDocs, queryFields, _d, aliases, rewrittenQuery, fallbackRead, fallbackDocs, _e, activeFallback, fallbackRead, fallbackDocs, _f, idLookup, fallbackRead, fallbackDocs, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, hasActiveStatusFilters, crossCollectionCandidates, crossCollectionCandidates_1, crossCollectionCandidates_1_1, candidateCollection, fallbackPayload, fallbackResult, fallbackDocs, existingFallbacks, rejectedQuality, error_5, existingErrors, e_1_1, nameFields, dateFields, diagnostics, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, total, sanitizedDocuments, requestedFields, missingFields, _o, projectionAliases, expandedProjection, refreshedDocs, includeIds, fieldAliases, displayDocs, idLookupDisplay, priorityFields, displayMaxRows, display;
|
|
2675
2713
|
var e_1, _p;
|
|
2676
2714
|
var _this = this;
|
|
2677
2715
|
var _q, _r;
|
|
@@ -2709,7 +2747,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
2709
2747
|
: input.permissionView;
|
|
2710
2748
|
return [4 /*yield*/, ensureAssistantReadAccess(context, effectivePermissionView, collection)];
|
|
2711
2749
|
case 3:
|
|
2712
|
-
_a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
|
|
2750
|
+
_a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin, canViewDebug = _a.canViewDebug;
|
|
2713
2751
|
if (!isSuperAdmin && AI_ASSISTANT_BLOCKED_COLLECTIONS.has(collection)) {
|
|
2714
2752
|
throw new Error('AI assistant report builder bridge: Access denied.');
|
|
2715
2753
|
}
|
|
@@ -3039,7 +3077,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3039
3077
|
case 33:
|
|
3040
3078
|
fallbackResult = _s.sent();
|
|
3041
3079
|
if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
|
|
3042
|
-
if (
|
|
3080
|
+
if (canViewDebug && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
|
|
3043
3081
|
existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
|
|
3044
3082
|
? fallbackResult.debug.fallbacks
|
|
3045
3083
|
: {};
|
|
@@ -3051,7 +3089,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3051
3089
|
}
|
|
3052
3090
|
return [2 /*return*/, fallbackResult];
|
|
3053
3091
|
}
|
|
3054
|
-
if (
|
|
3092
|
+
if (canViewDebug) {
|
|
3055
3093
|
fallbackMeta.reportFallback = { from: collection, to: baseCollection, attempted: true, used: false };
|
|
3056
3094
|
}
|
|
3057
3095
|
_s.label = 34;
|
|
@@ -3092,7 +3130,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3092
3130
|
fallbackResult = _s.sent();
|
|
3093
3131
|
fallbackDocs = Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) ? fallbackResult.documents : [];
|
|
3094
3132
|
if (fallbackDocs.length && shouldAcceptAssistantFallbackDocuments(fallbackDocs)) {
|
|
3095
|
-
if (
|
|
3133
|
+
if (canViewDebug && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
|
|
3096
3134
|
existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
|
|
3097
3135
|
? fallbackResult.debug.fallbacks
|
|
3098
3136
|
: {};
|
|
@@ -3106,7 +3144,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3106
3144
|
}
|
|
3107
3145
|
return [2 /*return*/, fallbackResult];
|
|
3108
3146
|
}
|
|
3109
|
-
if (fallbackDocs.length &&
|
|
3147
|
+
if (fallbackDocs.length && canViewDebug && fallbackMeta.collectionRetry && typeof fallbackMeta.collectionRetry === 'object') {
|
|
3110
3148
|
rejectedQuality = Array.isArray(fallbackMeta.collectionRetry.rejectedQuality)
|
|
3111
3149
|
? fallbackMeta.collectionRetry.rejectedQuality
|
|
3112
3150
|
: [];
|
|
@@ -3146,7 +3184,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3146
3184
|
return [7 /*endfinally*/];
|
|
3147
3185
|
case 45: return [3 /*break*/, 47];
|
|
3148
3186
|
case 46:
|
|
3149
|
-
if (!documents.length && crossCollectionRetryEnabled && hasActiveStatusFilters &&
|
|
3187
|
+
if (!documents.length && crossCollectionRetryEnabled && hasActiveStatusFilters && canViewDebug) {
|
|
3150
3188
|
fallbackMeta.collectionRetry = {
|
|
3151
3189
|
from: collection,
|
|
3152
3190
|
root: retryRootCollection,
|
|
@@ -3157,7 +3195,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3157
3195
|
}
|
|
3158
3196
|
_s.label = 47;
|
|
3159
3197
|
case 47:
|
|
3160
|
-
if (!(!documents.length &&
|
|
3198
|
+
if (!(!documents.length && canViewDebug)) return [3 /*break*/, 64];
|
|
3161
3199
|
nameFields = collectMatchFieldsByCondition(executedQuery, function (field, condition) { return isRegexMatchCondition(condition)
|
|
3162
3200
|
|| (typeof condition === 'string' && shouldApplyAssistantNameRegex(field)); });
|
|
3163
3201
|
dateFields = collectMatchFieldsByCondition(executedQuery, function (_field, condition) { return isDateCondition(condition); });
|
|
@@ -3328,7 +3366,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3328
3366
|
if (Object.keys(fieldAliases).length) {
|
|
3329
3367
|
fallbackMeta.fieldAliases = fieldAliases;
|
|
3330
3368
|
}
|
|
3331
|
-
return [2 /*return*/, __assign({ documents: sanitizedDocuments, total: total, display: display }, (
|
|
3369
|
+
return [2 /*return*/, __assign({ documents: sanitizedDocuments, total: total, display: display }, (canViewDebug ? {
|
|
3332
3370
|
debug: {
|
|
3333
3371
|
collection: collection,
|
|
3334
3372
|
collectionRequested: rawCollection,
|
|
@@ -3350,7 +3388,7 @@ function executeAiAssistantMongoRead(payload, context) {
|
|
|
3350
3388
|
}
|
|
3351
3389
|
function executeAiAssistantMongoAggregate(payload, context) {
|
|
3352
3390
|
return __awaiter(this, void 0, void 0, function () {
|
|
3353
|
-
var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, nestedFallbacks, nestedFallbacks_1, nestedFallbacks_1_1, nestedFallback, fallbackPayload, fallbackResult, existingFallbacks, error_7, errorMessage, existingErrors, e_2_1, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, fallbackAcceptanceOptions, crossCollectionCandidates, crossCollectionCandidates_2, crossCollectionCandidates_2_1, candidateCollection, fallbackPayload, fallbackResult, fallbackDocs, fallbackQuality, existingFallbacks, rejectedQuality, error_8, existingErrors, e_3_1, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
|
|
3391
|
+
var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, canViewDebug, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, nestedFallbacks, nestedFallbacks_1, nestedFallbacks_1_1, nestedFallback, fallbackPayload, fallbackResult, existingFallbacks, error_7, errorMessage, existingErrors, e_2_1, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, fallbackAcceptanceOptions, crossCollectionCandidates, crossCollectionCandidates_2, crossCollectionCandidates_2_1, candidateCollection, fallbackPayload, fallbackResult, fallbackDocs, fallbackQuality, existingFallbacks, rejectedQuality, error_8, existingErrors, e_3_1, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
|
|
3354
3392
|
var e_2, _o, e_3, _p;
|
|
3355
3393
|
var _this = this;
|
|
3356
3394
|
var _q, _r;
|
|
@@ -3388,7 +3426,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
3388
3426
|
: input.permissionView;
|
|
3389
3427
|
return [4 /*yield*/, ensureAssistantReadAccess(context, effectivePermissionView, collection)];
|
|
3390
3428
|
case 3:
|
|
3391
|
-
_a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
|
|
3429
|
+
_a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin, canViewDebug = _a.canViewDebug;
|
|
3392
3430
|
if (!isSuperAdmin && AI_ASSISTANT_BLOCKED_COLLECTIONS.has(collection)) {
|
|
3393
3431
|
throw new Error('AI assistant report builder bridge: Access denied.');
|
|
3394
3432
|
}
|
|
@@ -3952,7 +3990,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
3952
3990
|
case 47:
|
|
3953
3991
|
fallbackResult = _s.sent();
|
|
3954
3992
|
if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
|
|
3955
|
-
if (
|
|
3993
|
+
if (canViewDebug && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
|
|
3956
3994
|
existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
|
|
3957
3995
|
? fallbackResult.debug.fallbacks
|
|
3958
3996
|
: {};
|
|
@@ -4008,7 +4046,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4008
4046
|
case 55:
|
|
4009
4047
|
fallbackResult = _s.sent();
|
|
4010
4048
|
if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
|
|
4011
|
-
if (
|
|
4049
|
+
if (canViewDebug && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
|
|
4012
4050
|
existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
|
|
4013
4051
|
? fallbackResult.debug.fallbacks
|
|
4014
4052
|
: {};
|
|
@@ -4020,7 +4058,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4020
4058
|
}
|
|
4021
4059
|
return [2 /*return*/, fallbackResult];
|
|
4022
4060
|
}
|
|
4023
|
-
if (
|
|
4061
|
+
if (canViewDebug) {
|
|
4024
4062
|
fallbackMeta.reportFallback = { from: collection, to: baseCollection, attempted: true, used: false };
|
|
4025
4063
|
}
|
|
4026
4064
|
_s.label = 56;
|
|
@@ -4062,7 +4100,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4062
4100
|
fallbackDocs = Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) ? fallbackResult.documents : [];
|
|
4063
4101
|
fallbackQuality = evaluateAssistantFallbackDocumentsQuality(fallbackDocs, fallbackAcceptanceOptions);
|
|
4064
4102
|
if (fallbackDocs.length && fallbackQuality.accepted) {
|
|
4065
|
-
if (
|
|
4103
|
+
if (canViewDebug && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
|
|
4066
4104
|
existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
|
|
4067
4105
|
? fallbackResult.debug.fallbacks
|
|
4068
4106
|
: {};
|
|
@@ -4076,7 +4114,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4076
4114
|
}
|
|
4077
4115
|
return [2 /*return*/, fallbackResult];
|
|
4078
4116
|
}
|
|
4079
|
-
if (fallbackDocs.length &&
|
|
4117
|
+
if (fallbackDocs.length && canViewDebug && fallbackMeta.collectionRetry && typeof fallbackMeta.collectionRetry === 'object') {
|
|
4080
4118
|
rejectedQuality = Array.isArray(fallbackMeta.collectionRetry.rejectedQuality)
|
|
4081
4119
|
? fallbackMeta.collectionRetry.rejectedQuality
|
|
4082
4120
|
: [];
|
|
@@ -4120,7 +4158,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4120
4158
|
finally { if (e_3) throw e_3.error; }
|
|
4121
4159
|
return [7 /*endfinally*/];
|
|
4122
4160
|
case 67:
|
|
4123
|
-
if (!(!documents.length &&
|
|
4161
|
+
if (!(!documents.length && canViewDebug)) return [3 /*break*/, 84];
|
|
4124
4162
|
matchStages = (executedPipeline || []).filter(function (stage) { return stage && typeof stage === 'object' && stage.$match && typeof stage.$match === 'object'; });
|
|
4125
4163
|
diagnostics = {};
|
|
4126
4164
|
if (!matchStages.length) return [3 /*break*/, 84];
|
|
@@ -4241,7 +4279,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
4241
4279
|
maxRows: normalizedOptions.limit || sanitizedDocuments.length,
|
|
4242
4280
|
includeGroupFromId: false
|
|
4243
4281
|
});
|
|
4244
|
-
return [2 /*return*/, __assign(__assign({ documents: sanitizedDocuments, display: display }, (verification ? { verification: verification } : {})), (
|
|
4282
|
+
return [2 /*return*/, __assign(__assign({ documents: sanitizedDocuments, display: display }, (verification ? { verification: verification } : {})), (canViewDebug ? {
|
|
4245
4283
|
debug: __assign(__assign({ collection: collection, collectionRequested: rawCollection, collectionResolved: collection, collectionMatched: collectionResolution.matched, collectionCandidates: collectionResolution.candidates, collectionScore: collectionResolution.score, bridge: 'report-builder', database: dbName, query: scopedQuery, options: normalizedOptions.aggregateOptions, originalPipeline: limitedPipeline, executedPipeline: executedPipeline }, (verification ? { verification: verification } : {})), { fallbacks: fallbackMeta })
|
|
4246
4284
|
} : {}))];
|
|
4247
4285
|
}
|
|
@@ -9562,23 +9600,15 @@ function applyAssistantDisplayTableToResponse(value, display) {
|
|
|
9562
9600
|
var rowCount = typeof normalizedDisplay.rowCount === 'number' && normalizedDisplay.rowCount > 0
|
|
9563
9601
|
? normalizedDisplay.rowCount
|
|
9564
9602
|
: 0;
|
|
9565
|
-
if (rowCount <= 0) {
|
|
9566
|
-
if (!cleaned_1) {
|
|
9567
|
-
return 'No rows matched your request.';
|
|
9568
|
-
}
|
|
9569
|
-
if (/\bno rows? matched\b/i.test(cleaned_1)) {
|
|
9570
|
-
return cleaned_1;
|
|
9571
|
-
}
|
|
9572
|
-
return "".concat(cleaned_1.trim(), "\n\nNo rows matched your request.").trim();
|
|
9573
|
-
}
|
|
9574
9603
|
var fallbackColumns = Array.isArray(normalizedDisplay.columns) && normalizedDisplay.columns.length
|
|
9575
9604
|
? normalizedDisplay.columns
|
|
9576
9605
|
: resolveAssistantEmptyDisplayColumns(cleaned_1 || value);
|
|
9577
9606
|
var normalizedColumns = fallbackColumns.length === 1
|
|
9578
9607
|
? __spreadArray(__spreadArray([], __read(fallbackColumns), false), ['Value'], false) : fallbackColumns;
|
|
9579
|
-
var rowSummary =
|
|
9580
|
-
|
|
9581
|
-
|
|
9608
|
+
var rowSummary = [(_a = {},
|
|
9609
|
+
_a[normalizedColumns[0]] = rowCount > 0 ? 'Rows matched' : 'No rows matched',
|
|
9610
|
+
_a[normalizedColumns[1]] = rowCount,
|
|
9611
|
+
_a)];
|
|
9582
9612
|
var tableDisplay = {
|
|
9583
9613
|
columns: normalizedColumns,
|
|
9584
9614
|
rows: rowSummary,
|
|
@@ -9590,10 +9620,19 @@ function applyAssistantDisplayTableToResponse(value, display) {
|
|
|
9590
9620
|
if (!emptyTable) {
|
|
9591
9621
|
return cleaned_1 || value;
|
|
9592
9622
|
}
|
|
9623
|
+
var noRowsNote = rowCount > 0 ? '' : 'No rows matched your request.';
|
|
9624
|
+
var base = cleaned_1
|
|
9625
|
+
? (noRowsNote && !/\bno rows? matched\b/i.test(cleaned_1)
|
|
9626
|
+
? "".concat(cleaned_1.trim(), "\n\n").concat(noRowsNote).trim()
|
|
9627
|
+
: cleaned_1.trim())
|
|
9628
|
+
: noRowsNote;
|
|
9593
9629
|
if (!cleaned_1) {
|
|
9594
|
-
|
|
9630
|
+
if (!base) {
|
|
9631
|
+
return emptyTable;
|
|
9632
|
+
}
|
|
9633
|
+
return "".concat(base, "\n\n").concat(emptyTable).trim();
|
|
9595
9634
|
}
|
|
9596
|
-
return "".concat(
|
|
9635
|
+
return "".concat(base, "\n\n").concat(emptyTable).trim();
|
|
9597
9636
|
}
|
|
9598
9637
|
var table = formatDisplayTableMarkdown(normalizedDisplay);
|
|
9599
9638
|
if (!table) {
|
|
@@ -9635,7 +9674,7 @@ function isDisplayObjectLike(value) {
|
|
|
9635
9674
|
}
|
|
9636
9675
|
function ensureAssistantReadAccess(context, permissionView, collection) {
|
|
9637
9676
|
return __awaiter(this, void 0, void 0, function () {
|
|
9638
|
-
var idUser, user, isSuperAdmin, normalizedCollection, normalizedPermission, requiresInvoiceAccess, hasInvoiceAccess, hasViewAccess;
|
|
9677
|
+
var idUser, user, isSuperAdmin, canViewDebug, normalizedCollection, normalizedPermission, requiresInvoiceAccess, hasInvoiceAccess, hasViewAccess;
|
|
9639
9678
|
var _a;
|
|
9640
9679
|
return __generator(this, function (_b) {
|
|
9641
9680
|
switch (_b.label) {
|
|
@@ -9651,8 +9690,9 @@ function ensureAssistantReadAccess(context, permissionView, collection) {
|
|
|
9651
9690
|
throw new Error('AI assistant report builder bridge: Unauthorized.');
|
|
9652
9691
|
}
|
|
9653
9692
|
isSuperAdmin = !!((_a = user === null || user === void 0 ? void 0 : user.roles) === null || _a === void 0 ? void 0 : _a.super_admin);
|
|
9693
|
+
canViewDebug = isAssistantDebugUser(user);
|
|
9654
9694
|
if (isSuperAdmin) {
|
|
9655
|
-
return [2 /*return*/, { user: user, isSuperAdmin: isSuperAdmin }];
|
|
9695
|
+
return [2 /*return*/, { user: user, isSuperAdmin: isSuperAdmin, canViewDebug: canViewDebug }];
|
|
9656
9696
|
}
|
|
9657
9697
|
normalizedCollection = normalizeOptionalString(collection);
|
|
9658
9698
|
normalizedPermission = normalizeAssistantPermissionView(permissionView, normalizedCollection);
|
|
@@ -9668,7 +9708,7 @@ function ensureAssistantReadAccess(context, permissionView, collection) {
|
|
|
9668
9708
|
if (requiresInvoiceAccess && !hasInvoiceAccess) {
|
|
9669
9709
|
throw new Error('AI assistant report builder bridge: Access denied.');
|
|
9670
9710
|
}
|
|
9671
|
-
return [2 /*return*/, { user: user, isSuperAdmin: isSuperAdmin }];
|
|
9711
|
+
return [2 /*return*/, { user: user, isSuperAdmin: isSuperAdmin, canViewDebug: canViewDebug }];
|
|
9672
9712
|
}
|
|
9673
9713
|
});
|
|
9674
9714
|
});
|
|
@@ -10150,6 +10190,18 @@ function normalizeAssistantDateArithmeticArgs(expression) {
|
|
|
10150
10190
|
if (expression instanceof Date || expression instanceof RegExp || isMongoObjectId(expression)) {
|
|
10151
10191
|
return expression;
|
|
10152
10192
|
}
|
|
10193
|
+
var looksLikeDateOperand = function (candidate) {
|
|
10194
|
+
if (candidate instanceof Date) {
|
|
10195
|
+
return true;
|
|
10196
|
+
}
|
|
10197
|
+
if (typeof candidate === 'string') {
|
|
10198
|
+
return candidate.startsWith('$$') || candidate.startsWith('$');
|
|
10199
|
+
}
|
|
10200
|
+
if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
|
|
10201
|
+
return Object.keys(candidate).some(function (op) { return op.startsWith('$'); });
|
|
10202
|
+
}
|
|
10203
|
+
return false;
|
|
10204
|
+
};
|
|
10153
10205
|
var normalizeOperatorArgs = function (operator) {
|
|
10154
10206
|
if (!Object.prototype.hasOwnProperty.call(expression, operator)) {
|
|
10155
10207
|
return;
|
|
@@ -10325,6 +10377,54 @@ function normalizeAssistantDateArithmeticArgs(expression) {
|
|
|
10325
10377
|
});
|
|
10326
10378
|
expression.$dateTrunc = nextArgs;
|
|
10327
10379
|
};
|
|
10380
|
+
var normalizeDateToStringArgs = function () {
|
|
10381
|
+
if (!Object.prototype.hasOwnProperty.call(expression, '$dateToString')) {
|
|
10382
|
+
return;
|
|
10383
|
+
}
|
|
10384
|
+
var rawArgs = expression.$dateToString;
|
|
10385
|
+
if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) {
|
|
10386
|
+
return;
|
|
10387
|
+
}
|
|
10388
|
+
if (rawArgs instanceof Date || rawArgs instanceof RegExp || isMongoObjectId(rawArgs)) {
|
|
10389
|
+
return;
|
|
10390
|
+
}
|
|
10391
|
+
var nextArgs = __assign({}, rawArgs);
|
|
10392
|
+
if (!Object.prototype.hasOwnProperty.call(nextArgs, 'date')) {
|
|
10393
|
+
if (Object.prototype.hasOwnProperty.call(nextArgs, 'startDate')) {
|
|
10394
|
+
nextArgs.date = nextArgs.startDate;
|
|
10395
|
+
}
|
|
10396
|
+
else if (Object.prototype.hasOwnProperty.call(nextArgs, 'start')) {
|
|
10397
|
+
nextArgs.date = nextArgs.start;
|
|
10398
|
+
}
|
|
10399
|
+
else {
|
|
10400
|
+
var dateCandidateKey = Object.keys(nextArgs).find(function (key) {
|
|
10401
|
+
if (key === 'format' || key === 'timezone' || key === 'onNull' || key === 'onError') {
|
|
10402
|
+
return false;
|
|
10403
|
+
}
|
|
10404
|
+
return looksLikeDateOperand(nextArgs[key]);
|
|
10405
|
+
});
|
|
10406
|
+
if (dateCandidateKey) {
|
|
10407
|
+
nextArgs.date = nextArgs[dateCandidateKey];
|
|
10408
|
+
delete nextArgs[dateCandidateKey];
|
|
10409
|
+
}
|
|
10410
|
+
}
|
|
10411
|
+
}
|
|
10412
|
+
delete nextArgs.startDate;
|
|
10413
|
+
delete nextArgs.start;
|
|
10414
|
+
if (!Object.prototype.hasOwnProperty.call(nextArgs, 'date')) {
|
|
10415
|
+
nextArgs.date = '$$NOW';
|
|
10416
|
+
}
|
|
10417
|
+
if (!Object.prototype.hasOwnProperty.call(nextArgs, 'format')) {
|
|
10418
|
+
nextArgs.format = '%Y-%m-%d';
|
|
10419
|
+
}
|
|
10420
|
+
var allowedKeys = new Set(['date', 'format', 'timezone', 'onNull']);
|
|
10421
|
+
Object.keys(nextArgs).forEach(function (key) {
|
|
10422
|
+
if (!allowedKeys.has(key)) {
|
|
10423
|
+
delete nextArgs[key];
|
|
10424
|
+
}
|
|
10425
|
+
});
|
|
10426
|
+
expression.$dateToString = nextArgs;
|
|
10427
|
+
};
|
|
10328
10428
|
var normalizeLetArgs = function () {
|
|
10329
10429
|
if (!Object.prototype.hasOwnProperty.call(expression, '$let')) {
|
|
10330
10430
|
return;
|
|
@@ -10362,18 +10462,6 @@ function normalizeAssistantDateArithmeticArgs(expression) {
|
|
|
10362
10462
|
};
|
|
10363
10463
|
var normalizeDatePartArgs = function () {
|
|
10364
10464
|
var operators = ['$year', '$month', '$week', '$isoWeek', '$isoWeekYear', '$dayOfMonth', '$dayOfYear'];
|
|
10365
|
-
var looksLikeDateOperand = function (candidate) {
|
|
10366
|
-
if (candidate instanceof Date) {
|
|
10367
|
-
return true;
|
|
10368
|
-
}
|
|
10369
|
-
if (typeof candidate === 'string') {
|
|
10370
|
-
return candidate.startsWith('$$') || candidate.startsWith('$');
|
|
10371
|
-
}
|
|
10372
|
-
if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
|
|
10373
|
-
return Object.keys(candidate).some(function (op) { return op.startsWith('$'); });
|
|
10374
|
-
}
|
|
10375
|
-
return false;
|
|
10376
|
-
};
|
|
10377
10465
|
operators.forEach(function (operator) {
|
|
10378
10466
|
if (!Object.prototype.hasOwnProperty.call(expression, operator)) {
|
|
10379
10467
|
return;
|
|
@@ -10415,6 +10503,7 @@ function normalizeAssistantDateArithmeticArgs(expression) {
|
|
|
10415
10503
|
normalizeOperatorArgs('$dateAdd');
|
|
10416
10504
|
normalizeOperatorArgs('$dateSubtract');
|
|
10417
10505
|
normalizeDateTruncArgs();
|
|
10506
|
+
normalizeDateToStringArgs();
|
|
10418
10507
|
normalizeLetArgs();
|
|
10419
10508
|
normalizeDatePartArgs();
|
|
10420
10509
|
return expression;
|
|
@@ -10449,6 +10538,7 @@ function isAssistantDateArithmeticArgumentError(error) {
|
|
|
10449
10538
|
return message.includes('unrecognized argument to $datesubtract:')
|
|
10450
10539
|
|| message.includes('unrecognized argument to $dateadd:')
|
|
10451
10540
|
|| message.includes('unrecognized argument to $datetrunc:')
|
|
10541
|
+
|| message.includes('unrecognized argument to $datetostring:')
|
|
10452
10542
|
|| message.includes('unrecognized option to $year:')
|
|
10453
10543
|
|| message.includes('unrecognized option to $month:')
|
|
10454
10544
|
|| message.includes('unrecognized option to $week:')
|
|
@@ -10462,6 +10552,8 @@ function isAssistantDateArithmeticArgumentError(error) {
|
|
|
10462
10552
|
|| message.includes("missing 'date' parameter to $datetrunc")
|
|
10463
10553
|
|| message.includes("requires 'unit' parameter to $datetrunc")
|
|
10464
10554
|
|| message.includes("requires 'date' parameter to $datetrunc")
|
|
10555
|
+
|| message.includes("requires 'date' parameter to $datetostring")
|
|
10556
|
+
|| message.includes("missing 'date' parameter to $datetostring")
|
|
10465
10557
|
|| message.includes('$datesubtract requires startdate, unit, and amount to be present')
|
|
10466
10558
|
|| message.includes('$dateadd requires startdate, unit, and amount to be present')
|
|
10467
10559
|
|| message.includes('undefined variable: now_start_of_month')
|
|
@@ -10494,13 +10586,19 @@ function isAssistantDottedOutputFieldError(error) {
|
|
|
10494
10586
|
if (!message) {
|
|
10495
10587
|
return false;
|
|
10496
10588
|
}
|
|
10497
|
-
return message.includes("fieldpath field names may not contain '.'")
|
|
10589
|
+
return message.includes("fieldpath field names may not contain '.'")
|
|
10590
|
+
|| (message.includes("field name '") && message.includes("cannot contain '.'"));
|
|
10498
10591
|
}
|
|
10499
10592
|
function extractAssistantDottedFieldPathFromError(error) {
|
|
10500
10593
|
var message = normalizeOptionalString(error === null || error === void 0 ? void 0 : error.message);
|
|
10501
10594
|
if (!message) {
|
|
10502
10595
|
return null;
|
|
10503
10596
|
}
|
|
10597
|
+
var fieldNameMatch = message.match(/field name\s+'([^']+)'/i);
|
|
10598
|
+
if (fieldNameMatch === null || fieldNameMatch === void 0 ? void 0 : fieldNameMatch[1]) {
|
|
10599
|
+
var normalized = normalizeOptionalString(fieldNameMatch[1]);
|
|
10600
|
+
return normalized.includes('.') ? normalized : null;
|
|
10601
|
+
}
|
|
10504
10602
|
var quotedMatch = message.match(/given\s+'([^']+)'/i);
|
|
10505
10603
|
if (quotedMatch && quotedMatch[1]) {
|
|
10506
10604
|
var normalized = normalizeOptionalString(quotedMatch[1]);
|
|
@@ -19412,6 +19510,10 @@ function sanitizeAssistantResponse(value) {
|
|
|
19412
19510
|
function evaluateAssistantGuardrails(message) {
|
|
19413
19511
|
var e_52, _a;
|
|
19414
19512
|
var normalized = String(message || '').toLowerCase();
|
|
19513
|
+
var identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(normalized);
|
|
19514
|
+
if (identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked) {
|
|
19515
|
+
return identityGuardrail;
|
|
19516
|
+
}
|
|
19415
19517
|
var patterns = [
|
|
19416
19518
|
{
|
|
19417
19519
|
pattern: /\b(show|share|paste|provide|dump|output)\b.*\b(code|snippet|file|function|class|script|sql)\b/i,
|
|
@@ -20280,6 +20382,10 @@ function estimateUsage(messages, responseText, model) {
|
|
|
20280
20382
|
function evaluateGuardrails(message) {
|
|
20281
20383
|
var e_56, _a;
|
|
20282
20384
|
var normalized = String(message || '').toLowerCase();
|
|
20385
|
+
var identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(normalized);
|
|
20386
|
+
if (identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked) {
|
|
20387
|
+
return identityGuardrail;
|
|
20388
|
+
}
|
|
20283
20389
|
var patterns = [
|
|
20284
20390
|
{ pattern: /\b(source\s*code|full\s*code|entire\s*code|repo\s*dump|repository|git\s*clone)\b/i, reason: 'Code access is restricted.' },
|
|
20285
20391
|
{ pattern: /\b(show|share|paste|provide|dump|output)\b.*\b(code|file|contents|snippet)\b/i, reason: 'Code access is restricted.' },
|
|
@@ -20309,6 +20415,34 @@ function evaluateGuardrails(message) {
|
|
|
20309
20415
|
}
|
|
20310
20416
|
return null;
|
|
20311
20417
|
}
|
|
20418
|
+
function evaluateAssistantIdentityDisclosureGuardrail(message) {
|
|
20419
|
+
var normalized = String(message || '').toLowerCase();
|
|
20420
|
+
if (!normalized) {
|
|
20421
|
+
return null;
|
|
20422
|
+
}
|
|
20423
|
+
var patterns = [
|
|
20424
|
+
/\b(?:what|which)\s+(?:ai|model|llm)\b/i,
|
|
20425
|
+
/\b(?:what|which)\s+(?:model|engine|provider)\s+(?:are|is)\s+(?:you|this|it)\s+using\b/i,
|
|
20426
|
+
/\b(?:are\s+you|is\s+(?:this|it))\s+(?:codex|gpt|openai)\b/i,
|
|
20427
|
+
/\b(?:run(?:ning)?\s+locally|local(?:ly)?\s+(?:model|runtime|instance))\b/i,
|
|
20428
|
+
/\b(?:model|ai|assistant)\s+version\b/i,
|
|
20429
|
+
/\bwhat\s+version\s+are\s+you\b/i,
|
|
20430
|
+
/\bwhat\s+version\s+is\s+(?:this|it)\b/i,
|
|
20431
|
+
/\bsystem\s+prompt\b/i
|
|
20432
|
+
];
|
|
20433
|
+
if (!patterns.some(function (pattern) { return pattern.test(normalized); })) {
|
|
20434
|
+
return null;
|
|
20435
|
+
}
|
|
20436
|
+
return {
|
|
20437
|
+
blocked: true,
|
|
20438
|
+
reason: 'Assistant identity/runtime details are restricted.',
|
|
20439
|
+
response: 'I can’t share details about the underlying AI model, provider, runtime environment, or version.'
|
|
20440
|
+
};
|
|
20441
|
+
}
|
|
20442
|
+
function isAssistantDebugUser(user) {
|
|
20443
|
+
var username = normalizeOptionalString(user === null || user === void 0 ? void 0 : user.username).toLowerCase();
|
|
20444
|
+
return username === 'admin';
|
|
20445
|
+
}
|
|
20312
20446
|
function resolveIsSuperAdmin(id_user) {
|
|
20313
20447
|
return __awaiter(this, void 0, void 0, function () {
|
|
20314
20448
|
var user, _a;
|