@resolveio/server-lib 22.0.18 → 22.0.19

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.
@@ -116,6 +116,7 @@ exports.buildDisplayTable = buildDisplayTable;
116
116
  exports.formatDisplayTableMarkdown = formatDisplayTableMarkdown;
117
117
  exports.normalizeAssistantNowExprPlaceholders = normalizeAssistantNowExprPlaceholders;
118
118
  exports.rewriteMatchExpressionsToExpr = rewriteMatchExpressionsToExpr;
119
+ exports.normalizeAssistantMonthlyCalendarWindowPipeline = normalizeAssistantMonthlyCalendarWindowPipeline;
119
120
  exports.stripQueryFieldPathsDeep = stripQueryFieldPathsDeep;
120
121
  exports.stripScopedFieldsFromPipeline = stripScopedFieldsFromPipeline;
121
122
  exports.rewriteEmbeddedMatchObjects = rewriteEmbeddedMatchObjects;
@@ -408,6 +409,7 @@ var AI_ASSISTANT_REPORT_BUILDER_EXPERT_PLAYBOOK = [
408
409
  '- Use collection joins/lookups when selected fields live across related collections.',
409
410
  '- If multiple arrays are selected, link them by shared identifiers (_id or id_<x>) so rows are aligned and not duplicated by cartesian expansion.',
410
411
  '- For relative dates, include an upper bound <= $$NOW unless user explicitly asks for future ranges.',
412
+ '- For time-based trends over "last/past N" periods, use full completed calendar-period bounds in UTC aligned to the requested grain (day/week/month/quarter/year) unless the user explicitly asks for period-to-date.',
411
413
  '- For invoice revenue, prefer paid_total fallback grand_total and paid/closed states when applicable.',
412
414
  '',
413
415
  '6) Reliability fallback sequence when result is empty.',
@@ -497,6 +499,7 @@ var AI_ASSISTANT_SYSTEM_PROMPT = [
497
499
  '- Do not use /report/* routes as permissionView for data directives; use a module route that matches the collection.',
498
500
  '- For revenue/sales/billing questions, use invoices and sum paid_total (fallback to grand_total) with date_paid and Paid/Closed status when available.',
499
501
  '- For revenue answers, always state the metric/date basis used (paid_total/date_paid vs grand_total/date_invoice). If tool verification warns about ambiguity or partial months, call that out before totals.',
502
+ '- For time-based "last/past N" breakdowns, use full completed calendar-period windows in UTC aligned to the requested grain (day/week/month/quarter/year) by default, and present concrete start/end dates.',
500
503
  '- For relative date ranges (last/past/recent), include an upper bound <= $$NOW unless the user specifies a future end date.',
501
504
  '- Keep queries minimal, read-only, and avoid user/credential data unless the user is a super admin.',
502
505
  '- Assume you are not a super admin unless explicitly told otherwise.',
@@ -512,6 +515,7 @@ var AI_ASSISTANT_SYSTEM_PROMPT = [
512
515
  '- If the user explicitly asks for IDs, set options.includeIds: true.',
513
516
  '- If a data question returns zero results, verify the collection/date field with a tiny read (limit 1-5) or a date field fallback before concluding there is no data.',
514
517
  '- Keep responses concise and use the configured reasoning effort level (default low).',
518
+ '- Never show internal placeholders like $$NOW in user-facing text; always use concrete dates.',
515
519
  '',
516
520
  AI_ASSISTANT_REPORT_BUILDER_EXPERT_PLAYBOOK
517
521
  ].join('\n');
@@ -3147,7 +3151,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3147
3151
  }
3148
3152
  function verifyAssistantAggregateReliability(params) {
3149
3153
  return __awaiter(this, void 0, void 0, function () {
3150
- var collection, collectionBase, monthKey, amountKey, baseMap, groupIndex, groupPaths, dateField, mergedMatch, dateFieldsInMatch, baseMatchNoDate, primaryDateCondition, verifyPipeline, verifyDocs, _a, verifyMap, comparedMonths, paidCloserCount, grandCloserCount, sumPaidDiffPct, sumGrandDiffPct, maxPaidDiffPct, maxGrandDiffPct, sumPaidGrandGapPct, highVarianceMonths, checks, warnings, avgPaidDiffPct, avgGrandDiffPct, avgPaidGrandGapPct, baselineMetric, rollingWindow, rollingWindowBounds, verificationWindow, rollingStart, rollingEnd, fullMonthStart, fullMonthEndExclusive, normalizedMetric, bounds, fullMonthMatch, fullMonthDocs, fullMonthMap, fullMonthDiff, _b, alternateDateField, alternateDateCondition, bounds, alternateMatch, alternateDocs, alternateMap, alternateDiff, _c;
3154
+ var collection, collectionBase, monthKey, amountKey, baseMap, groupIndex, groupPaths, dateField, mergedMatch, dateFieldsInMatch, baseMatchNoDate, primaryDateCondition, verifyPipeline, verifyDocs, _a, verifyMap, comparedMonths, paidCloserCount, grandCloserCount, sumPaidDiffPct, sumGrandDiffPct, maxPaidDiffPct, maxGrandDiffPct, sumPaidGrandGapPct, highVarianceMonths, checks, warnings, avgPaidDiffPct, avgGrandDiffPct, avgPaidGrandGapPct, baselineMetric, rollingWindow, fullMonthWindow, rollingWindowBounds, fullMonthWindowBounds, verificationWindow, rollingStart, rollingEnd, fullMonthStart, fullMonthEndExclusive, fullMonthStart, fullMonthEndExclusive, fullMonthEndInclusiveDate, fullMonthEnd, normalizedMetric, bounds, fullMonthMatch, fullMonthDocs, fullMonthMap, fullMonthDiff, _b, alternateDateField, alternateDateCondition, bounds, bounds, alternateMatch, alternateDocs, alternateMap, alternateDiff, _c;
3151
3155
  var _d, _e;
3152
3156
  var _f;
3153
3157
  return __generator(this, function (_g) {
@@ -3225,9 +3229,8 @@ function verifyAssistantAggregateReliability(params) {
3225
3229
  comparedMonths += 1;
3226
3230
  var paidDiff = Math.abs(value - match.paid);
3227
3231
  var grandDiff = Math.abs(value - match.grand);
3228
- var denom = Math.max(Math.abs(value), 1);
3229
- var paidPct = paidDiff / denom;
3230
- var grandPct = grandDiff / denom;
3232
+ var paidPct = computeAssistantRelativeDiffPct(value, match.paid);
3233
+ var grandPct = computeAssistantRelativeDiffPct(value, match.grand);
3231
3234
  sumPaidDiffPct += paidPct;
3232
3235
  sumGrandDiffPct += grandPct;
3233
3236
  maxPaidDiffPct = Math.max(maxPaidDiffPct, paidPct);
@@ -3238,7 +3241,7 @@ function verifyAssistantAggregateReliability(params) {
3238
3241
  else if (grandDiff < paidDiff) {
3239
3242
  grandCloserCount += 1;
3240
3243
  }
3241
- var gapPct = Math.abs(match.paid - match.grand) / Math.max(Math.abs(match.grand), 1);
3244
+ var gapPct = computeAssistantRelativeDiffPct(match.paid, match.grand);
3242
3245
  sumPaidGrandGapPct += gapPct;
3243
3246
  if (Math.min(paidPct, grandPct) >= AI_ASSISTANT_REVENUE_VERIFY_DIFF_WARN_THRESHOLD) {
3244
3247
  highVarianceMonths.push(month);
@@ -3288,7 +3291,9 @@ function verifyAssistantAggregateReliability(params) {
3288
3291
  }
3289
3292
  }
3290
3293
  rollingWindow = detectAssistantRollingMonthWindow(params.pipeline || []);
3294
+ fullMonthWindow = detectAssistantFullMonthWindow(params.pipeline || []);
3291
3295
  rollingWindowBounds = null;
3296
+ fullMonthWindowBounds = null;
3292
3297
  verificationWindow = null;
3293
3298
  if ((rollingWindow === null || rollingWindow === void 0 ? void 0 : rollingWindow.months) && (rollingWindow === null || rollingWindow === void 0 ? void 0 : rollingWindow.upperNow)) {
3294
3299
  rollingWindowBounds = resolveAssistantRollingWindowBounds(rollingWindow.months);
@@ -3312,6 +3317,27 @@ function verifyAssistantAggregateReliability(params) {
3312
3317
  });
3313
3318
  warnings.push("Date window is rolling (".concat(rollingStart, " to ").concat(rollingEnd, " UTC; last ").concat(rollingWindow.months, " months), so first/current months may be partial."));
3314
3319
  }
3320
+ else if ((fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.months) && (fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.upperMonthStart)) {
3321
+ fullMonthWindowBounds = resolveAssistantRollingWindowBounds(fullMonthWindow.months);
3322
+ fullMonthStart = formatAssistantIsoDateOnly(fullMonthWindowBounds.startOfWindow);
3323
+ fullMonthEndExclusive = formatAssistantIsoDateOnly(fullMonthWindowBounds.startOfCurrentMonth);
3324
+ fullMonthEndInclusiveDate = new Date(fullMonthWindowBounds.startOfCurrentMonth);
3325
+ fullMonthEndInclusiveDate.setUTCDate(fullMonthEndInclusiveDate.getUTCDate() - 1);
3326
+ fullMonthEnd = formatAssistantIsoDateOnly(fullMonthEndInclusiveDate);
3327
+ verificationWindow = {
3328
+ type: 'full_month_last_n_months',
3329
+ months: fullMonthWindow.months,
3330
+ startDate: fullMonthStart,
3331
+ endDate: fullMonthEnd,
3332
+ endDateExclusive: fullMonthEndExclusive,
3333
+ timezone: 'UTC'
3334
+ };
3335
+ checks.push({
3336
+ name: 'Date window shape',
3337
+ status: 'pass',
3338
+ details: "Query uses full-month calendar bounds (".concat(fullMonthStart, " to ").concat(fullMonthEnd, " UTC; last ").concat(fullMonthWindow.months, " full months).")
3339
+ });
3340
+ }
3315
3341
  else {
3316
3342
  checks.push({
3317
3343
  name: 'Date window shape',
@@ -3345,7 +3371,7 @@ function verifyAssistantAggregateReliability(params) {
3345
3371
  ? "Compared ".concat(fullMonthDiff.comparedMonths, " month(s); avg diff ").concat((0, common_1.round)(fullMonthDiff.avgDiffPct * 100, 2), "%.")
3346
3372
  : 'No overlapping months for full-month cross-check.'
3347
3373
  });
3348
- if (fullMonthDiff.comparedMonths && fullMonthDiff.avgDiffPct >= AI_ASSISTANT_REVENUE_VERIFY_DIFF_WARN_THRESHOLD) {
3374
+ if (fullMonthDiff.comparedMonths >= 2 && fullMonthDiff.avgDiffPct >= AI_ASSISTANT_REVENUE_VERIFY_DIFF_WARN_THRESHOLD) {
3349
3375
  warnings.push("Rolling-window totals differ from full-month totals by ".concat((0, common_1.round)(fullMonthDiff.avgDiffPct * 100, 2), "% on average."));
3350
3376
  }
3351
3377
  if (!fullMonthDiff.comparedMonths) {
@@ -3376,6 +3402,13 @@ function verifyAssistantAggregateReliability(params) {
3376
3402
  $lte: bounds.now
3377
3403
  };
3378
3404
  }
3405
+ else if ((fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.months) && (fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.upperMonthStart) && fullMonthWindowBounds) {
3406
+ bounds = fullMonthWindowBounds;
3407
+ alternateDateCondition = {
3408
+ $gte: bounds.startOfWindow,
3409
+ $lt: bounds.startOfCurrentMonth
3410
+ };
3411
+ }
3379
3412
  else if (primaryDateCondition && typeof primaryDateCondition === 'object') {
3380
3413
  alternateDateCondition = primaryDateCondition;
3381
3414
  }
@@ -3398,7 +3431,7 @@ function verifyAssistantAggregateReliability(params) {
3398
3431
  ? "Compared ".concat(alternateDiff.comparedMonths, " month(s); avg diff ").concat((0, common_1.round)(alternateDiff.avgDiffPct * 100, 2), "%.")
3399
3432
  : 'No overlapping months for alternate date-field cross-check.'
3400
3433
  });
3401
- if (alternateDiff.comparedMonths && alternateDiff.avgDiffPct >= AI_ASSISTANT_REVENUE_VERIFY_DIFF_WARN_THRESHOLD) {
3434
+ if (alternateDiff.comparedMonths >= 2 && alternateDiff.avgDiffPct >= AI_ASSISTANT_REVENUE_VERIFY_DIFF_WARN_THRESHOLD) {
3402
3435
  warnings.push("Switching from ".concat(dateField, " to ").concat(alternateDateField, " changes monthly totals by ").concat((0, common_1.round)(alternateDiff.avgDiffPct * 100, 2), "% on average."));
3403
3436
  }
3404
3437
  return [3 /*break*/, 12];
@@ -3536,22 +3569,23 @@ function mergeAssistantPreGroupMatchStages(pipeline, groupIndex) {
3536
3569
  return { $and: matches };
3537
3570
  }
3538
3571
  function detectAssistantRollingMonthWindow(pipeline) {
3539
- var raw = JSON.stringify(Array.isArray(pipeline) ? pipeline : []);
3540
- if (!raw) {
3541
- return null;
3542
- }
3543
- var amountMatch = raw.match(/"\$dateSubtract":\{"startDate":"\$\$NOW","unit":"month","amount":([0-9]+)\}/);
3544
- if (!amountMatch) {
3572
+ var detected = detectAssistantMonthWindowFromPipeline(pipeline);
3573
+ if (!detected || detected.mode !== 'rolling') {
3545
3574
  return null;
3546
3575
  }
3547
- var months = Number(amountMatch[1]);
3548
- if (!Number.isFinite(months) || months < 1) {
3576
+ return {
3577
+ months: detected.months,
3578
+ upperNow: true
3579
+ };
3580
+ }
3581
+ function detectAssistantFullMonthWindow(pipeline) {
3582
+ var detected = detectAssistantMonthWindowFromPipeline(pipeline);
3583
+ if (!detected || detected.mode !== 'full_month') {
3549
3584
  return null;
3550
3585
  }
3551
- var nowCount = (raw.match(/\$\$NOW/g) || []).length;
3552
3586
  return {
3553
- months: months,
3554
- upperNow: nowCount >= 2
3587
+ months: detected.months,
3588
+ upperMonthStart: true
3555
3589
  };
3556
3590
  }
3557
3591
  function buildAssistantMonthlyRevenueVerificationPipeline(match, dateField) {
@@ -3622,6 +3656,12 @@ function mapAssistantMetricByMonth(source, metric) {
3622
3656
  });
3623
3657
  return mapped;
3624
3658
  }
3659
+ function computeAssistantRelativeDiffPct(baseValue, compareValue) {
3660
+ var left = Number.isFinite(baseValue) ? baseValue : 0;
3661
+ var right = Number.isFinite(compareValue) ? compareValue : 0;
3662
+ var denom = Math.max(Math.abs(left), Math.abs(right), 1);
3663
+ return Math.abs(left - right) / denom;
3664
+ }
3625
3665
  function compareAssistantMonthlyValueMaps(base, compare) {
3626
3666
  var comparedMonths = 0;
3627
3667
  var sumDiffPct = 0;
@@ -3631,7 +3671,7 @@ function compareAssistantMonthlyValueMaps(base, compare) {
3631
3671
  if (typeof compareValue !== 'number') {
3632
3672
  return;
3633
3673
  }
3634
- var diffPct = Math.abs(baseValue - compareValue) / Math.max(Math.abs(baseValue), 1);
3674
+ var diffPct = computeAssistantRelativeDiffPct(baseValue, compareValue);
3635
3675
  comparedMonths += 1;
3636
3676
  sumDiffPct += diffPct;
3637
3677
  maxDiffPct = Math.max(maxDiffPct, diffPct);
@@ -3888,7 +3928,7 @@ function buildAssistantCodexToolFollowupPrompt(message, attachmentText, historyT
3888
3928
  var trimmedHistory = normalizeOptionalString(historyText);
3889
3929
  var historyBlock = trimmedHistory ? "\n\nConversation so far:\n".concat(trimmedHistory) : '';
3890
3930
  var toolBlock = toolResultText ? "\n\nTool Result:\n".concat(toolResultText) : '';
3891
- var instruction = '\n\nInstruction:\nNow answer the user. Do NOT output another REPORT_BUILDER_* directive. Output plain Markdown. Summarize first, then include a Markdown table. If the Tool Result includes Verification warnings, explicitly include them and call out the metric/date basis used.';
3931
+ var instruction = '\n\nInstruction:\nNow answer the user. Do NOT output another REPORT_BUILDER_* directive. Output plain Markdown. Summarize first, then include a Markdown table. If the Tool Result includes Verification warnings, explicitly include them and call out the metric/date basis used. Include explicit UTC date boundaries and never show placeholders like $$NOW.';
3892
3932
  return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(toolBlock).concat(instruction).trim();
3893
3933
  }
3894
3934
  function buildAssistantToolFallbackResponse(result) {
@@ -3939,8 +3979,18 @@ function applyAssistantDatedReportWindow(value, toolResult) {
3939
3979
  if (!startDate || !endDate) {
3940
3980
  return content || value || '';
3941
3981
  }
3982
+ var mode = normalizeOptionalString(window === null || window === void 0 ? void 0 : window.mode).toLowerCase();
3942
3983
  var months = normalizeOptionalNumber(window === null || window === void 0 ? void 0 : window.months);
3943
- var monthsText = months && months > 0 ? "; rolling last ".concat((0, common_1.round)(months), " month").concat((0, common_1.round)(months) === 1 ? '' : 's') : '';
3984
+ var monthsText = '';
3985
+ if (months && months > 0) {
3986
+ var count = (0, common_1.round)(months);
3987
+ if (mode === 'full_month') {
3988
+ monthsText = "; last ".concat(count, " full month").concat(count === 1 ? '' : 's');
3989
+ }
3990
+ else if (mode === 'rolling') {
3991
+ monthsText = "; rolling last ".concat(count, " month").concat(count === 1 ? '' : 's');
3992
+ }
3993
+ }
3944
3994
  var line = "Report date range (UTC): ".concat(startDate, " to ").concat(endDate).concat(monthsText, ".");
3945
3995
  var normalizedLower = String(content || '').toLowerCase();
3946
3996
  if (normalizedLower.includes(startDate.toLowerCase()) && normalizedLower.includes(endDate.toLowerCase())) {
@@ -3958,10 +4008,19 @@ function resolveAssistantDatedReportWindow(toolResult) {
3958
4008
  var verificationStart = normalizeOptionalString(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.startDate);
3959
4009
  var verificationEnd = normalizeOptionalString(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.endDate);
3960
4010
  if (verificationStart && verificationEnd) {
4011
+ var verificationType = normalizeOptionalString(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.type).toLowerCase();
4012
+ var mode = void 0;
4013
+ if (verificationType.includes('full_month')) {
4014
+ mode = 'full_month';
4015
+ }
4016
+ else if (verificationType.includes('rolling')) {
4017
+ mode = 'rolling';
4018
+ }
3961
4019
  return {
3962
4020
  startDate: verificationStart,
3963
4021
  endDate: verificationEnd,
3964
- months: normalizeOptionalNumber(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.months) || undefined
4022
+ months: normalizeOptionalNumber(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.months) || undefined,
4023
+ mode: mode
3965
4024
  };
3966
4025
  }
3967
4026
  var pipelineCandidates = [
@@ -3975,6 +4034,22 @@ function resolveAssistantDatedReportWindow(toolResult) {
3975
4034
  if (!Array.isArray(candidate)) {
3976
4035
  continue;
3977
4036
  }
4037
+ var fullMonthWindow = detectAssistantFullMonthWindow(candidate);
4038
+ if ((fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.months) && (fullMonthWindow === null || fullMonthWindow === void 0 ? void 0 : fullMonthWindow.upperMonthStart)) {
4039
+ var bounds_1 = resolveAssistantRollingWindowBounds(fullMonthWindow.months);
4040
+ var startDate_1 = formatAssistantIsoDateOnly(bounds_1.startOfWindow);
4041
+ var endDateValue = new Date(bounds_1.startOfCurrentMonth);
4042
+ endDateValue.setUTCDate(endDateValue.getUTCDate() - 1);
4043
+ var endDate_1 = formatAssistantIsoDateOnly(endDateValue);
4044
+ if (startDate_1 && endDate_1) {
4045
+ return {
4046
+ startDate: startDate_1,
4047
+ endDate: endDate_1,
4048
+ months: fullMonthWindow.months,
4049
+ mode: 'full_month'
4050
+ };
4051
+ }
4052
+ }
3978
4053
  var rollingWindow = detectAssistantRollingMonthWindow(candidate);
3979
4054
  if (!(rollingWindow === null || rollingWindow === void 0 ? void 0 : rollingWindow.months) || !(rollingWindow === null || rollingWindow === void 0 ? void 0 : rollingWindow.upperNow)) {
3980
4055
  continue;
@@ -3988,7 +4063,8 @@ function resolveAssistantDatedReportWindow(toolResult) {
3988
4063
  return {
3989
4064
  startDate: startDate,
3990
4065
  endDate: endDate,
3991
- months: rollingWindow.months
4066
+ months: rollingWindow.months,
4067
+ mode: 'rolling'
3992
4068
  };
3993
4069
  }
3994
4070
  }
@@ -5923,9 +5999,13 @@ function isAssistantMarkdownTableRowLine(line) {
5923
5999
  return /^\|.*\|$/.test(trimmed);
5924
6000
  }
5925
6001
  function applyAssistantDisplayTableToResponse(value, display) {
5926
- if (!display || !Array.isArray(display.rows) || !display.rows.length) {
6002
+ if (!display || !Array.isArray(display.rows)) {
5927
6003
  return value;
5928
6004
  }
6005
+ if (!display.rows.length) {
6006
+ // Remove any model-generated placeholder table when tool data has no rows.
6007
+ return stripAssistantMarkdownTables(value);
6008
+ }
5929
6009
  var table = formatDisplayTableMarkdown(display);
5930
6010
  if (!table) {
5931
6011
  return value;
@@ -6381,7 +6461,7 @@ function rewriteMatchExpressionsToExpr(match) {
6381
6461
  return rewriteValue(match);
6382
6462
  }
6383
6463
  function buildInvoiceStatusRegex(value) {
6384
- var normalized = String(value || '').toLowerCase();
6464
+ var normalized = normalizeOptionalString(value).toLowerCase();
6385
6465
  if (!normalized) {
6386
6466
  return null;
6387
6467
  }
@@ -6391,6 +6471,31 @@ function buildInvoiceStatusRegex(value) {
6391
6471
  }
6392
6472
  return /paid|closed/i;
6393
6473
  }
6474
+ function buildInvoiceStatusRegexFromValue(value) {
6475
+ if (typeof value === 'string') {
6476
+ return buildInvoiceStatusRegex(value);
6477
+ }
6478
+ if (Array.isArray(value)) {
6479
+ var normalizedValues = value
6480
+ .filter(function (entry) { return typeof entry === 'string'; })
6481
+ .map(function (entry) { return normalizeOptionalString(entry); })
6482
+ .filter(Boolean);
6483
+ if (!normalizedValues.length) {
6484
+ return null;
6485
+ }
6486
+ return buildInvoiceStatusRegex(normalizedValues.join(' '));
6487
+ }
6488
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
6489
+ var keys = Object.keys(value);
6490
+ if (keys.length === 1 && typeof value.$eq === 'string') {
6491
+ return buildInvoiceStatusRegex(value.$eq);
6492
+ }
6493
+ if (keys.length === 1 && Array.isArray(value.$in)) {
6494
+ return buildInvoiceStatusRegexFromValue(value.$in);
6495
+ }
6496
+ }
6497
+ return null;
6498
+ }
6394
6499
  function normalizeInvoiceStatusMatch(match) {
6395
6500
  var rewriteValue = function (value) {
6396
6501
  if (Array.isArray(value)) {
@@ -6407,8 +6512,8 @@ function normalizeInvoiceStatusMatch(match) {
6407
6512
  return;
6408
6513
  }
6409
6514
  var field = key.split('.').pop() || key;
6410
- if (field === 'status' && typeof entry === 'string') {
6411
- var regex = buildInvoiceStatusRegex(entry);
6515
+ if (field === 'status' || field === 'state') {
6516
+ var regex = buildInvoiceStatusRegexFromValue(entry);
6412
6517
  if (regex) {
6413
6518
  result[key] = regex;
6414
6519
  return;
@@ -6424,12 +6529,299 @@ function normalizeInvoiceStatusMatch(match) {
6424
6529
  };
6425
6530
  return rewriteValue(match);
6426
6531
  }
6532
+ function extractAssistantFieldPathFromOperand(value) {
6533
+ if (typeof value !== 'string') {
6534
+ return '';
6535
+ }
6536
+ if (!value.startsWith('$') || value.startsWith('$$')) {
6537
+ return '';
6538
+ }
6539
+ return value.slice(1);
6540
+ }
6541
+ function createAssistantNowMonthStartExpr() {
6542
+ return {
6543
+ $dateTrunc: {
6544
+ date: '$$NOW',
6545
+ unit: 'month'
6546
+ }
6547
+ };
6548
+ }
6549
+ function isAssistantNowMonthStartExpr(value) {
6550
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
6551
+ return false;
6552
+ }
6553
+ var dateTrunc = value.$dateTrunc;
6554
+ if (!dateTrunc || typeof dateTrunc !== 'object' || Array.isArray(dateTrunc)) {
6555
+ return false;
6556
+ }
6557
+ if (dateTrunc.date !== '$$NOW') {
6558
+ return false;
6559
+ }
6560
+ return normalizeOptionalString(dateTrunc.unit).toLowerCase() === 'month';
6561
+ }
6562
+ function extractAssistantMonthLowerBound(value) {
6563
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
6564
+ return null;
6565
+ }
6566
+ var dateSubtract = value.$dateSubtract;
6567
+ if (!dateSubtract || typeof dateSubtract !== 'object' || Array.isArray(dateSubtract)) {
6568
+ return null;
6569
+ }
6570
+ var unit = normalizeOptionalString(dateSubtract.unit).toLowerCase();
6571
+ var months = normalizeOptionalNumber(dateSubtract.amount);
6572
+ if (unit !== 'month' || !months || months < 1) {
6573
+ return null;
6574
+ }
6575
+ if (dateSubtract.startDate === '$$NOW') {
6576
+ return { months: (0, common_1.round)(months), mode: 'rolling' };
6577
+ }
6578
+ if (isAssistantNowMonthStartExpr(dateSubtract.startDate)) {
6579
+ return { months: (0, common_1.round)(months), mode: 'full_month' };
6580
+ }
6581
+ return null;
6582
+ }
6583
+ function flattenAssistantExprClauses(expr) {
6584
+ if (!expr || typeof expr !== 'object' || Array.isArray(expr)) {
6585
+ return [];
6586
+ }
6587
+ if (Array.isArray(expr.$and)) {
6588
+ return expr.$and;
6589
+ }
6590
+ return [expr];
6591
+ }
6592
+ function detectAssistantMonthWindowInExpr(expr, allowedDateFields) {
6593
+ var e_12, _a;
6594
+ var clauses = flattenAssistantExprClauses(expr);
6595
+ if (!clauses.length) {
6596
+ return null;
6597
+ }
6598
+ var lowerClauses = [];
6599
+ var upperClauses = [];
6600
+ clauses.forEach(function (clause, index) {
6601
+ if (!clause || typeof clause !== 'object' || Array.isArray(clause)) {
6602
+ return;
6603
+ }
6604
+ var keys = Object.keys(clause);
6605
+ if (keys.length !== 1) {
6606
+ return;
6607
+ }
6608
+ var operator = keys[0];
6609
+ if (!['$gte', '$gt', '$lte', '$lt'].includes(operator)) {
6610
+ return;
6611
+ }
6612
+ var operands = clause[operator];
6613
+ if (!Array.isArray(operands) || operands.length !== 2) {
6614
+ return;
6615
+ }
6616
+ var field = extractAssistantFieldPathFromOperand(operands[0]);
6617
+ if (!field) {
6618
+ return;
6619
+ }
6620
+ if ((allowedDateFields === null || allowedDateFields === void 0 ? void 0 : allowedDateFields.size) && !allowedDateFields.has(field)) {
6621
+ return;
6622
+ }
6623
+ if (operator === '$gte' || operator === '$gt') {
6624
+ var lowerBound = extractAssistantMonthLowerBound(operands[1]);
6625
+ if (!lowerBound) {
6626
+ return;
6627
+ }
6628
+ lowerClauses.push({
6629
+ index: index,
6630
+ field: field,
6631
+ months: lowerBound.months,
6632
+ mode: lowerBound.mode
6633
+ });
6634
+ return;
6635
+ }
6636
+ if (operands[1] === '$$NOW') {
6637
+ upperClauses.push({ index: index, field: field, mode: 'rolling' });
6638
+ return;
6639
+ }
6640
+ if (isAssistantNowMonthStartExpr(operands[1])) {
6641
+ upperClauses.push({ index: index, field: field, mode: 'full_month' });
6642
+ }
6643
+ });
6644
+ var _loop_6 = function (lower) {
6645
+ var upper = upperClauses.find(function (candidate) { return (candidate.field === lower.field
6646
+ && candidate.mode === lower.mode); });
6647
+ if (!upper) {
6648
+ return "continue";
6649
+ }
6650
+ return { value: {
6651
+ field: lower.field,
6652
+ months: lower.months,
6653
+ mode: lower.mode,
6654
+ lowerIndex: lower.index,
6655
+ upperIndex: upper.index,
6656
+ clauses: clauses
6657
+ } };
6658
+ };
6659
+ try {
6660
+ for (var lowerClauses_1 = __values(lowerClauses), lowerClauses_1_1 = lowerClauses_1.next(); !lowerClauses_1_1.done; lowerClauses_1_1 = lowerClauses_1.next()) {
6661
+ var lower = lowerClauses_1_1.value;
6662
+ var state_4 = _loop_6(lower);
6663
+ if (typeof state_4 === "object")
6664
+ return state_4.value;
6665
+ }
6666
+ }
6667
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
6668
+ finally {
6669
+ try {
6670
+ if (lowerClauses_1_1 && !lowerClauses_1_1.done && (_a = lowerClauses_1.return)) _a.call(lowerClauses_1);
6671
+ }
6672
+ finally { if (e_12) throw e_12.error; }
6673
+ }
6674
+ return null;
6675
+ }
6676
+ function isAssistantMonthDateFormat(format) {
6677
+ var normalized = normalizeOptionalString(format);
6678
+ if (!normalized) {
6679
+ return false;
6680
+ }
6681
+ if (!/%m/.test(normalized)) {
6682
+ return false;
6683
+ }
6684
+ return !/(%d|%j|%H|%I|%M|%S|%U|%V|%W|%w)/.test(normalized);
6685
+ }
6686
+ function collectAssistantMonthlyGroupDateFields(value, output) {
6687
+ if (Array.isArray(value)) {
6688
+ value.forEach(function (entry) { return collectAssistantMonthlyGroupDateFields(entry, output); });
6689
+ return;
6690
+ }
6691
+ if (!value || typeof value !== 'object') {
6692
+ return;
6693
+ }
6694
+ var dateToString = value.$dateToString;
6695
+ if (dateToString && typeof dateToString === 'object' && !Array.isArray(dateToString)) {
6696
+ var format = normalizeOptionalString(dateToString.format);
6697
+ var field = extractAssistantFieldPathFromOperand(dateToString.date);
6698
+ if (field && isAssistantMonthDateFormat(format)) {
6699
+ output.add(field);
6700
+ }
6701
+ }
6702
+ var dateTrunc = value.$dateTrunc;
6703
+ if (dateTrunc && typeof dateTrunc === 'object' && !Array.isArray(dateTrunc)) {
6704
+ var unit = normalizeOptionalString(dateTrunc.unit).toLowerCase();
6705
+ var field = extractAssistantFieldPathFromOperand(dateTrunc.date);
6706
+ if (field && unit === 'month') {
6707
+ output.add(field);
6708
+ }
6709
+ }
6710
+ var monthExpr = value.$month;
6711
+ if (monthExpr !== undefined) {
6712
+ var field = extractAssistantFieldPathFromOperand(monthExpr);
6713
+ if (field) {
6714
+ output.add(field);
6715
+ }
6716
+ }
6717
+ Object.keys(value).forEach(function (key) {
6718
+ collectAssistantMonthlyGroupDateFields(value[key], output);
6719
+ });
6720
+ }
6721
+ function resolveAssistantMonthlyGroupDateFields(pipeline) {
6722
+ var fields = new Set();
6723
+ var groupIndex = findAggregateGroupIndex(pipeline);
6724
+ if (groupIndex === -1) {
6725
+ return fields;
6726
+ }
6727
+ var groupStage = pipeline[groupIndex];
6728
+ if (!groupStage || typeof groupStage !== 'object' || !groupStage.$group || typeof groupStage.$group !== 'object') {
6729
+ return fields;
6730
+ }
6731
+ collectAssistantMonthlyGroupDateFields(groupStage.$group, fields);
6732
+ return fields;
6733
+ }
6734
+ function detectAssistantMonthWindowFromPipeline(pipeline) {
6735
+ var e_13, _a;
6736
+ var _b;
6737
+ var monthlyFields = resolveAssistantMonthlyGroupDateFields(pipeline);
6738
+ var scanMatch = function (match) {
6739
+ if (!match || typeof match !== 'object' || Array.isArray(match)) {
6740
+ return null;
6741
+ }
6742
+ if (!match.$expr || typeof match.$expr !== 'object') {
6743
+ return null;
6744
+ }
6745
+ return detectAssistantMonthWindowInExpr(match.$expr, monthlyFields);
6746
+ };
6747
+ try {
6748
+ for (var _c = __values((pipeline || [])), _d = _c.next(); !_d.done; _d = _c.next()) {
6749
+ var stage = _d.value;
6750
+ if (!stage || typeof stage !== 'object') {
6751
+ continue;
6752
+ }
6753
+ var directMatch = scanMatch(stage.$match);
6754
+ if (directMatch) {
6755
+ return directMatch;
6756
+ }
6757
+ var geoNearMatch = scanMatch((_b = stage.$geoNear) === null || _b === void 0 ? void 0 : _b.query);
6758
+ if (geoNearMatch) {
6759
+ return geoNearMatch;
6760
+ }
6761
+ }
6762
+ }
6763
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
6764
+ finally {
6765
+ try {
6766
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
6767
+ }
6768
+ finally { if (e_13) throw e_13.error; }
6769
+ }
6770
+ return null;
6771
+ }
6772
+ function normalizeAssistantMonthlyCalendarWindowPipeline(pipeline) {
6773
+ var monthlyFields = resolveAssistantMonthlyGroupDateFields(pipeline);
6774
+ if (!monthlyFields.size) {
6775
+ return pipeline;
6776
+ }
6777
+ return (pipeline || []).map(function (stage) {
6778
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
6779
+ return stage;
6780
+ }
6781
+ var rewriteMatch = function (match) {
6782
+ if (!match || typeof match !== 'object' || Array.isArray(match) || !match.$expr) {
6783
+ return match;
6784
+ }
6785
+ var detection = detectAssistantMonthWindowInExpr(match.$expr, monthlyFields);
6786
+ if (!detection || detection.mode !== 'rolling') {
6787
+ return match;
6788
+ }
6789
+ var nextClauses = detection.clauses.filter(function (_entry, index) { return (index !== detection.lowerIndex && index !== detection.upperIndex); });
6790
+ nextClauses.push({
6791
+ $gte: [
6792
+ "$".concat(detection.field),
6793
+ {
6794
+ $dateSubtract: {
6795
+ startDate: createAssistantNowMonthStartExpr(),
6796
+ unit: 'month',
6797
+ amount: detection.months
6798
+ }
6799
+ }
6800
+ ]
6801
+ }, {
6802
+ $lt: [
6803
+ "$".concat(detection.field),
6804
+ createAssistantNowMonthStartExpr()
6805
+ ]
6806
+ });
6807
+ return __assign(__assign({}, match), { $expr: nextClauses.length === 1 ? nextClauses[0] : { $and: nextClauses } });
6808
+ };
6809
+ var next = __assign({}, stage);
6810
+ if (next.$match && typeof next.$match === 'object') {
6811
+ next.$match = rewriteMatch(next.$match);
6812
+ }
6813
+ if (next.$geoNear && typeof next.$geoNear === 'object' && next.$geoNear.query) {
6814
+ next.$geoNear = __assign(__assign({}, next.$geoNear), { query: rewriteMatch(next.$geoNear.query) });
6815
+ }
6816
+ return next;
6817
+ });
6818
+ }
6427
6819
  function normalizeAssistantAggregatePipeline(pipeline, collection) {
6428
6820
  if (!Array.isArray(pipeline)) {
6429
6821
  return [];
6430
6822
  }
6431
6823
  var isInvoiceCollection = ['invoice', 'invoices', 'invoice-versions'].includes(String(collection || '').toLowerCase());
6432
- return pipeline
6824
+ var normalizedPipeline = pipeline
6433
6825
  .filter(function (stage) { return stage && typeof stage === 'object' && !Array.isArray(stage); })
6434
6826
  .map(function (stage) {
6435
6827
  var next = __assign({}, stage);
@@ -6447,6 +6839,7 @@ function normalizeAssistantAggregatePipeline(pipeline, collection) {
6447
6839
  }
6448
6840
  return normalizeAssistantNowExprPlaceholdersDeep(next);
6449
6841
  });
6842
+ return normalizeAssistantMonthlyCalendarWindowPipeline(normalizedPipeline);
6450
6843
  }
6451
6844
  function buildAssistantAggregatePipeline(query, pipeline) {
6452
6845
  var _a;
@@ -6575,7 +6968,7 @@ function matchContainsField(value, field) {
6575
6968
  });
6576
6969
  }
6577
6970
  function resolveAggregateCompletionFallback(pipeline) {
6578
- var e_12, _a;
6971
+ var e_14, _a;
6579
6972
  if (!Array.isArray(pipeline)) {
6580
6973
  return null;
6581
6974
  }
@@ -6588,7 +6981,7 @@ function resolveAggregateCompletionFallback(pipeline) {
6588
6981
  }
6589
6982
  var addFields = stage.$addFields;
6590
6983
  try {
6591
- for (var _b = (e_12 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
6984
+ for (var _b = (e_14 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
6592
6985
  var key = _c.value;
6593
6986
  if (!isCompletionFieldName(key)) {
6594
6987
  continue;
@@ -6602,12 +6995,12 @@ function resolveAggregateCompletionFallback(pipeline) {
6602
6995
  }
6603
6996
  }
6604
6997
  }
6605
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
6998
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
6606
6999
  finally {
6607
7000
  try {
6608
7001
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6609
7002
  }
6610
- finally { if (e_12) throw e_12.error; }
7003
+ finally { if (e_14) throw e_14.error; }
6611
7004
  }
6612
7005
  if (candidateField) {
6613
7006
  break;
@@ -6763,7 +7156,7 @@ function buildCompletionFallbackSources(field) {
6763
7156
  ]);
6764
7157
  }
6765
7158
  function resolveAggregateCompletionExprFallback(pipeline) {
6766
- var e_13, _a;
7159
+ var e_15, _a;
6767
7160
  if (!Array.isArray(pipeline)) {
6768
7161
  return null;
6769
7162
  }
@@ -6783,7 +7176,7 @@ function resolveAggregateCompletionExprFallback(pipeline) {
6783
7176
  }
6784
7177
  if (!candidateField) {
6785
7178
  try {
6786
- for (var _b = (e_13 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
7179
+ for (var _b = (e_15 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
6787
7180
  var key = _c.value;
6788
7181
  if (key.startsWith('$')) {
6789
7182
  continue;
@@ -6798,12 +7191,12 @@ function resolveAggregateCompletionExprFallback(pipeline) {
6798
7191
  }
6799
7192
  }
6800
7193
  }
6801
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
7194
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
6802
7195
  finally {
6803
7196
  try {
6804
7197
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6805
7198
  }
6806
- finally { if (e_13) throw e_13.error; }
7199
+ finally { if (e_15) throw e_15.error; }
6807
7200
  }
6808
7201
  }
6809
7202
  if (!candidateField) {
@@ -6973,7 +7366,7 @@ function isRegexMatchCondition(value) {
6973
7366
  return false;
6974
7367
  }
6975
7368
  function findRegexMatchInMatchObject(match, prefix) {
6976
- var e_14, _a, e_15, _b;
7369
+ var e_16, _a, e_17, _b;
6977
7370
  if (prefix === void 0) { prefix = ''; }
6978
7371
  if (Array.isArray(match)) {
6979
7372
  try {
@@ -6985,12 +7378,12 @@ function findRegexMatchInMatchObject(match, prefix) {
6985
7378
  }
6986
7379
  }
6987
7380
  }
6988
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
7381
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
6989
7382
  finally {
6990
7383
  try {
6991
7384
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
6992
7385
  }
6993
- finally { if (e_14) throw e_14.error; }
7386
+ finally { if (e_16) throw e_16.error; }
6994
7387
  }
6995
7388
  return null;
6996
7389
  }
@@ -7021,12 +7414,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7021
7414
  }
7022
7415
  }
7023
7416
  }
7024
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
7417
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
7025
7418
  finally {
7026
7419
  try {
7027
7420
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
7028
7421
  }
7029
- finally { if (e_15) throw e_15.error; }
7422
+ finally { if (e_17) throw e_17.error; }
7030
7423
  }
7031
7424
  return null;
7032
7425
  }
@@ -7250,7 +7643,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
7250
7643
  return results;
7251
7644
  }
7252
7645
  function findMatchConditionForField(match, targetField, prefix) {
7253
- var e_16, _a, e_17, _b;
7646
+ var e_18, _a, e_19, _b;
7254
7647
  if (prefix === void 0) { prefix = ''; }
7255
7648
  if (!match || typeof match !== 'object') {
7256
7649
  return undefined;
@@ -7265,12 +7658,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7265
7658
  }
7266
7659
  }
7267
7660
  }
7268
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
7661
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
7269
7662
  finally {
7270
7663
  try {
7271
7664
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
7272
7665
  }
7273
- finally { if (e_16) throw e_16.error; }
7666
+ finally { if (e_18) throw e_18.error; }
7274
7667
  }
7275
7668
  return undefined;
7276
7669
  }
@@ -7297,12 +7690,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7297
7690
  }
7298
7691
  }
7299
7692
  }
7300
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
7693
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
7301
7694
  finally {
7302
7695
  try {
7303
7696
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
7304
7697
  }
7305
- finally { if (e_17) throw e_17.error; }
7698
+ finally { if (e_19) throw e_19.error; }
7306
7699
  }
7307
7700
  return undefined;
7308
7701
  }
@@ -7345,7 +7738,7 @@ function detectIdLikeValue(value) {
7345
7738
  return false;
7346
7739
  }
7347
7740
  function detectChemicalIdFromProbe(probeDocs, fields) {
7348
- var e_18, _a, e_19, _b;
7741
+ var e_20, _a, e_21, _b;
7349
7742
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
7350
7743
  return false;
7351
7744
  }
@@ -7357,7 +7750,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7357
7750
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
7358
7751
  var doc = probeDocs_1_1.value;
7359
7752
  try {
7360
- for (var targets_1 = (e_19 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
7753
+ for (var targets_1 = (e_21 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
7361
7754
  var field = targets_1_1.value;
7362
7755
  var value = getValueAtPath(doc, field);
7363
7756
  if (Array.isArray(value)) {
@@ -7370,21 +7763,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7370
7763
  }
7371
7764
  }
7372
7765
  }
7373
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
7766
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
7374
7767
  finally {
7375
7768
  try {
7376
7769
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
7377
7770
  }
7378
- finally { if (e_19) throw e_19.error; }
7771
+ finally { if (e_21) throw e_21.error; }
7379
7772
  }
7380
7773
  }
7381
7774
  }
7382
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
7775
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
7383
7776
  finally {
7384
7777
  try {
7385
7778
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
7386
7779
  }
7387
- finally { if (e_18) throw e_18.error; }
7780
+ finally { if (e_20) throw e_20.error; }
7388
7781
  }
7389
7782
  return false;
7390
7783
  }
@@ -7605,8 +7998,8 @@ function buildChemicalIdFieldCandidates(field) {
7605
7998
  }
7606
7999
  function applyChemicalNameLookupFallbackToQuery(params) {
7607
8000
  return __awaiter(this, void 0, void 0, function () {
7608
- var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, chemicalFields, targetField, condition, regex, sampleDocs, collectionNames, candidates, _loop_6, candidates_2, candidates_2_1, candidate, state_4, e_20_1;
7609
- var e_20, _a;
8001
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, chemicalFields, targetField, condition, regex, sampleDocs, collectionNames, candidates, _loop_7, candidates_2, candidates_2_1, candidate, state_5, e_22_1;
8002
+ var e_22, _a;
7610
8003
  var _b;
7611
8004
  return __generator(this, function (_c) {
7612
8005
  switch (_c.label) {
@@ -7630,7 +8023,7 @@ function applyChemicalNameLookupFallbackToQuery(params) {
7630
8023
  case 1:
7631
8024
  collectionNames = _c.sent();
7632
8025
  candidates = resolveIdLookupCandidates('chemical', collectionNames);
7633
- _loop_6 = function (candidate) {
8026
+ _loop_7 = function (candidate) {
7634
8027
  var candidateHasClientScope, _d, candidateProbe, lookup, idFields, baseMatch, orConditions, nextMatch;
7635
8028
  return __generator(this, function (_e) {
7636
8029
  switch (_e.label) {
@@ -7708,25 +8101,25 @@ function applyChemicalNameLookupFallbackToQuery(params) {
7708
8101
  case 3:
7709
8102
  if (!!candidates_2_1.done) return [3 /*break*/, 6];
7710
8103
  candidate = candidates_2_1.value;
7711
- return [5 /*yield**/, _loop_6(candidate)];
8104
+ return [5 /*yield**/, _loop_7(candidate)];
7712
8105
  case 4:
7713
- state_4 = _c.sent();
7714
- if (typeof state_4 === "object")
7715
- return [2 /*return*/, state_4.value];
8106
+ state_5 = _c.sent();
8107
+ if (typeof state_5 === "object")
8108
+ return [2 /*return*/, state_5.value];
7716
8109
  _c.label = 5;
7717
8110
  case 5:
7718
8111
  candidates_2_1 = candidates_2.next();
7719
8112
  return [3 /*break*/, 3];
7720
8113
  case 6: return [3 /*break*/, 9];
7721
8114
  case 7:
7722
- e_20_1 = _c.sent();
7723
- e_20 = { error: e_20_1 };
8115
+ e_22_1 = _c.sent();
8116
+ e_22 = { error: e_22_1 };
7724
8117
  return [3 /*break*/, 9];
7725
8118
  case 8:
7726
8119
  try {
7727
8120
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
7728
8121
  }
7729
- finally { if (e_20) throw e_20.error; }
8122
+ finally { if (e_22) throw e_22.error; }
7730
8123
  return [7 /*endfinally*/];
7731
8124
  case 9: return [2 /*return*/, null];
7732
8125
  }
@@ -7820,8 +8213,8 @@ function lookupIdsForNameMatch(params) {
7820
8213
  }
7821
8214
  function applyIdLookupFallbackToQuery(params) {
7822
8215
  return __awaiter(this, void 0, void 0, function () {
7823
- var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, conditions, collectionNames, _a, conditions_1, conditions_1_1, condition, regex, baseToken, targetFieldType, nextValue, localNameField, candidates, candidates_3, candidates_3_1, candidate, candidateHasClientScope, _b, candidateProbe, lookup, targetFieldType, normalizedIds, idsForQuery, e_21_1, e_22_1;
7824
- var e_22, _c, e_21, _d;
8216
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, conditions, collectionNames, _a, conditions_1, conditions_1_1, condition, regex, baseToken, targetFieldType, nextValue, localNameField, candidates, candidates_3, candidates_3_1, candidate, candidateHasClientScope, _b, candidateProbe, lookup, targetFieldType, normalizedIds, idsForQuery, e_23_1, e_24_1;
8217
+ var e_24, _c, e_23, _d;
7825
8218
  var _e;
7826
8219
  return __generator(this, function (_f) {
7827
8220
  switch (_f.label) {
@@ -7891,7 +8284,7 @@ function applyIdLookupFallbackToQuery(params) {
7891
8284
  _f.label = 5;
7892
8285
  case 5:
7893
8286
  _f.trys.push([5, 14, 15, 16]);
7894
- candidates_3 = (e_21 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8287
+ candidates_3 = (e_23 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
7895
8288
  _f.label = 6;
7896
8289
  case 6:
7897
8290
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -7958,28 +8351,28 @@ function applyIdLookupFallbackToQuery(params) {
7958
8351
  return [3 /*break*/, 6];
7959
8352
  case 13: return [3 /*break*/, 16];
7960
8353
  case 14:
7961
- e_21_1 = _f.sent();
7962
- e_21 = { error: e_21_1 };
8354
+ e_23_1 = _f.sent();
8355
+ e_23 = { error: e_23_1 };
7963
8356
  return [3 /*break*/, 16];
7964
8357
  case 15:
7965
8358
  try {
7966
8359
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
7967
8360
  }
7968
- finally { if (e_21) throw e_21.error; }
8361
+ finally { if (e_23) throw e_23.error; }
7969
8362
  return [7 /*endfinally*/];
7970
8363
  case 16:
7971
8364
  conditions_1_1 = conditions_1.next();
7972
8365
  return [3 /*break*/, 4];
7973
8366
  case 17: return [3 /*break*/, 20];
7974
8367
  case 18:
7975
- e_22_1 = _f.sent();
7976
- e_22 = { error: e_22_1 };
8368
+ e_24_1 = _f.sent();
8369
+ e_24 = { error: e_24_1 };
7977
8370
  return [3 /*break*/, 20];
7978
8371
  case 19:
7979
8372
  try {
7980
8373
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
7981
8374
  }
7982
- finally { if (e_22) throw e_22.error; }
8375
+ finally { if (e_24) throw e_24.error; }
7983
8376
  return [7 /*endfinally*/];
7984
8377
  case 20: return [2 /*return*/, null];
7985
8378
  }
@@ -8831,7 +9224,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection) {
8831
9224
  throw new Error('AI assistant report builder bridge: Collection is not configured for report builder.');
8832
9225
  }
8833
9226
  function findQueryDateField(query) {
8834
- var e_23, _a, e_24, _b;
9227
+ var e_25, _a, e_26, _b;
8835
9228
  if (!query || typeof query !== 'object') {
8836
9229
  return null;
8837
9230
  }
@@ -8845,12 +9238,12 @@ function findQueryDateField(query) {
8845
9238
  }
8846
9239
  }
8847
9240
  }
8848
- catch (e_23_1) { e_23 = { error: e_23_1 }; }
9241
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
8849
9242
  finally {
8850
9243
  try {
8851
9244
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
8852
9245
  }
8853
- finally { if (e_23) throw e_23.error; }
9246
+ finally { if (e_25) throw e_25.error; }
8854
9247
  }
8855
9248
  return null;
8856
9249
  }
@@ -8869,12 +9262,12 @@ function findQueryDateField(query) {
8869
9262
  }
8870
9263
  }
8871
9264
  }
8872
- catch (e_24_1) { e_24 = { error: e_24_1 }; }
9265
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
8873
9266
  finally {
8874
9267
  try {
8875
9268
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
8876
9269
  }
8877
- finally { if (e_24) throw e_24.error; }
9270
+ finally { if (e_26) throw e_26.error; }
8878
9271
  }
8879
9272
  return null;
8880
9273
  }
@@ -9030,7 +9423,7 @@ function expandAggregateDateMatchFallback(pipeline) {
9030
9423
  if (!Array.isArray(pipeline)) {
9031
9424
  return null;
9032
9425
  }
9033
- var _loop_7 = function (i) {
9426
+ var _loop_8 = function (i) {
9034
9427
  var stage = pipeline[i];
9035
9428
  if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
9036
9429
  return "continue";
@@ -9078,9 +9471,9 @@ function expandAggregateDateMatchFallback(pipeline) {
9078
9471
  return { value: { pipeline: updated, fields: Array.from(addedFields) } };
9079
9472
  };
9080
9473
  for (var i = 0; i < pipeline.length; i += 1) {
9081
- var state_5 = _loop_7(i);
9082
- if (typeof state_5 === "object")
9083
- return state_5.value;
9474
+ var state_6 = _loop_8(i);
9475
+ if (typeof state_6 === "object")
9476
+ return state_6.value;
9084
9477
  }
9085
9478
  return null;
9086
9479
  }
@@ -9096,7 +9489,7 @@ function resolveQueryDateFieldFallback(query) {
9096
9489
  return { from: dateField, to: fallback };
9097
9490
  }
9098
9491
  function containsForbiddenMongoOperators(value) {
9099
- var e_25, _a;
9492
+ var e_27, _a;
9100
9493
  if (!value || typeof value !== 'object') {
9101
9494
  return false;
9102
9495
  }
@@ -9115,12 +9508,12 @@ function containsForbiddenMongoOperators(value) {
9115
9508
  }
9116
9509
  }
9117
9510
  }
9118
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
9511
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
9119
9512
  finally {
9120
9513
  try {
9121
9514
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9122
9515
  }
9123
- finally { if (e_25) throw e_25.error; }
9516
+ finally { if (e_27) throw e_27.error; }
9124
9517
  }
9125
9518
  return false;
9126
9519
  }
@@ -9555,8 +9948,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
9555
9948
  }
9556
9949
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
9557
9950
  return __awaiter(this, void 0, void 0, function () {
9558
- var _a, _b, _c, _d, message, payload, status_1, e_26_1;
9559
- var _e, e_26, _f, _g;
9951
+ var _a, _b, _c, _d, message, payload, status_1, e_28_1;
9952
+ var _e, e_28, _f, _g;
9560
9953
  return __generator(this, function (_h) {
9561
9954
  switch (_h.label) {
9562
9955
  case 0:
@@ -9583,8 +9976,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
9583
9976
  return [3 /*break*/, 1];
9584
9977
  case 4: return [3 /*break*/, 11];
9585
9978
  case 5:
9586
- e_26_1 = _h.sent();
9587
- e_26 = { error: e_26_1 };
9979
+ e_28_1 = _h.sent();
9980
+ e_28 = { error: e_28_1 };
9588
9981
  return [3 /*break*/, 11];
9589
9982
  case 6:
9590
9983
  _h.trys.push([6, , 9, 10]);
@@ -9595,7 +9988,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
9595
9988
  _h.label = 8;
9596
9989
  case 8: return [3 /*break*/, 10];
9597
9990
  case 9:
9598
- if (e_26) throw e_26.error;
9991
+ if (e_28) throw e_28.error;
9599
9992
  return [7 /*endfinally*/];
9600
9993
  case 10: return [7 /*endfinally*/];
9601
9994
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -10201,7 +10594,7 @@ function resolveAssistantPlannerEnabled() {
10201
10594
  return raw === undefined ? true : raw === true;
10202
10595
  }
10203
10596
  function resolveAssistantPlannerKnownRoutes() {
10204
- var e_27, _a;
10597
+ var e_29, _a;
10205
10598
  var _b;
10206
10599
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10207
10600
  var unique = new Set();
@@ -10214,12 +10607,12 @@ function resolveAssistantPlannerKnownRoutes() {
10214
10607
  }
10215
10608
  }
10216
10609
  }
10217
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
10610
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
10218
10611
  finally {
10219
10612
  try {
10220
10613
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
10221
10614
  }
10222
- finally { if (e_27) throw e_27.error; }
10615
+ finally { if (e_29) throw e_29.error; }
10223
10616
  }
10224
10617
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
10225
10618
  }
@@ -10462,7 +10855,7 @@ function normalizeRouteMatchKey(value) {
10462
10855
  return normalizeRouteKey(value).toLowerCase();
10463
10856
  }
10464
10857
  function buildClientRouteIndex() {
10465
- var e_28, _a;
10858
+ var e_30, _a;
10466
10859
  var _b;
10467
10860
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10468
10861
  var set = new Set();
@@ -10481,12 +10874,12 @@ function buildClientRouteIndex() {
10481
10874
  }
10482
10875
  }
10483
10876
  }
10484
- catch (e_28_1) { e_28 = { error: e_28_1 }; }
10877
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
10485
10878
  finally {
10486
10879
  try {
10487
10880
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
10488
10881
  }
10489
- finally { if (e_28) throw e_28.error; }
10882
+ finally { if (e_30) throw e_30.error; }
10490
10883
  }
10491
10884
  return { set: set, map: map, size: routes.length };
10492
10885
  }
@@ -10627,7 +11020,7 @@ function sanitizeAssistantResponse(value) {
10627
11020
  return normalizeAssistantRoutes(normalizedCurrency);
10628
11021
  }
10629
11022
  function evaluateAssistantGuardrails(message) {
10630
- var e_29, _a;
11023
+ var e_31, _a;
10631
11024
  var normalized = String(message || '').toLowerCase();
10632
11025
  var patterns = [
10633
11026
  {
@@ -10673,12 +11066,12 @@ function evaluateAssistantGuardrails(message) {
10673
11066
  }
10674
11067
  }
10675
11068
  }
10676
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
11069
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
10677
11070
  finally {
10678
11071
  try {
10679
11072
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
10680
11073
  }
10681
- finally { if (e_29) throw e_29.error; }
11074
+ finally { if (e_31) throw e_31.error; }
10682
11075
  }
10683
11076
  return null;
10684
11077
  }
@@ -10793,7 +11186,7 @@ function tokenizeArithmeticExpression(expression) {
10793
11186
  return tokens;
10794
11187
  }
10795
11188
  function evaluateArithmeticExpression(expression) {
10796
- var e_30, _a, e_31, _b;
11189
+ var e_32, _a, e_33, _b;
10797
11190
  var tokens = tokenizeArithmeticExpression(expression);
10798
11191
  if (!tokens || !tokens.length) {
10799
11192
  return null;
@@ -10850,12 +11243,12 @@ function evaluateArithmeticExpression(expression) {
10850
11243
  prevToken = token;
10851
11244
  }
10852
11245
  }
10853
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
11246
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
10854
11247
  finally {
10855
11248
  try {
10856
11249
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
10857
11250
  }
10858
- finally { if (e_30) throw e_30.error; }
11251
+ finally { if (e_32) throw e_32.error; }
10859
11252
  }
10860
11253
  while (ops.length) {
10861
11254
  var op = ops.pop();
@@ -10895,12 +11288,12 @@ function evaluateArithmeticExpression(expression) {
10895
11288
  stack.push(Number(token));
10896
11289
  }
10897
11290
  }
10898
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
11291
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
10899
11292
  finally {
10900
11293
  try {
10901
11294
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
10902
11295
  }
10903
- finally { if (e_31) throw e_31.error; }
11296
+ finally { if (e_33) throw e_33.error; }
10904
11297
  }
10905
11298
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
10906
11299
  return null;
@@ -11084,8 +11477,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
11084
11477
  }
11085
11478
  function readAttachmentContents(attachments) {
11086
11479
  return __awaiter(this, void 0, void 0, function () {
11087
- var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_32_1;
11088
- var e_32, _b;
11480
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_34_1;
11481
+ var e_34, _b;
11089
11482
  return __generator(this, function (_c) {
11090
11483
  switch (_c.label) {
11091
11484
  case 0:
@@ -11164,14 +11557,14 @@ function readAttachmentContents(attachments) {
11164
11557
  return [3 /*break*/, 2];
11165
11558
  case 10: return [3 /*break*/, 13];
11166
11559
  case 11:
11167
- e_32_1 = _c.sent();
11168
- e_32 = { error: e_32_1 };
11560
+ e_34_1 = _c.sent();
11561
+ e_34 = { error: e_34_1 };
11169
11562
  return [3 /*break*/, 13];
11170
11563
  case 12:
11171
11564
  try {
11172
11565
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
11173
11566
  }
11174
- finally { if (e_32) throw e_32.error; }
11567
+ finally { if (e_34) throw e_34.error; }
11175
11568
  return [7 /*endfinally*/];
11176
11569
  case 13: return [2 /*return*/, {
11177
11570
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -11412,7 +11805,7 @@ function estimateUsage(messages, responseText, model) {
11412
11805
  };
11413
11806
  }
11414
11807
  function evaluateGuardrails(message) {
11415
- var e_33, _a;
11808
+ var e_35, _a;
11416
11809
  var normalized = String(message || '').toLowerCase();
11417
11810
  var patterns = [
11418
11811
  { 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.' },
@@ -11434,12 +11827,12 @@ function evaluateGuardrails(message) {
11434
11827
  }
11435
11828
  }
11436
11829
  }
11437
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
11830
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
11438
11831
  finally {
11439
11832
  try {
11440
11833
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
11441
11834
  }
11442
- finally { if (e_33) throw e_33.error; }
11835
+ finally { if (e_35) throw e_35.error; }
11443
11836
  }
11444
11837
  return null;
11445
11838
  }