@resolveio/server-lib 20.15.7 → 20.15.8

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.
@@ -145,6 +145,7 @@ var AI_ASSISTANT_DISPLAY_STRING_LIMIT = 160;
145
145
  var AI_ASSISTANT_PROGRESS_PLACEHOLDER = 'Planning...';
146
146
  var AI_ASSISTANT_PROGRESS_TICK_MS = 5000;
147
147
  var AI_ASSISTANT_READ_PREFERENCE = 'secondary';
148
+ var AI_ASSISTANT_NAME_MATCH_FALLBACK_MAX_FIELDS = 12;
148
149
  var AI_ASSISTANT_PROGRESS_TICKS = [
149
150
  'Grabbing Data',
150
151
  'Drafting response'
@@ -1048,10 +1049,10 @@ function executeAiAssistantCodexRun(payload, context) {
1048
1049
  insertResult = _d.sent();
1049
1050
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1050
1051
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1051
- var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, dataQuestion, lastDirective, toolResponseDebug, toolError, termHints, collectionHints, contextRoute, contextMode, hintSeed, termExpansion, hintText, dbName, db, _a, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, responseText, directiveText, directive, directivePrompt, forcedDirective, _b, directivePrompt, forcedDirective, _c, cleanedResponseText, toolRequest, toolResponse, _d, toolPayload, followupPrompt, followupText, _e, error_2, error_3, finalNow, finishedAt, finalMetadata, finalAssistantDoc;
1052
- var _f, _g, _h, _j, _k, _l, _m, _o;
1053
- return __generator(this, function (_p) {
1054
- switch (_p.label) {
1052
+ var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, dataQuestion, lastDirective, toolResponseDebug, toolError, termHints, collectionHints, collectionTokenization, collectionRanking, collectionSelection, timingBreakdown, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, dbName, db, collectionNames, _a, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, responseText, directiveText, directive, directivePrompt, directiveStart, forcedDirective, _b, initialStart, directivePrompt, forcedStart, forcedDirective, _c, cleanedResponseText, toolRequest, toolStart, toolResponse, _d, toolPayload, followupPrompt, followupStart, followupText, _e, error_2, error_3, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalAssistantDoc;
1053
+ var _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
1054
+ return __generator(this, function (_s) {
1055
+ switch (_s.label) {
1055
1056
  case 0:
1056
1057
  runStart = Date.now();
1057
1058
  steps = [];
@@ -1075,31 +1076,54 @@ function executeAiAssistantCodexRun(payload, context) {
1075
1076
  toolError = null;
1076
1077
  termHints = [];
1077
1078
  collectionHints = [];
1079
+ collectionTokenization = null;
1080
+ collectionRanking = null;
1081
+ collectionSelection = null;
1082
+ timingBreakdown = {
1083
+ directiveMs: 0,
1084
+ initialResponseMs: 0,
1085
+ forcedDirectiveMs: 0,
1086
+ toolMs: 0,
1087
+ followupMs: 0
1088
+ };
1078
1089
  contextRoute = normalizeOptionalString((_f = input === null || input === void 0 ? void 0 : input.context) === null || _f === void 0 ? void 0 : _f.route);
1079
1090
  contextMode = normalizeOptionalString((_g = input === null || input === void 0 ? void 0 : input.context) === null || _g === void 0 ? void 0 : _g.mode);
1080
1091
  recordStep('Queued', { requestId: requestId || undefined });
1081
- _p.label = 1;
1092
+ _s.label = 1;
1082
1093
  case 1:
1083
- _p.trys.push([1, 30, 31, 32]);
1094
+ _s.trys.push([1, 30, 31, 32]);
1084
1095
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1085
1096
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1086
1097
  hintText = termExpansion.expanded || hintSeed;
1087
1098
  termHints = termExpansion.matches.map(function (match) { return "".concat(match.term, " -> ").concat(match.expansions.join(', ')); });
1099
+ baseTokens = tokenizeCollectionText(hintSeed);
1100
+ expandedTokens = tokenizeCollectionText(hintText);
1101
+ collectionTokenization = {
1102
+ baseText: hintSeed || undefined,
1103
+ expandedText: hintText || undefined,
1104
+ baseTokens: baseTokens.length ? baseTokens : undefined,
1105
+ expandedTokens: expandedTokens.length ? expandedTokens : undefined
1106
+ };
1088
1107
  recordStep('Planning: term expansion', {
1089
1108
  termMatches: termExpansion.matches.length ? termExpansion.matches : undefined
1090
1109
  });
1091
- _p.label = 2;
1110
+ _s.label = 2;
1092
1111
  case 2:
1093
- _p.trys.push([2, 4, , 5]);
1112
+ _s.trys.push([2, 4, , 5]);
1094
1113
  dbName = resolveAssistantDatabaseName(undefined, input.mongo);
1095
1114
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
1096
- return [4 /*yield*/, resolveAssistantCollectionHints(hintText, dbName, db)];
1115
+ return [4 /*yield*/, listAssistantCollections(db, dbName)];
1097
1116
  case 3:
1098
- collectionHints = _p.sent();
1117
+ collectionNames = _s.sent();
1118
+ collectionHints = resolveCollectionHintsFromTokens(expandedTokens, collectionNames, 5);
1119
+ collectionRanking = buildCollectionRankingDebugFromTokens(expandedTokens, collectionNames, 8);
1099
1120
  return [3 /*break*/, 5];
1100
1121
  case 4:
1101
- _a = _p.sent();
1122
+ _a = _s.sent();
1102
1123
  collectionHints = [];
1124
+ collectionRanking = collectionRanking || ((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens)
1125
+ ? buildCollectionRankingDebugFromTokens(collectionTokenization.expandedTokens || [], [], 0)
1126
+ : null);
1103
1127
  return [3 /*break*/, 5];
1104
1128
  case 5:
1105
1129
  recordStep('Planning: collection hints', {
@@ -1118,7 +1142,7 @@ function executeAiAssistantCodexRun(payload, context) {
1118
1142
  prompt_1 = buildAssistantCodexPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1119
1143
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
1120
1144
  case 6:
1121
- workspaceRoot = _p.sent();
1145
+ workspaceRoot = _s.sent();
1122
1146
  codexConfig = resolveCodexSettings();
1123
1147
  runOptions = {
1124
1148
  timeoutMs: resolveCodexTimeoutMs(),
@@ -1139,71 +1163,80 @@ function executeAiAssistantCodexRun(payload, context) {
1139
1163
  if (!dataQuestion) return [3 /*break*/, 10];
1140
1164
  recordStep('Directive: determine tool', { type: 'data-question' });
1141
1165
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1142
- _p.label = 7;
1166
+ _s.label = 7;
1143
1167
  case 7:
1144
- _p.trys.push([7, 9, , 10]);
1168
+ _s.trys.push([7, 9, , 10]);
1169
+ directiveStart = Date.now();
1145
1170
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1146
1171
  case 8:
1147
- directiveText = _p.sent();
1172
+ directiveText = _s.sent();
1173
+ timingBreakdown.directiveMs = Date.now() - directiveStart;
1148
1174
  forcedDirective = extractAssistantMongoDirective(directiveText);
1149
1175
  if (forcedDirective) {
1150
1176
  directive = forcedDirective;
1151
1177
  directiveSource = 'model';
1152
1178
  lastDirective = forcedDirective;
1179
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_h = directive.payload) === null || _h === void 0 ? void 0 : _h.collection) || '');
1153
1180
  recordStep('Directive resolved', {
1154
1181
  source: directiveSource,
1155
1182
  type: directive.type,
1156
- collection: normalizeOptionalString((_h = directive.payload) === null || _h === void 0 ? void 0 : _h.collection) || undefined,
1157
- permissionView: normalizeOptionalString((_j = directive.payload) === null || _j === void 0 ? void 0 : _j.permissionView) || undefined
1183
+ collection: normalizeOptionalString((_j = directive.payload) === null || _j === void 0 ? void 0 : _j.collection) || undefined,
1184
+ permissionView: normalizeOptionalString((_k = directive.payload) === null || _k === void 0 ? void 0 : _k.permissionView) || undefined
1158
1185
  });
1159
1186
  }
1160
1187
  return [3 /*break*/, 10];
1161
1188
  case 9:
1162
- _b = _p.sent();
1189
+ _b = _s.sent();
1163
1190
  return [3 /*break*/, 10];
1164
1191
  case 10:
1165
1192
  if (!!directive) return [3 /*break*/, 12];
1166
1193
  recordStep('Response: draft initial answer', { mode: 'full' });
1194
+ initialStart = Date.now();
1167
1195
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
1168
1196
  case 11:
1169
- responseText = _p.sent();
1197
+ responseText = _s.sent();
1198
+ timingBreakdown.initialResponseMs = Date.now() - initialStart;
1170
1199
  directive = extractAssistantMongoDirective(responseText);
1171
1200
  if (directive) {
1172
1201
  directiveSource = 'model';
1173
1202
  lastDirective = directive;
1203
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.collection) || '');
1174
1204
  recordStep('Directive resolved', {
1175
1205
  source: directiveSource,
1176
1206
  type: directive.type,
1177
- collection: normalizeOptionalString((_k = directive.payload) === null || _k === void 0 ? void 0 : _k.collection) || undefined,
1178
- permissionView: normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.permissionView) || undefined
1207
+ collection: normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1208
+ permissionView: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.permissionView) || undefined
1179
1209
  });
1180
1210
  }
1181
- _p.label = 12;
1211
+ _s.label = 12;
1182
1212
  case 12:
1183
1213
  if (!(!directive && dataQuestion)) return [3 /*break*/, 16];
1184
1214
  recordStep('Directive: forced retry', { mode: 'directive-only' });
1185
1215
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1186
- _p.label = 13;
1216
+ _s.label = 13;
1187
1217
  case 13:
1188
- _p.trys.push([13, 15, , 16]);
1218
+ _s.trys.push([13, 15, , 16]);
1219
+ forcedStart = Date.now();
1189
1220
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1190
1221
  case 14:
1191
- directiveText = _p.sent();
1222
+ directiveText = _s.sent();
1223
+ timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
1192
1224
  forcedDirective = extractAssistantMongoDirective(directiveText);
1193
1225
  if (forcedDirective) {
1194
1226
  directive = forcedDirective;
1195
1227
  directiveSource = 'forced';
1196
1228
  lastDirective = forcedDirective;
1229
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || '');
1197
1230
  recordStep('Directive resolved', {
1198
1231
  source: directiveSource,
1199
1232
  type: directive.type,
1200
- collection: normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1201
- permissionView: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.permissionView) || undefined
1233
+ collection: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || undefined,
1234
+ permissionView: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.permissionView) || undefined
1202
1235
  });
1203
1236
  }
1204
1237
  return [3 /*break*/, 16];
1205
1238
  case 15:
1206
- _c = _p.sent();
1239
+ _c = _s.sent();
1207
1240
  return [3 /*break*/, 16];
1208
1241
  case 16:
1209
1242
  cleanedResponseText = (directive === null || directive === void 0 ? void 0 : directive.cleaned) || responseText;
@@ -1218,20 +1251,22 @@ function executeAiAssistantCodexRun(payload, context) {
1218
1251
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
1219
1252
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
1220
1253
  });
1221
- _p.label = 17;
1254
+ _s.label = 17;
1222
1255
  case 17:
1223
- _p.trys.push([17, 26, , 27]);
1256
+ _s.trys.push([17, 26, , 27]);
1257
+ toolStart = Date.now();
1224
1258
  if (!(directive.type === 'aggregate')) return [3 /*break*/, 19];
1225
1259
  return [4 /*yield*/, executeAiAssistantMongoAggregate(toolRequest, context)];
1226
1260
  case 18:
1227
- _d = _p.sent();
1261
+ _d = _s.sent();
1228
1262
  return [3 /*break*/, 21];
1229
1263
  case 19: return [4 /*yield*/, executeAiAssistantMongoRead(toolRequest, context)];
1230
1264
  case 20:
1231
- _d = _p.sent();
1232
- _p.label = 21;
1265
+ _d = _s.sent();
1266
+ _s.label = 21;
1233
1267
  case 21:
1234
1268
  toolResponse = _d;
1269
+ timingBreakdown.toolMs = Date.now() - toolStart;
1235
1270
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
1236
1271
  ? toolResponse.debug
1237
1272
  : null;
@@ -1245,21 +1280,23 @@ function executeAiAssistantCodexRun(payload, context) {
1245
1280
  progressTracker.push('Drafting response');
1246
1281
  recordStep('Drafting response');
1247
1282
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
1248
- _p.label = 22;
1283
+ _s.label = 22;
1249
1284
  case 22:
1250
- _p.trys.push([22, 24, , 25]);
1285
+ _s.trys.push([22, 24, , 25]);
1286
+ followupStart = Date.now();
1251
1287
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
1252
1288
  case 23:
1253
- followupText = _p.sent();
1289
+ followupText = _s.sent();
1290
+ timingBreakdown.followupMs = Date.now() - followupStart;
1254
1291
  assistantContent = sanitizeAssistantResponse(followupText);
1255
1292
  return [3 /*break*/, 25];
1256
1293
  case 24:
1257
- _e = _p.sent();
1294
+ _e = _s.sent();
1258
1295
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
1259
1296
  return [3 /*break*/, 25];
1260
1297
  case 25: return [3 /*break*/, 27];
1261
1298
  case 26:
1262
- error_2 = _p.sent();
1299
+ error_2 = _s.sent();
1263
1300
  assistantContent = buildAssistantToolErrorMessage(error_2, directive, toolRequest);
1264
1301
  toolError = error_2;
1265
1302
  return [3 /*break*/, 27];
@@ -1267,10 +1304,10 @@ function executeAiAssistantCodexRun(payload, context) {
1267
1304
  case 28:
1268
1305
  progressTracker.push('Drafting response');
1269
1306
  recordStep('Drafting response');
1270
- _p.label = 29;
1307
+ _s.label = 29;
1271
1308
  case 29: return [3 /*break*/, 32];
1272
1309
  case 30:
1273
- error_3 = _p.sent();
1310
+ error_3 = _s.sent();
1274
1311
  assistantContent = buildAssistantCodexErrorMessage(error_3);
1275
1312
  recordStep('Error', { message: normalizeOptionalString(error_3 === null || error_3 === void 0 ? void 0 : error_3.message) || 'Unknown error' });
1276
1313
  return [3 /*break*/, 32];
@@ -1284,6 +1321,11 @@ function executeAiAssistantCodexRun(payload, context) {
1284
1321
  finalNow = new Date();
1285
1322
  if (isSuperAdmin) {
1286
1323
  finishedAt = Date.now();
1324
+ codexMs = timingBreakdown.directiveMs
1325
+ + timingBreakdown.initialResponseMs
1326
+ + timingBreakdown.forcedDirectiveMs
1327
+ + timingBreakdown.followupMs;
1328
+ draftingMs = timingBreakdown.followupMs || timingBreakdown.initialResponseMs;
1287
1329
  assistantDebug = buildAssistantDebugPayload({
1288
1330
  dataQuestion: dataQuestion,
1289
1331
  directive: lastDirective,
@@ -1297,12 +1339,22 @@ function executeAiAssistantCodexRun(payload, context) {
1297
1339
  contextMode: contextMode || undefined,
1298
1340
  contextRoute: contextRoute || undefined,
1299
1341
  termHints: termHints.length ? termHints : undefined,
1300
- collectionHints: collectionHints.length ? collectionHints : undefined
1342
+ collectionHints: collectionHints.length ? collectionHints : undefined,
1343
+ collectionTokenization: collectionTokenization || undefined,
1344
+ collectionRanking: collectionRanking || undefined,
1345
+ collectionSelection: collectionSelection || undefined
1301
1346
  },
1302
1347
  timings: {
1303
1348
  startedAt: new Date(runStart).toISOString(),
1304
1349
  finishedAt: new Date(finishedAt).toISOString(),
1305
- totalMs: finishedAt - runStart
1350
+ totalMs: finishedAt - runStart,
1351
+ codexMs: codexMs,
1352
+ draftingMs: draftingMs,
1353
+ toolMs: timingBreakdown.toolMs,
1354
+ directiveMs: timingBreakdown.directiveMs,
1355
+ initialResponseMs: timingBreakdown.initialResponseMs,
1356
+ forcedDirectiveMs: timingBreakdown.forcedDirectiveMs,
1357
+ followupMs: timingBreakdown.followupMs
1306
1358
  }
1307
1359
  }
1308
1360
  });
@@ -1318,16 +1370,16 @@ function executeAiAssistantCodexRun(payload, context) {
1318
1370
  }
1319
1371
  })];
1320
1372
  case 33:
1321
- _p.sent();
1322
- _p.label = 34;
1373
+ _s.sent();
1374
+ _s.label = 34;
1323
1375
  case 34: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
1324
1376
  case 35:
1325
- _p.sent();
1377
+ _s.sent();
1326
1378
  if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 37];
1327
1379
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
1328
1380
  case 36:
1329
- _p.sent();
1330
- _p.label = 37;
1381
+ _s.sent();
1382
+ _s.label = 37;
1331
1383
  case 37: return [2 /*return*/, finalAssistantDoc];
1332
1384
  }
1333
1385
  });
@@ -1341,7 +1393,7 @@ function executeAiAssistantCodexRun(payload, context) {
1341
1393
  }
1342
1394
  function executeAiAssistantMongoRead(payload, context) {
1343
1395
  return __awaiter(this, void 0, void 0, function () {
1344
- var input, rawCollection, dbName, db, collectionResolution, collection, _a, user, isSuperAdmin, customerId, baseQuery, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalized, findOptions, documents, executedQuery, fallbackMeta, dateFallback, fallbackQuery, fallbackDocs, total, sanitizedDocuments, includeIds, requestedFields, fieldAliases, displayDocs, priorityFields, display;
1396
+ var input, rawCollection, dbName, db, collectionResolution, collection, _a, user, isSuperAdmin, customerId, baseQuery, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalized, findOptions, documents, executedQuery, fallbackMeta, dateFallback, fallbackQuery, fallbackDocs, expanded, fallbackDocs, total, sanitizedDocuments, includeIds, requestedFields, fieldAliases, displayDocs, priorityFields, display;
1345
1397
  var _c, _d;
1346
1398
  return __generator(this, function (_e) {
1347
1399
  switch (_e.label) {
@@ -1396,7 +1448,7 @@ function executeAiAssistantMongoRead(payload, context) {
1396
1448
  documents = _e.sent();
1397
1449
  executedQuery = scopedQuery;
1398
1450
  fallbackMeta = {};
1399
- if (!!documents.length) return [3 /*break*/, 8];
1451
+ if (!!documents.length) return [3 /*break*/, 10];
1400
1452
  dateFallback = resolveQueryDateFieldFallback(scopedQuery);
1401
1453
  if (!dateFallback) return [3 /*break*/, 8];
1402
1454
  fallbackQuery = replaceQueryField(scopedQuery, dateFallback.from, dateFallback.to);
@@ -1411,13 +1463,31 @@ function executeAiAssistantMongoRead(payload, context) {
1411
1463
  }
1412
1464
  _e.label = 8;
1413
1465
  case 8:
1414
- total = null;
1415
- if (!normalized.includeTotal) return [3 /*break*/, 10];
1416
- return [4 /*yield*/, db.collection(collection).countDocuments(executedQuery, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
1466
+ if (!!documents.length) return [3 /*break*/, 10];
1467
+ expanded = expandQueryDateFallbacks(scopedQuery);
1468
+ if (!expanded) return [3 /*break*/, 10];
1469
+ fallbackMeta.dateFieldsExpanded = {
1470
+ fields: expanded.fields,
1471
+ attempted: true,
1472
+ used: false
1473
+ };
1474
+ return [4 /*yield*/, db.collection(collection).find(expanded.query, findOptions).toArray()];
1417
1475
  case 9:
1418
- total = _e.sent();
1476
+ fallbackDocs = _e.sent();
1477
+ if (fallbackDocs.length) {
1478
+ documents = fallbackDocs;
1479
+ executedQuery = expanded.query;
1480
+ fallbackMeta.dateFieldsExpanded.used = true;
1481
+ }
1419
1482
  _e.label = 10;
1420
1483
  case 10:
1484
+ total = null;
1485
+ if (!normalized.includeTotal) return [3 /*break*/, 12];
1486
+ return [4 /*yield*/, db.collection(collection).countDocuments(executedQuery, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
1487
+ case 11:
1488
+ total = _e.sent();
1489
+ _e.label = 12;
1490
+ case 12:
1421
1491
  sanitizedDocuments = isSuperAdmin
1422
1492
  ? documents
1423
1493
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
@@ -1433,7 +1503,8 @@ function executeAiAssistantMongoRead(payload, context) {
1433
1503
  includeIds: includeIds,
1434
1504
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
1435
1505
  maxRows: normalized.findOptions.limit,
1436
- priorityFields: priorityFields
1506
+ priorityFields: priorityFields,
1507
+ includeGroupFromId: false
1437
1508
  });
1438
1509
  if (total !== null) {
1439
1510
  display.total = total;
@@ -1462,7 +1533,7 @@ function executeAiAssistantMongoRead(payload, context) {
1462
1533
  }
1463
1534
  function executeAiAssistantMongoAggregate(payload, context) {
1464
1535
  return __awaiter(this, void 0, void 0, function () {
1465
- var input, rawCollection, dbName, db, collectionResolution, collection, _a, user, isSuperAdmin, customerId, baseQuery, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, dateField, aggregateOptions, documents, executedPipeline, fallbackMeta, fallback, fallbackPipeline, fallbackDocs, createdFallback, createdPipeline, createdDocs, completionFallback, fallbackPipeline, fallbackDocs, unwindFallback, fallbackPipeline, fallbackDocs, sanitizedDocuments, includeIds, display;
1536
+ var input, rawCollection, dbName, db, collectionResolution, collection, _a, user, isSuperAdmin, customerId, baseQuery, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, dateField, aggregateOptions, documents, executedPipeline, fallbackMeta, fallback, fallbackPipeline, fallbackDocs, createdFallback, createdPipeline, createdDocs, completionFallback, fallbackPipeline, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackDocs, unwindFallback, fallbackPipeline, fallbackDocs, nameFallback, fallbackPipeline, fallbackDocs, sanitizedDocuments, includeIds, display;
1466
1537
  var _c, _d;
1467
1538
  return __generator(this, function (_e) {
1468
1539
  switch (_e.label) {
@@ -1561,7 +1632,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
1561
1632
  }
1562
1633
  _e.label = 10;
1563
1634
  case 10:
1564
- if (!!documents.length) return [3 /*break*/, 12];
1635
+ if (!!documents.length) return [3 /*break*/, 14];
1565
1636
  completionFallback = resolveAggregateCompletionFallback(executedPipeline);
1566
1637
  if (!completionFallback) return [3 /*break*/, 12];
1567
1638
  fallbackMeta.completion = {
@@ -1569,7 +1640,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
1569
1640
  sources: completionFallback.sources,
1570
1641
  attempted: true,
1571
1642
  used: false,
1572
- statusFilter: !!completionFallback.statusFilter
1643
+ statusFilter: !!completionFallback.statusFilter,
1644
+ strategy: 'addFields'
1573
1645
  };
1574
1646
  fallbackPipeline = buildAggregateCompletionFallbackPipeline(executedPipeline, completionFallback);
1575
1647
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 12];
@@ -1585,24 +1657,72 @@ function executeAiAssistantMongoAggregate(payload, context) {
1585
1657
  }
1586
1658
  _e.label = 12;
1587
1659
  case 12:
1588
- if (!(documents.length <= 1)) return [3 /*break*/, 14];
1660
+ if (!!documents.length) return [3 /*break*/, 14];
1661
+ completionExprFallback = resolveAggregateCompletionExprFallback(executedPipeline);
1662
+ if (!completionExprFallback) return [3 /*break*/, 14];
1663
+ fallbackMeta.completion = {
1664
+ field: completionExprFallback.field,
1665
+ sources: completionExprFallback.sources,
1666
+ attempted: true,
1667
+ used: false,
1668
+ statusFilter: !!completionExprFallback.statusFilter,
1669
+ strategy: 'expr'
1670
+ };
1671
+ fallbackPipeline = buildAggregateCompletionExprFallbackPipeline(executedPipeline, completionExprFallback);
1672
+ if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 14];
1673
+ return [4 /*yield*/, db.collection(collection)
1674
+ .aggregate(fallbackPipeline, aggregateOptions)
1675
+ .toArray()];
1676
+ case 13:
1677
+ fallbackDocs = _e.sent();
1678
+ if (fallbackDocs.length) {
1679
+ documents = fallbackDocs;
1680
+ executedPipeline = fallbackPipeline;
1681
+ fallbackMeta.completion.used = true;
1682
+ }
1683
+ _e.label = 14;
1684
+ case 14:
1685
+ if (!(documents.length <= 1)) return [3 /*break*/, 16];
1589
1686
  unwindFallback = resolveAggregateUnwindFallback(executedPipeline);
1590
- if (!unwindFallback) return [3 /*break*/, 14];
1687
+ if (!unwindFallback) return [3 /*break*/, 16];
1591
1688
  fallbackMeta.unwind = { path: unwindFallback.path, attempted: true, used: false };
1592
1689
  fallbackPipeline = buildAggregateUnwindFallbackPipeline(executedPipeline, unwindFallback);
1593
- if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 14];
1690
+ if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 16];
1594
1691
  return [4 /*yield*/, db.collection(collection)
1595
1692
  .aggregate(fallbackPipeline, aggregateOptions)
1596
1693
  .toArray()];
1597
- case 13:
1694
+ case 15:
1598
1695
  fallbackDocs = _e.sent();
1599
1696
  if (fallbackDocs.length > documents.length) {
1600
1697
  documents = fallbackDocs;
1601
1698
  executedPipeline = fallbackPipeline;
1602
1699
  fallbackMeta.unwind.used = true;
1603
1700
  }
1604
- _e.label = 14;
1605
- case 14:
1701
+ _e.label = 16;
1702
+ case 16:
1703
+ if (!!documents.length) return [3 /*break*/, 18];
1704
+ nameFallback = resolveAggregateNameMatchFallback(executedPipeline);
1705
+ if (!nameFallback) return [3 /*break*/, 18];
1706
+ fallbackMeta.nameMatch = {
1707
+ field: nameFallback.field,
1708
+ fields: nameFallback.fields,
1709
+ attempted: true,
1710
+ used: false
1711
+ };
1712
+ fallbackPipeline = buildAggregateNameMatchFallbackPipeline(executedPipeline, nameFallback);
1713
+ if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 18];
1714
+ return [4 /*yield*/, db.collection(collection)
1715
+ .aggregate(fallbackPipeline, aggregateOptions)
1716
+ .toArray()];
1717
+ case 17:
1718
+ fallbackDocs = _e.sent();
1719
+ if (fallbackDocs.length) {
1720
+ documents = fallbackDocs;
1721
+ executedPipeline = fallbackPipeline;
1722
+ fallbackMeta.nameMatch.used = true;
1723
+ }
1724
+ _e.label = 18;
1725
+ case 18:
1606
1726
  sanitizedDocuments = isSuperAdmin
1607
1727
  ? documents
1608
1728
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
@@ -1610,7 +1730,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
1610
1730
  display = buildDisplayTable(sanitizedDocuments, {
1611
1731
  includeIds: includeIds,
1612
1732
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
1613
- maxRows: normalizedOptions.limit || sanitizedDocuments.length
1733
+ maxRows: normalizedOptions.limit || sanitizedDocuments.length,
1734
+ includeGroupFromId: true
1614
1735
  });
1615
1736
  return [2 /*return*/, __assign({ documents: sanitizedDocuments, display: display }, (isSuperAdmin ? {
1616
1737
  debug: {
@@ -1699,7 +1820,8 @@ function buildAssistantToolResultPayload(directive, toolResponse) {
1699
1820
  : buildDisplayTable(documents, {
1700
1821
  includeIds: includeIds,
1701
1822
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
1702
- maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS
1823
+ maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS,
1824
+ includeGroupFromId: directive.type === 'aggregate'
1703
1825
  });
1704
1826
  var trimmedDisplay = trimDisplayTable(display, {
1705
1827
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
@@ -1779,7 +1901,7 @@ function buildAssistantToolFallbackResponse(result) {
1779
1901
  return lines.join('\n').trim();
1780
1902
  }
1781
1903
  function buildAssistantDebugPayload(params) {
1782
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
1904
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1783
1905
  var notes = [];
1784
1906
  if (params.dataQuestion) {
1785
1907
  notes.push('Detected a data request; tool call required.');
@@ -1820,11 +1942,32 @@ function buildAssistantDebugPayload(params) {
1820
1942
  if ((_k = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.dateFieldCreatedAt) === null || _k === void 0 ? void 0 : _k.used) {
1821
1943
  notes.push("Retried with date field fallback ".concat(fallbackInfo.dateFieldCreatedAt.from, " -> ").concat(fallbackInfo.dateFieldCreatedAt.to, "."));
1822
1944
  }
1823
- if ((_l = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.unwind) === null || _l === void 0 ? void 0 : _l.used) {
1945
+ if ((_l = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.completion) === null || _l === void 0 ? void 0 : _l.used) {
1946
+ var sources = Array.isArray(fallbackInfo.completion.sources)
1947
+ ? fallbackInfo.completion.sources.join(', ')
1948
+ : fallbackInfo.completion.field;
1949
+ var strategy = fallbackInfo.completion.strategy ? " (".concat(fallbackInfo.completion.strategy, ")") : '';
1950
+ notes.push("Applied completion fallback".concat(strategy, ": ").concat(sources, "."));
1951
+ }
1952
+ if ((_m = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.dateFieldsExpanded) === null || _m === void 0 ? void 0 : _m.used) {
1953
+ var fields = Array.isArray(fallbackInfo.dateFieldsExpanded.fields)
1954
+ ? fallbackInfo.dateFieldsExpanded.fields.join(', ')
1955
+ : String(fallbackInfo.dateFieldsExpanded.fields || '');
1956
+ if (fields) {
1957
+ notes.push("Expanded date fields: ".concat(fields, "."));
1958
+ }
1959
+ }
1960
+ if ((_o = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.unwind) === null || _o === void 0 ? void 0 : _o.used) {
1824
1961
  notes.push("Applied unwind fallback on ".concat(fallbackInfo.unwind.path, "."));
1825
1962
  }
1963
+ if ((_p = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.nameMatch) === null || _p === void 0 ? void 0 : _p.used) {
1964
+ var fields = Array.isArray(fallbackInfo.nameMatch.fields)
1965
+ ? fallbackInfo.nameMatch.fields.join(', ')
1966
+ : fallbackInfo.nameMatch.field;
1967
+ notes.push("Expanded name match fields: ".concat(fields, "."));
1968
+ }
1826
1969
  if (params.toolError) {
1827
- var errorMessage = ((_m = params.toolError) === null || _m === void 0 ? void 0 : _m.message) || String(params.toolError || '');
1970
+ var errorMessage = ((_q = params.toolError) === null || _q === void 0 ? void 0 : _q.message) || String(params.toolError || '');
1828
1971
  if (errorMessage) {
1829
1972
  notes.push("Tool error: ".concat(errorMessage));
1830
1973
  }
@@ -1844,13 +1987,13 @@ function buildAssistantDebugPayload(params) {
1844
1987
  collectionResolved: resolvedCollection || undefined,
1845
1988
  collectionMatched: matchedCollection,
1846
1989
  collectionCandidates: candidateCollections.length ? candidateCollections : undefined,
1847
- collectionScore: typeof ((_o = params.toolResponseDebug) === null || _o === void 0 ? void 0 : _o.collectionScore) === 'number'
1990
+ collectionScore: typeof ((_r = params.toolResponseDebug) === null || _r === void 0 ? void 0 : _r.collectionScore) === 'number'
1848
1991
  ? params.toolResponseDebug.collectionScore
1849
1992
  : undefined,
1850
- query: ((_p = params.toolResponseDebug) === null || _p === void 0 ? void 0 : _p.query) || undefined,
1851
- pipeline: ((_q = params.toolResponseDebug) === null || _q === void 0 ? void 0 : _q.executedPipeline) || ((_r = params.toolResponseDebug) === null || _r === void 0 ? void 0 : _r.originalPipeline) || undefined,
1852
- options: ((_s = params.toolResponseDebug) === null || _s === void 0 ? void 0 : _s.options) || undefined,
1853
- fallbacks: ((_t = params.toolResponseDebug) === null || _t === void 0 ? void 0 : _t.fallbacks) || undefined,
1993
+ query: ((_s = params.toolResponseDebug) === null || _s === void 0 ? void 0 : _s.query) || undefined,
1994
+ pipeline: ((_t = params.toolResponseDebug) === null || _t === void 0 ? void 0 : _t.executedPipeline) || ((_u = params.toolResponseDebug) === null || _u === void 0 ? void 0 : _u.originalPipeline) || undefined,
1995
+ options: ((_v = params.toolResponseDebug) === null || _v === void 0 ? void 0 : _v.options) || undefined,
1996
+ fallbacks: ((_w = params.toolResponseDebug) === null || _w === void 0 ? void 0 : _w.fallbacks) || undefined,
1854
1997
  notes: notes
1855
1998
  };
1856
1999
  if (params.trace && typeof params.trace === 'object') {
@@ -2415,14 +2558,17 @@ function serializeMongoValue(value, maxLength) {
2415
2558
  }
2416
2559
  return truncateDisplayText(String(value), maxLength);
2417
2560
  }
2418
- function flattenForTable(doc) {
2561
+ function flattenForTable(doc, options) {
2419
2562
  var result = {};
2420
2563
  if (!doc || typeof doc !== 'object') {
2421
2564
  return result;
2422
2565
  }
2423
2566
  if (Object.prototype.hasOwnProperty.call(doc, '_id')) {
2424
2567
  var idValue_1 = doc._id;
2425
- if (idValue_1 !== null && idValue_1 !== undefined) {
2568
+ if (options === null || options === void 0 ? void 0 : options.includeIds) {
2569
+ result._id = idValue_1;
2570
+ }
2571
+ if ((options === null || options === void 0 ? void 0 : options.includeGroupFromId) && idValue_1 !== null && idValue_1 !== undefined) {
2426
2572
  if (isPlainObject(idValue_1) && !isMongoObjectId(idValue_1) && !(idValue_1 instanceof Date)) {
2427
2573
  Object.keys(idValue_1).forEach(function (key) {
2428
2574
  if (!key || Object.prototype.hasOwnProperty.call(result, key)) {
@@ -2465,7 +2611,12 @@ function flattenForTable(doc) {
2465
2611
  return result;
2466
2612
  }
2467
2613
  function buildDisplayTable(docs, options) {
2468
- var rowsRaw = Array.isArray(docs) ? docs.map(function (doc) { return flattenForTable(doc); }) : [];
2614
+ var rowsRaw = Array.isArray(docs)
2615
+ ? docs.map(function (doc) { return flattenForTable(doc, {
2616
+ includeIds: (options === null || options === void 0 ? void 0 : options.includeIds) === true,
2617
+ includeGroupFromId: (options === null || options === void 0 ? void 0 : options.includeGroupFromId) === true
2618
+ }); })
2619
+ : [];
2469
2620
  var stats = new Map();
2470
2621
  rowsRaw.forEach(function (row) {
2471
2622
  Object.keys(row).forEach(function (key) {
@@ -2821,7 +2972,8 @@ function normalizeAggregateFieldList(values) {
2821
2972
  return result;
2822
2973
  }
2823
2974
  function isCompletionFieldName(value) {
2824
- return String(value || '').toLowerCase().includes('complete');
2975
+ var normalized = String(value || '').toLowerCase();
2976
+ return normalized.includes('complete') || normalized.includes('close');
2825
2977
  }
2826
2978
  function isDateLikeFieldName(value) {
2827
2979
  var normalized = String(value || '').toLowerCase();
@@ -2926,18 +3078,18 @@ function resolveAggregateCompletionFallback(pipeline) {
2926
3078
  statusFilter: statusFilter
2927
3079
  };
2928
3080
  }
3081
+ function buildIfNullChain(fields) {
3082
+ if (!fields.length) {
3083
+ return null;
3084
+ }
3085
+ var expr = "$".concat(fields[fields.length - 1]);
3086
+ for (var i = fields.length - 2; i >= 0; i -= 1) {
3087
+ expr = { $ifNull: ["$".concat(fields[i]), expr] };
3088
+ }
3089
+ return expr;
3090
+ }
2929
3091
  function buildAggregateCompletionFallbackPipeline(pipeline, fallback) {
2930
3092
  var _a;
2931
- var buildIfNullChain = function (fields) {
2932
- if (!fields.length) {
2933
- return null;
2934
- }
2935
- var expr = "$".concat(fields[fields.length - 1]);
2936
- for (var i = fields.length - 2; i >= 0; i -= 1) {
2937
- expr = { $ifNull: ["$".concat(fields[i]), expr] };
2938
- }
2939
- return expr;
2940
- };
2941
3093
  var matchStage = (_a = pipeline[fallback.matchIndex]) === null || _a === void 0 ? void 0 : _a.$match;
2942
3094
  if (!matchStage || typeof matchStage !== 'object') {
2943
3095
  return pipeline;
@@ -2970,6 +3122,163 @@ function buildAggregateCompletionFallbackPipeline(pipeline, fallback) {
2970
3122
  return stage;
2971
3123
  });
2972
3124
  }
3125
+ function normalizeCompletionStatusValue(value) {
3126
+ var normalized = String(value || '').toLowerCase();
3127
+ if (!normalized) {
3128
+ return null;
3129
+ }
3130
+ if (normalized.includes('complete')) {
3131
+ return 'complete';
3132
+ }
3133
+ if (normalized.includes('close')) {
3134
+ return 'close';
3135
+ }
3136
+ return null;
3137
+ }
3138
+ function applyCompletionStatusRegexFallback(match) {
3139
+ if (Array.isArray(match)) {
3140
+ return match.map(function (entry) { return applyCompletionStatusRegexFallback(entry); });
3141
+ }
3142
+ if (!match || typeof match !== 'object') {
3143
+ return match;
3144
+ }
3145
+ var result = {};
3146
+ Object.keys(match).forEach(function (key) {
3147
+ var value = match[key];
3148
+ if (key === 'status' || key === 'state') {
3149
+ if (typeof value === 'string') {
3150
+ var token = normalizeCompletionStatusValue(value);
3151
+ if (token) {
3152
+ result[key] = { $regex: token, $options: 'i' };
3153
+ return;
3154
+ }
3155
+ }
3156
+ result[key] = value;
3157
+ return;
3158
+ }
3159
+ if (key.startsWith('$')) {
3160
+ result[key] = applyCompletionStatusRegexFallback(value);
3161
+ return;
3162
+ }
3163
+ if (value && typeof value === 'object') {
3164
+ result[key] = applyCompletionStatusRegexFallback(value);
3165
+ return;
3166
+ }
3167
+ result[key] = value;
3168
+ });
3169
+ return result;
3170
+ }
3171
+ function buildCompletionFallbackSources(field) {
3172
+ return normalizeAggregateFieldList([
3173
+ field,
3174
+ 'date_completed',
3175
+ 'date_closed',
3176
+ 'completedAt',
3177
+ 'closedAt',
3178
+ 'completed_at',
3179
+ 'closed_at',
3180
+ 'date_completed_at',
3181
+ 'date_closed_at',
3182
+ 'completion_date',
3183
+ 'completed_date',
3184
+ 'date_finished',
3185
+ 'finished_at',
3186
+ 'createdAt',
3187
+ 'date_created'
3188
+ ]);
3189
+ }
3190
+ function resolveAggregateCompletionExprFallback(pipeline) {
3191
+ var e_4, _a;
3192
+ if (!Array.isArray(pipeline)) {
3193
+ return null;
3194
+ }
3195
+ for (var i = 0; i < pipeline.length; i += 1) {
3196
+ var stage = pipeline[i];
3197
+ if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
3198
+ continue;
3199
+ }
3200
+ var matchStage = stage.$match;
3201
+ var candidateField = '';
3202
+ if (matchStage.$expr) {
3203
+ var exprFields = extractExpressionFieldPaths(matchStage.$expr)
3204
+ .filter(function (field) { return isCompletionFieldName(field); });
3205
+ if (exprFields.length) {
3206
+ candidateField = exprFields[0];
3207
+ }
3208
+ }
3209
+ if (!candidateField) {
3210
+ try {
3211
+ for (var _b = (e_4 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
3212
+ var key = _c.value;
3213
+ if (key.startsWith('$')) {
3214
+ continue;
3215
+ }
3216
+ if (!isCompletionFieldName(key)) {
3217
+ continue;
3218
+ }
3219
+ var entry = matchStage[key];
3220
+ if (hasDateRangeOperators(entry) || entry instanceof Date) {
3221
+ candidateField = key;
3222
+ break;
3223
+ }
3224
+ }
3225
+ }
3226
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
3227
+ finally {
3228
+ try {
3229
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3230
+ }
3231
+ finally { if (e_4) throw e_4.error; }
3232
+ }
3233
+ }
3234
+ if (!candidateField) {
3235
+ continue;
3236
+ }
3237
+ var sources = buildCompletionFallbackSources(candidateField);
3238
+ if (!sources.length) {
3239
+ return null;
3240
+ }
3241
+ var hasStatus = matchContainsField(matchStage, 'status') || matchContainsField(matchStage, 'state');
3242
+ var statusFilter = !hasStatus
3243
+ ? { $or: [{ status: { $regex: 'complete', $options: 'i' } }, { state: { $regex: 'complete', $options: 'i' } }] }
3244
+ : null;
3245
+ return {
3246
+ matchIndex: i,
3247
+ field: candidateField,
3248
+ sources: sources,
3249
+ statusFilter: statusFilter
3250
+ };
3251
+ }
3252
+ return null;
3253
+ }
3254
+ function buildAggregateCompletionExprFallbackPipeline(pipeline, fallback) {
3255
+ var _a;
3256
+ var _b;
3257
+ var targetField = 'completed_at_effective';
3258
+ var replacedPipeline = replaceAggregateDateField(pipeline, fallback.field, targetField);
3259
+ var matchStage = (_b = replacedPipeline[fallback.matchIndex]) === null || _b === void 0 ? void 0 : _b.$match;
3260
+ if (!matchStage || typeof matchStage !== 'object') {
3261
+ return replacedPipeline;
3262
+ }
3263
+ var baseMatch = applyCompletionStatusRegexFallback(matchStage);
3264
+ var nextMatch = fallback.statusFilter ? { $and: [baseMatch, fallback.statusFilter] } : baseMatch;
3265
+ var addFieldsStage = { $addFields: (_a = {}, _a[targetField] = buildIfNullChain(fallback.sources), _a) };
3266
+ var alreadyHasField = replacedPipeline
3267
+ .slice(0, fallback.matchIndex)
3268
+ .some(function (stage) { return stage && typeof stage === 'object' && stage.$addFields && Object.prototype.hasOwnProperty.call(stage.$addFields, targetField); });
3269
+ var output = [];
3270
+ replacedPipeline.forEach(function (stage, index) {
3271
+ if (index === fallback.matchIndex) {
3272
+ if (!alreadyHasField) {
3273
+ output.push(addFieldsStage);
3274
+ }
3275
+ output.push({ $match: nextMatch });
3276
+ return;
3277
+ }
3278
+ output.push(stage);
3279
+ });
3280
+ return output;
3281
+ }
2973
3282
  function resolveAggregateUnwindFallback(pipeline) {
2974
3283
  var groupIndex = findAggregateGroupIndex(pipeline);
2975
3284
  if (groupIndex === -1) {
@@ -3076,6 +3385,253 @@ function buildAggregateUnwindFallbackPipeline(pipeline, fallback) {
3076
3385
  };
3077
3386
  return __spreadArray(__spreadArray(__spreadArray([], __read(before), false), [unwindStage], false), __read(after), false);
3078
3387
  }
3388
+ function isRegexMatchCondition(value) {
3389
+ if (!value) {
3390
+ return false;
3391
+ }
3392
+ if (value instanceof RegExp) {
3393
+ return true;
3394
+ }
3395
+ if (typeof value === 'object' && !Array.isArray(value)) {
3396
+ return Object.prototype.hasOwnProperty.call(value, '$regex');
3397
+ }
3398
+ return false;
3399
+ }
3400
+ function findRegexMatchInMatchObject(match, prefix) {
3401
+ var e_5, _a, e_6, _b;
3402
+ if (prefix === void 0) { prefix = ''; }
3403
+ if (Array.isArray(match)) {
3404
+ try {
3405
+ for (var match_1 = __values(match), match_1_1 = match_1.next(); !match_1_1.done; match_1_1 = match_1.next()) {
3406
+ var entry = match_1_1.value;
3407
+ var found = findRegexMatchInMatchObject(entry, prefix);
3408
+ if (found) {
3409
+ return found;
3410
+ }
3411
+ }
3412
+ }
3413
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
3414
+ finally {
3415
+ try {
3416
+ if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
3417
+ }
3418
+ finally { if (e_5) throw e_5.error; }
3419
+ }
3420
+ return null;
3421
+ }
3422
+ if (!match || typeof match !== 'object') {
3423
+ return null;
3424
+ }
3425
+ var keys = Object.keys(match);
3426
+ try {
3427
+ for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
3428
+ var key = keys_1_1.value;
3429
+ var value = match[key];
3430
+ if (key.startsWith('$')) {
3431
+ var found = findRegexMatchInMatchObject(value, prefix);
3432
+ if (found) {
3433
+ return found;
3434
+ }
3435
+ continue;
3436
+ }
3437
+ var currentPath = prefix ? "".concat(prefix, ".").concat(key) : key;
3438
+ if (isRegexMatchCondition(value)) {
3439
+ return { field: currentPath, condition: value };
3440
+ }
3441
+ if (value && typeof value === 'object') {
3442
+ var found = findRegexMatchInMatchObject(value, currentPath);
3443
+ if (found) {
3444
+ return found;
3445
+ }
3446
+ }
3447
+ }
3448
+ }
3449
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
3450
+ finally {
3451
+ try {
3452
+ if (keys_1_1 && !keys_1_1.done && (_b = keys_1.return)) _b.call(keys_1);
3453
+ }
3454
+ finally { if (e_6) throw e_6.error; }
3455
+ }
3456
+ return null;
3457
+ }
3458
+ function expandNameFieldCandidates(field) {
3459
+ var normalized = normalizeOptionalString(field);
3460
+ if (!normalized) {
3461
+ return [];
3462
+ }
3463
+ var parts = normalized.split('.').filter(Boolean);
3464
+ var leaf = parts[parts.length - 1] || normalized;
3465
+ var prefix = parts.length > 1 ? parts.slice(0, -1).join('.') : '';
3466
+ var withPrefix = function (value) { return (prefix ? "".concat(prefix, ".").concat(value) : value); };
3467
+ var candidates = [];
3468
+ var seen = new Set();
3469
+ var push = function (value) {
3470
+ if (!value) {
3471
+ return;
3472
+ }
3473
+ if (seen.has(value)) {
3474
+ return;
3475
+ }
3476
+ seen.add(value);
3477
+ candidates.push(value);
3478
+ };
3479
+ push(normalized);
3480
+ var leafLower = leaf.toLowerCase();
3481
+ var genericVariants = ['name', 'title', 'label', 'display_name', 'displayName', 'description'];
3482
+ genericVariants.forEach(function (variant) { return push(withPrefix(variant)); });
3483
+ if (!leafLower.endsWith('name')) {
3484
+ push(withPrefix("".concat(leaf, "_name")));
3485
+ push(withPrefix("".concat(leaf, "Name")));
3486
+ }
3487
+ if (leafLower.includes('chemical')) {
3488
+ [
3489
+ 'chemical',
3490
+ 'chemical_name',
3491
+ 'chemicalName',
3492
+ 'chem_name',
3493
+ 'chemName',
3494
+ 'product',
3495
+ 'product_name',
3496
+ 'productName',
3497
+ 'material',
3498
+ 'blend_name'
3499
+ ].forEach(function (variant) { return push(withPrefix(variant)); });
3500
+ push(withPrefix("".concat(leaf, ".name")));
3501
+ push(withPrefix("".concat(leaf, ".label")));
3502
+ push(withPrefix("".concat(leaf, ".product")));
3503
+ }
3504
+ if (leafLower.includes('customer')) {
3505
+ [
3506
+ 'customer',
3507
+ 'customer_name',
3508
+ 'customerName',
3509
+ 'company',
3510
+ 'company_name',
3511
+ 'companyName',
3512
+ 'account',
3513
+ 'account_name',
3514
+ 'accountName',
3515
+ 'name'
3516
+ ].forEach(function (variant) { return push(withPrefix(variant)); });
3517
+ push(withPrefix("".concat(leaf, ".name")));
3518
+ }
3519
+ if (leafLower.includes('well')) {
3520
+ [
3521
+ 'well',
3522
+ 'well_name',
3523
+ 'wellName',
3524
+ 'name',
3525
+ 'site',
3526
+ 'site_name',
3527
+ 'siteName',
3528
+ 'pad',
3529
+ 'pad_name',
3530
+ 'padName',
3531
+ 'api',
3532
+ 'api_number',
3533
+ 'apiNumber',
3534
+ 'well_number',
3535
+ 'wellNumber'
3536
+ ].forEach(function (variant) { return push(withPrefix(variant)); });
3537
+ push(withPrefix("".concat(leaf, ".name")));
3538
+ }
3539
+ return candidates.slice(0, AI_ASSISTANT_NAME_MATCH_FALLBACK_MAX_FIELDS);
3540
+ }
3541
+ function resolveAggregateNameMatchFallback(pipeline) {
3542
+ if (!Array.isArray(pipeline)) {
3543
+ return null;
3544
+ }
3545
+ for (var i = 0; i < pipeline.length; i += 1) {
3546
+ var stage = pipeline[i];
3547
+ if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
3548
+ continue;
3549
+ }
3550
+ var found = findRegexMatchInMatchObject(stage.$match);
3551
+ if (!found || !shouldApplyAssistantNameRegex(found.field)) {
3552
+ continue;
3553
+ }
3554
+ var fields = expandNameFieldCandidates(found.field);
3555
+ if (fields.length <= 1) {
3556
+ continue;
3557
+ }
3558
+ return {
3559
+ matchIndex: i,
3560
+ field: found.field,
3561
+ condition: found.condition,
3562
+ fields: fields
3563
+ };
3564
+ }
3565
+ return null;
3566
+ }
3567
+ function isEmptyMatchValue(value) {
3568
+ if (value === null || value === undefined) {
3569
+ return true;
3570
+ }
3571
+ if (Array.isArray(value)) {
3572
+ return value.length === 0;
3573
+ }
3574
+ if (typeof value === 'object') {
3575
+ return Object.keys(value).length === 0;
3576
+ }
3577
+ return false;
3578
+ }
3579
+ function stripMatchField(match, field) {
3580
+ if (Array.isArray(match)) {
3581
+ var strippedArray = match
3582
+ .map(function (entry) { return stripMatchField(entry, field); })
3583
+ .filter(function (entry) { return !isEmptyMatchValue(entry); });
3584
+ return strippedArray;
3585
+ }
3586
+ if (!match || typeof match !== 'object') {
3587
+ return match;
3588
+ }
3589
+ var result = {};
3590
+ Object.keys(match).forEach(function (key) {
3591
+ if (key === field) {
3592
+ return;
3593
+ }
3594
+ var value = match[key];
3595
+ if (key.startsWith('$')) {
3596
+ var stripped = stripMatchField(value, field);
3597
+ if (isEmptyMatchValue(stripped) && (key === '$and' || key === '$or')) {
3598
+ return;
3599
+ }
3600
+ result[key] = stripped;
3601
+ return;
3602
+ }
3603
+ if (value && typeof value === 'object') {
3604
+ var stripped = stripMatchField(value, field);
3605
+ if (!isEmptyMatchValue(stripped)) {
3606
+ result[key] = stripped;
3607
+ }
3608
+ return;
3609
+ }
3610
+ result[key] = value;
3611
+ });
3612
+ return result;
3613
+ }
3614
+ function buildAggregateNameMatchFallbackPipeline(pipeline, fallback) {
3615
+ var _a;
3616
+ var matchStage = (_a = pipeline[fallback.matchIndex]) === null || _a === void 0 ? void 0 : _a.$match;
3617
+ if (!matchStage || typeof matchStage !== 'object') {
3618
+ return pipeline;
3619
+ }
3620
+ var baseMatch = stripMatchField(matchStage, fallback.field);
3621
+ var orConditions = fallback.fields.map(function (field) {
3622
+ var _a;
3623
+ return (_a = {}, _a[field] = fallback.condition, _a);
3624
+ });
3625
+ var nextMatch = isEmptyMatchValue(baseMatch)
3626
+ ? { $or: orConditions }
3627
+ : { $and: [baseMatch, { $or: orConditions }] };
3628
+ return pipeline.map(function (stage, index) {
3629
+ if (index === fallback.matchIndex) {
3630
+ return { $match: nextMatch };
3631
+ }
3632
+ return stage;
3633
+ });
3634
+ }
3079
3635
  function findAggregateDateField(pipeline) {
3080
3636
  var fields = new Set();
3081
3637
  (pipeline || []).forEach(function (stage) {
@@ -3323,6 +3879,75 @@ function scoreCollectionMatch(requestedTokens, candidateName) {
3323
3879
  }
3324
3880
  return score;
3325
3881
  }
3882
+ function scoreCollectionMatchDetailed(requestedTokens, candidateName) {
3883
+ var candidateTokens = tokenizeCollectionText(candidateName);
3884
+ var tokenMatches = requestedTokens.filter(function (token) { return candidateTokens.includes(token); });
3885
+ var score = tokenMatches.length * 10;
3886
+ var requestedKey = normalizeCollectionKey(requestedTokens.join('-'));
3887
+ var candidateKey = normalizeCollectionKey(candidateName);
3888
+ var keyMatch = null;
3889
+ if (candidateKey === requestedKey && requestedKey) {
3890
+ score += 50;
3891
+ keyMatch = 'exact';
3892
+ }
3893
+ else if (requestedKey && (candidateKey.includes(requestedKey) || requestedKey.includes(candidateKey))) {
3894
+ score += 20;
3895
+ keyMatch = 'partial';
3896
+ }
3897
+ return {
3898
+ score: score,
3899
+ tokenMatches: tokenMatches,
3900
+ keyMatch: keyMatch,
3901
+ candidateTokens: candidateTokens
3902
+ };
3903
+ }
3904
+ function resolveCollectionHintsFromTokens(tokens, collectionNames, max) {
3905
+ if (max === void 0) { max = 5; }
3906
+ if (!tokens.length || !collectionNames.length) {
3907
+ return [];
3908
+ }
3909
+ return collectionNames
3910
+ .map(function (name) { return ({ name: name, score: scoreCollectionMatch(tokens, name) }); })
3911
+ .filter(function (entry) { return entry.score > 0; })
3912
+ .sort(function (a, b) { return b.score - a.score; })
3913
+ .slice(0, Math.max(max, 0))
3914
+ .map(function (entry) { return entry.name; });
3915
+ }
3916
+ function buildCollectionRankingDebugFromTokens(tokens, collectionNames, max) {
3917
+ if (max === void 0) { max = 8; }
3918
+ var requestedKey = normalizeCollectionKey(tokens.join('-'));
3919
+ if (!tokens.length || !collectionNames.length) {
3920
+ return {
3921
+ tokens: tokens,
3922
+ requestedKey: requestedKey,
3923
+ ranked: []
3924
+ };
3925
+ }
3926
+ var ranked = collectionNames
3927
+ .map(function (name) { return (__assign({ name: name }, scoreCollectionMatchDetailed(tokens, name))); })
3928
+ .filter(function (entry) { return entry.score > 0; })
3929
+ .sort(function (a, b) { return b.score - a.score; })
3930
+ .slice(0, Math.max(max, 0));
3931
+ return {
3932
+ tokens: tokens,
3933
+ requestedKey: requestedKey,
3934
+ ranked: ranked
3935
+ };
3936
+ }
3937
+ function buildCollectionSelectionDetail(tokens, collection) {
3938
+ var trimmed = normalizeOptionalString(collection);
3939
+ if (!trimmed) {
3940
+ return null;
3941
+ }
3942
+ var detail = scoreCollectionMatchDetailed(tokens, trimmed);
3943
+ return {
3944
+ collection: trimmed,
3945
+ score: detail.score,
3946
+ tokenMatches: detail.tokenMatches,
3947
+ keyMatch: detail.keyMatch,
3948
+ candidateTokens: detail.candidateTokens
3949
+ };
3950
+ }
3326
3951
  function findBestCollectionMatch(requested, collectionNames) {
3327
3952
  var requestedTokens = tokenizeCollectionText(requested);
3328
3953
  if (!requestedTokens.length || !collectionNames.length) {
@@ -3368,38 +3993,8 @@ function resolveAssistantCollectionName(db, dbName, requested) {
3368
3993
  });
3369
3994
  });
3370
3995
  }
3371
- function resolveAssistantCollectionHints(message, dbName, db) {
3372
- return __awaiter(this, void 0, void 0, function () {
3373
- var text, collectionNames, tokens;
3374
- return __generator(this, function (_a) {
3375
- switch (_a.label) {
3376
- case 0:
3377
- text = normalizeOptionalString(message);
3378
- if (!text) {
3379
- return [2 /*return*/, []];
3380
- }
3381
- return [4 /*yield*/, listAssistantCollections(db, dbName)];
3382
- case 1:
3383
- collectionNames = _a.sent();
3384
- if (!collectionNames.length) {
3385
- return [2 /*return*/, []];
3386
- }
3387
- tokens = tokenizeCollectionText(text);
3388
- if (!tokens.length) {
3389
- return [2 /*return*/, []];
3390
- }
3391
- return [2 /*return*/, collectionNames
3392
- .map(function (name) { return ({ name: name, score: scoreCollectionMatch(tokens, name) }); })
3393
- .filter(function (entry) { return entry.score > 0; })
3394
- .sort(function (a, b) { return b.score - a.score; })
3395
- .slice(0, 5)
3396
- .map(function (entry) { return entry.name; })];
3397
- }
3398
- });
3399
- });
3400
- }
3401
3996
  function findQueryDateField(query) {
3402
- var e_4, _a, e_5, _b;
3997
+ var e_7, _a, e_8, _b;
3403
3998
  if (!query || typeof query !== 'object') {
3404
3999
  return null;
3405
4000
  }
@@ -3413,12 +4008,12 @@ function findQueryDateField(query) {
3413
4008
  }
3414
4009
  }
3415
4010
  }
3416
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
4011
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
3417
4012
  finally {
3418
4013
  try {
3419
4014
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
3420
4015
  }
3421
- finally { if (e_4) throw e_4.error; }
4016
+ finally { if (e_7) throw e_7.error; }
3422
4017
  }
3423
4018
  return null;
3424
4019
  }
@@ -3437,12 +4032,12 @@ function findQueryDateField(query) {
3437
4032
  }
3438
4033
  }
3439
4034
  }
3440
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
4035
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
3441
4036
  finally {
3442
4037
  try {
3443
4038
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
3444
4039
  }
3445
- finally { if (e_5) throw e_5.error; }
4040
+ finally { if (e_8) throw e_8.error; }
3446
4041
  }
3447
4042
  return null;
3448
4043
  }
@@ -3460,6 +4055,117 @@ function replaceQueryField(query, fromField, toField) {
3460
4055
  });
3461
4056
  return result;
3462
4057
  }
4058
+ function extractDateRangeConditions(query) {
4059
+ if (!query || typeof query !== 'object' || query instanceof Date) {
4060
+ return [];
4061
+ }
4062
+ var results = [];
4063
+ Object.keys(query).forEach(function (key) {
4064
+ if (key.startsWith('$')) {
4065
+ return;
4066
+ }
4067
+ var value = query[key];
4068
+ if (value instanceof Date) {
4069
+ results.push({ field: key, condition: value });
4070
+ return;
4071
+ }
4072
+ if (value && typeof value === 'object' && hasDateRangeOperators(value)) {
4073
+ results.push({ field: key, condition: value });
4074
+ }
4075
+ });
4076
+ return results;
4077
+ }
4078
+ function expandQueryDateFallbacks(query) {
4079
+ if (!query || typeof query !== 'object') {
4080
+ return null;
4081
+ }
4082
+ var addedFields = [];
4083
+ var pushField = function (field) {
4084
+ if (!field) {
4085
+ return;
4086
+ }
4087
+ if (addedFields.includes(field)) {
4088
+ return;
4089
+ }
4090
+ addedFields.push(field);
4091
+ };
4092
+ var expandOrArray = function (orArray) {
4093
+ var existingFields = new Set();
4094
+ orArray.forEach(function (entry) {
4095
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
4096
+ return;
4097
+ }
4098
+ Object.keys(entry).forEach(function (key) {
4099
+ if (!key.startsWith('$')) {
4100
+ existingFields.add(key);
4101
+ }
4102
+ });
4103
+ });
4104
+ var extended = __spreadArray([], __read(orArray), false);
4105
+ orArray.forEach(function (entry) {
4106
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
4107
+ return;
4108
+ }
4109
+ var dateConditions = extractDateRangeConditions(entry);
4110
+ dateConditions.forEach(function (condition) {
4111
+ var fallback = AI_ASSISTANT_DATE_FALLBACKS[condition.field];
4112
+ if (fallback && !existingFields.has(fallback)) {
4113
+ extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, fallback)], false);
4114
+ existingFields.add(fallback);
4115
+ pushField(fallback);
4116
+ }
4117
+ });
4118
+ if (!existingFields.has('date_original')) {
4119
+ var candidate = dateConditions.find(function (condition) { return condition.field.startsWith('date_') && condition.field !== 'date_original'; });
4120
+ if (candidate) {
4121
+ extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, candidate.field, 'date_original')], false);
4122
+ existingFields.add('date_original');
4123
+ pushField('date_original');
4124
+ }
4125
+ }
4126
+ });
4127
+ return extended;
4128
+ };
4129
+ var visit = function (value) {
4130
+ if (Array.isArray(value)) {
4131
+ var changed_1 = false;
4132
+ var nextArray = value.map(function (entry) {
4133
+ var visited = visit(entry);
4134
+ if (visited.changed) {
4135
+ changed_1 = true;
4136
+ }
4137
+ return visited.value;
4138
+ });
4139
+ return { value: changed_1 ? nextArray : value, changed: changed_1 };
4140
+ }
4141
+ if (!value || typeof value !== 'object') {
4142
+ return { value: value, changed: false };
4143
+ }
4144
+ var changed = false;
4145
+ var next = __assign({}, value);
4146
+ Object.keys(value).forEach(function (key) {
4147
+ if (key === '$or' && Array.isArray(value.$or)) {
4148
+ var expanded = expandOrArray(value.$or);
4149
+ if (expanded.length !== value.$or.length) {
4150
+ next.$or = expanded;
4151
+ changed = true;
4152
+ }
4153
+ return;
4154
+ }
4155
+ var visited = visit(value[key]);
4156
+ if (visited.changed) {
4157
+ next[key] = visited.value;
4158
+ changed = true;
4159
+ }
4160
+ });
4161
+ return { value: changed ? next : value, changed: changed };
4162
+ };
4163
+ var result = visit(query);
4164
+ if (!result.changed || !addedFields.length) {
4165
+ return null;
4166
+ }
4167
+ return { query: result.value, fields: addedFields };
4168
+ }
3463
4169
  function resolveQueryDateFieldFallback(query) {
3464
4170
  var dateField = findQueryDateField(query);
3465
4171
  if (!dateField) {
@@ -3472,7 +4178,7 @@ function resolveQueryDateFieldFallback(query) {
3472
4178
  return { from: dateField, to: fallback };
3473
4179
  }
3474
4180
  function containsForbiddenMongoOperators(value) {
3475
- var e_6, _a;
4181
+ var e_9, _a;
3476
4182
  if (!value || typeof value !== 'object') {
3477
4183
  return false;
3478
4184
  }
@@ -3491,12 +4197,12 @@ function containsForbiddenMongoOperators(value) {
3491
4197
  }
3492
4198
  }
3493
4199
  }
3494
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
4200
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
3495
4201
  finally {
3496
4202
  try {
3497
4203
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3498
4204
  }
3499
- finally { if (e_6) throw e_6.error; }
4205
+ finally { if (e_9) throw e_9.error; }
3500
4206
  }
3501
4207
  return false;
3502
4208
  }
@@ -3730,8 +4436,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
3730
4436
  }
3731
4437
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
3732
4438
  return __awaiter(this, void 0, void 0, function () {
3733
- var _a, _b, _c, _d, message, payload, status_1, e_7_1;
3734
- var _e, e_7, _f, _g;
4439
+ var _a, _b, _c, _d, message, payload, status_1, e_10_1;
4440
+ var _e, e_10, _f, _g;
3735
4441
  return __generator(this, function (_h) {
3736
4442
  switch (_h.label) {
3737
4443
  case 0:
@@ -3758,8 +4464,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
3758
4464
  return [3 /*break*/, 1];
3759
4465
  case 4: return [3 /*break*/, 11];
3760
4466
  case 5:
3761
- e_7_1 = _h.sent();
3762
- e_7 = { error: e_7_1 };
4467
+ e_10_1 = _h.sent();
4468
+ e_10 = { error: e_10_1 };
3763
4469
  return [3 /*break*/, 11];
3764
4470
  case 6:
3765
4471
  _h.trys.push([6, , 9, 10]);
@@ -3770,7 +4476,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
3770
4476
  _h.label = 8;
3771
4477
  case 8: return [3 /*break*/, 10];
3772
4478
  case 9:
3773
- if (e_7) throw e_7.error;
4479
+ if (e_10) throw e_10.error;
3774
4480
  return [7 /*endfinally*/];
3775
4481
  case 10: return [7 /*endfinally*/];
3776
4482
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -4158,7 +4864,7 @@ function normalizeRouteMatchKey(value) {
4158
4864
  return normalizeRouteKey(value).toLowerCase();
4159
4865
  }
4160
4866
  function buildClientRouteIndex() {
4161
- var e_8, _a;
4867
+ var e_11, _a;
4162
4868
  var _b;
4163
4869
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
4164
4870
  var set = new Set();
@@ -4177,12 +4883,12 @@ function buildClientRouteIndex() {
4177
4883
  }
4178
4884
  }
4179
4885
  }
4180
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
4886
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
4181
4887
  finally {
4182
4888
  try {
4183
4889
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
4184
4890
  }
4185
- finally { if (e_8) throw e_8.error; }
4891
+ finally { if (e_11) throw e_11.error; }
4186
4892
  }
4187
4893
  return { set: set, map: map, size: routes.length };
4188
4894
  }
@@ -4308,7 +5014,7 @@ function sanitizeAssistantResponse(value) {
4308
5014
  return normalizeAssistantRoutes(normalizedCurrency);
4309
5015
  }
4310
5016
  function evaluateAssistantGuardrails(message) {
4311
- var e_9, _a;
5017
+ var e_12, _a;
4312
5018
  var normalized = String(message || '').toLowerCase();
4313
5019
  var patterns = [
4314
5020
  {
@@ -4354,12 +5060,12 @@ function evaluateAssistantGuardrails(message) {
4354
5060
  }
4355
5061
  }
4356
5062
  }
4357
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
5063
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
4358
5064
  finally {
4359
5065
  try {
4360
5066
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
4361
5067
  }
4362
- finally { if (e_9) throw e_9.error; }
5068
+ finally { if (e_12) throw e_12.error; }
4363
5069
  }
4364
5070
  return null;
4365
5071
  }
@@ -4446,20 +5152,262 @@ function normalizeAiFormFields(fields) {
4446
5152
  })
4447
5153
  .filter(function (field) { return !!field; });
4448
5154
  }
5155
+ function tokenizeArithmeticExpression(expression) {
5156
+ var tokens = [];
5157
+ var i = 0;
5158
+ while (i < expression.length) {
5159
+ var char = expression[i];
5160
+ if (/\s/.test(char)) {
5161
+ i += 1;
5162
+ continue;
5163
+ }
5164
+ if (/[()+\-*/]/.test(char)) {
5165
+ tokens.push(char);
5166
+ i += 1;
5167
+ continue;
5168
+ }
5169
+ if (/\d|\./.test(char)) {
5170
+ var j = i + 1;
5171
+ while (j < expression.length && /[\d.]/.test(expression[j])) {
5172
+ j += 1;
5173
+ }
5174
+ tokens.push(expression.slice(i, j));
5175
+ i = j;
5176
+ continue;
5177
+ }
5178
+ return null;
5179
+ }
5180
+ return tokens;
5181
+ }
5182
+ function evaluateArithmeticExpression(expression) {
5183
+ var e_13, _a, e_14, _b;
5184
+ var tokens = tokenizeArithmeticExpression(expression);
5185
+ if (!tokens || !tokens.length) {
5186
+ return null;
5187
+ }
5188
+ var output = [];
5189
+ var ops = [];
5190
+ var precedence = { '+': 1, '-': 1, '*': 2, '/': 2 };
5191
+ var prevToken = '';
5192
+ var pushOperator = function (op) {
5193
+ while (ops.length) {
5194
+ var top_1 = ops[ops.length - 1];
5195
+ if (top_1 === '(') {
5196
+ break;
5197
+ }
5198
+ if ((precedence[top_1] || 0) >= (precedence[op] || 0)) {
5199
+ output.push(ops.pop());
5200
+ continue;
5201
+ }
5202
+ break;
5203
+ }
5204
+ ops.push(op);
5205
+ };
5206
+ try {
5207
+ for (var tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next(); !tokens_1_1.done; tokens_1_1 = tokens_1.next()) {
5208
+ var token = tokens_1_1.value;
5209
+ if (token === '(') {
5210
+ ops.push(token);
5211
+ prevToken = token;
5212
+ continue;
5213
+ }
5214
+ if (token === ')') {
5215
+ while (ops.length && ops[ops.length - 1] !== '(') {
5216
+ output.push(ops.pop());
5217
+ }
5218
+ if (!ops.length) {
5219
+ return null;
5220
+ }
5221
+ ops.pop();
5222
+ prevToken = token;
5223
+ continue;
5224
+ }
5225
+ if (precedence[token]) {
5226
+ if (!prevToken || prevToken === '(' || precedence[prevToken]) {
5227
+ output.push('0');
5228
+ }
5229
+ pushOperator(token);
5230
+ prevToken = token;
5231
+ continue;
5232
+ }
5233
+ if (!/^\d+(\.\d+)?$/.test(token)) {
5234
+ return null;
5235
+ }
5236
+ output.push(token);
5237
+ prevToken = token;
5238
+ }
5239
+ }
5240
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
5241
+ finally {
5242
+ try {
5243
+ if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
5244
+ }
5245
+ finally { if (e_13) throw e_13.error; }
5246
+ }
5247
+ while (ops.length) {
5248
+ var op = ops.pop();
5249
+ if (op === '(' || op === ')') {
5250
+ return null;
5251
+ }
5252
+ output.push(op);
5253
+ }
5254
+ var stack = [];
5255
+ try {
5256
+ for (var output_1 = __values(output), output_1_1 = output_1.next(); !output_1_1.done; output_1_1 = output_1.next()) {
5257
+ var token = output_1_1.value;
5258
+ if (precedence[token]) {
5259
+ if (stack.length < 2) {
5260
+ return null;
5261
+ }
5262
+ var b = stack.pop();
5263
+ var a = stack.pop();
5264
+ switch (token) {
5265
+ case '+':
5266
+ stack.push(a + b);
5267
+ break;
5268
+ case '-':
5269
+ stack.push(a - b);
5270
+ break;
5271
+ case '*':
5272
+ stack.push(a * b);
5273
+ break;
5274
+ case '/':
5275
+ stack.push(a / b);
5276
+ break;
5277
+ default:
5278
+ return null;
5279
+ }
5280
+ continue;
5281
+ }
5282
+ stack.push(Number(token));
5283
+ }
5284
+ }
5285
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
5286
+ finally {
5287
+ try {
5288
+ if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
5289
+ }
5290
+ finally { if (e_14) throw e_14.error; }
5291
+ }
5292
+ if (stack.length !== 1 || Number.isNaN(stack[0])) {
5293
+ return null;
5294
+ }
5295
+ return stack[0];
5296
+ }
5297
+ function resolveDateExpression(expression) {
5298
+ var trimmed = String(expression || '').trim();
5299
+ if (!trimmed) {
5300
+ return null;
5301
+ }
5302
+ var quotedMatch = trimmed.match(/^['"](.+?)['"]$/);
5303
+ if (quotedMatch) {
5304
+ var date = new Date(quotedMatch[1]);
5305
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
5306
+ }
5307
+ if (trimmed === 'Date.now()') {
5308
+ return new Date(Date.now()).toISOString();
5309
+ }
5310
+ var nowMatch = trimmed.match(/^Date\.now\(\)\s*([+-])\s*(.+)$/);
5311
+ if (nowMatch) {
5312
+ var delta = evaluateArithmeticExpression(nowMatch[2]);
5313
+ if (delta === null) {
5314
+ return null;
5315
+ }
5316
+ var base = Date.now();
5317
+ var computed = nowMatch[1] === '-' ? base - delta : base + delta;
5318
+ return new Date(computed).toISOString();
5319
+ }
5320
+ var numeric = evaluateArithmeticExpression(trimmed);
5321
+ if (numeric !== null) {
5322
+ var date = new Date(numeric);
5323
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
5324
+ }
5325
+ return null;
5326
+ }
5327
+ function replaceNewDateExpressions(input) {
5328
+ var output = '';
5329
+ var index = 0;
5330
+ while (index < input.length) {
5331
+ var start = input.indexOf('new Date(', index);
5332
+ if (start === -1) {
5333
+ output += input.slice(index);
5334
+ break;
5335
+ }
5336
+ output += input.slice(index, start);
5337
+ var cursor = start + 'new Date('.length;
5338
+ var depth = 1;
5339
+ while (cursor < input.length && depth > 0) {
5340
+ var char = input[cursor];
5341
+ if (char === '(') {
5342
+ depth += 1;
5343
+ }
5344
+ else if (char === ')') {
5345
+ depth -= 1;
5346
+ }
5347
+ cursor += 1;
5348
+ }
5349
+ if (depth !== 0) {
5350
+ output += input.slice(start);
5351
+ break;
5352
+ }
5353
+ var inner = input.slice(start + 'new Date('.length, cursor - 1);
5354
+ var iso = resolveDateExpression(inner);
5355
+ if (iso) {
5356
+ output += "{\"$date\":\"".concat(iso, "\"}");
5357
+ }
5358
+ else {
5359
+ output += input.slice(start, cursor);
5360
+ }
5361
+ index = cursor;
5362
+ }
5363
+ return output;
5364
+ }
5365
+ function replaceIsoDateExpressions(input) {
5366
+ return input.replace(/ISODate\(([^)]+)\)/g, function (_match, inner) {
5367
+ var iso = resolveDateExpression(inner);
5368
+ return iso ? "{\"$date\":\"".concat(iso, "\"}") : _match;
5369
+ });
5370
+ }
5371
+ function preprocessJsonLike(content) {
5372
+ var normalized = content;
5373
+ normalized = replaceNewDateExpressions(normalized);
5374
+ normalized = replaceIsoDateExpressions(normalized);
5375
+ return normalized;
5376
+ }
5377
+ function convertExtendedDates(value) {
5378
+ if (Array.isArray(value)) {
5379
+ return value.map(function (entry) { return convertExtendedDates(entry); });
5380
+ }
5381
+ if (!value || typeof value !== 'object') {
5382
+ return value;
5383
+ }
5384
+ var keys = Object.keys(value);
5385
+ if (keys.length === 1 && keys[0] === '$date') {
5386
+ var raw = value.$date;
5387
+ var date = new Date(raw);
5388
+ return Number.isNaN(date.getTime()) ? value : date;
5389
+ }
5390
+ var output = {};
5391
+ keys.forEach(function (key) {
5392
+ output[key] = convertExtendedDates(value[key]);
5393
+ });
5394
+ return output;
5395
+ }
4449
5396
  function parseJsonObject(content) {
4450
5397
  if (!content || typeof content !== 'string') {
4451
5398
  return null;
4452
5399
  }
5400
+ var normalized = preprocessJsonLike(content);
4453
5401
  try {
4454
- return JSON.parse(content);
5402
+ return convertExtendedDates(JSON.parse(normalized));
4455
5403
  }
4456
5404
  catch (_a) {
4457
- var match = content.match(/\{[\s\S]*\}/);
5405
+ var match = normalized.match(/\{[\s\S]*\}/);
4458
5406
  if (!match) {
4459
5407
  return null;
4460
5408
  }
4461
5409
  try {
4462
- return JSON.parse(match[0]);
5410
+ return convertExtendedDates(JSON.parse(match[0]));
4463
5411
  }
4464
5412
  catch (_b) {
4465
5413
  return null;
@@ -4523,8 +5471,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
4523
5471
  }
4524
5472
  function readAttachmentContents(attachments) {
4525
5473
  return __awaiter(this, void 0, void 0, function () {
4526
- var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_10_1;
4527
- var e_10, _b;
5474
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_15_1;
5475
+ var e_15, _b;
4528
5476
  return __generator(this, function (_c) {
4529
5477
  switch (_c.label) {
4530
5478
  case 0:
@@ -4603,14 +5551,14 @@ function readAttachmentContents(attachments) {
4603
5551
  return [3 /*break*/, 2];
4604
5552
  case 10: return [3 /*break*/, 13];
4605
5553
  case 11:
4606
- e_10_1 = _c.sent();
4607
- e_10 = { error: e_10_1 };
5554
+ e_15_1 = _c.sent();
5555
+ e_15 = { error: e_15_1 };
4608
5556
  return [3 /*break*/, 13];
4609
5557
  case 12:
4610
5558
  try {
4611
5559
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
4612
5560
  }
4613
- finally { if (e_10) throw e_10.error; }
5561
+ finally { if (e_15) throw e_15.error; }
4614
5562
  return [7 /*endfinally*/];
4615
5563
  case 13: return [2 /*return*/, {
4616
5564
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -4787,7 +5735,7 @@ function estimateUsage(messages, responseText, model) {
4787
5735
  };
4788
5736
  }
4789
5737
  function evaluateGuardrails(message) {
4790
- var e_11, _a;
5738
+ var e_16, _a;
4791
5739
  var normalized = String(message || '').toLowerCase();
4792
5740
  var patterns = [
4793
5741
  { 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.' },
@@ -4809,12 +5757,12 @@ function evaluateGuardrails(message) {
4809
5757
  }
4810
5758
  }
4811
5759
  }
4812
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
5760
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
4813
5761
  finally {
4814
5762
  try {
4815
5763
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
4816
5764
  }
4817
- finally { if (e_11) throw e_11.error; }
5765
+ finally { if (e_16) throw e_16.error; }
4818
5766
  }
4819
5767
  return null;
4820
5768
  }