@resolveio/server-lib 22.0.20 → 22.0.22

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.
@@ -200,17 +200,33 @@ var AI_ASSISTANT_DATE_FALLBACKS = {
200
200
  date_created: 'createdAt',
201
201
  createdAt: 'date_created',
202
202
  date_invoice: 'date_invoiced',
203
- date_invoiced: 'date_invoice'
203
+ date_invoiced: 'date_invoice',
204
+ date_last: 'date_next',
205
+ date_next: 'date_last',
206
+ date_treated: 'date_scheduled',
207
+ date_scheduled: 'date_treated'
204
208
  };
205
209
  var AI_ASSISTANT_DATE_EXPANSION_FIELDS = [
206
210
  'date',
207
211
  'date_start',
208
212
  'date_end',
209
213
  'date_original',
214
+ 'date_next',
215
+ 'date_last',
216
+ 'date_scheduled',
217
+ 'date_treated',
218
+ 'date_completed',
219
+ 'date_closed',
220
+ 'date_due',
221
+ 'date_paid',
222
+ 'date_invoice',
223
+ 'date_invoiced',
224
+ 'date_updated',
210
225
  'date_created',
211
226
  'createdAt',
212
227
  'updatedAt'
213
228
  ];
229
+ var AI_ASSISTANT_DATE_EXPANSION_SCHEMA_MAX_FIELDS = 12;
214
230
  var AI_ASSISTANT_BLOCKED_COLLECTIONS = new Set([
215
231
  'user-groups',
216
232
  'logged-in-users',
@@ -498,6 +514,7 @@ var AI_ASSISTANT_SYSTEM_PROMPT = [
498
514
  '- For invoice data, set permissionView to an invoice-capable route (ex: /invoice/list).',
499
515
  '- Do not use /report/* routes as permissionView for data directives; use a module route that matches the collection.',
500
516
  '- For revenue/sales/billing questions, use invoices and sum paid_total (fallback to grand_total) with date_paid and Paid/Closed status when available.',
517
+ '- For blend ticket summaries, use product = blend_name (fallback chemical), total volume = chemical_recipe_quantity, and unit = lb when blend_in_pounds is true otherwise gal.',
501
518
  '- 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
519
  '- 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.',
503
520
  '- For relative date ranges (last/past/recent), include an upper bound <= $$NOW unless the user specifies a future end date.',
@@ -1462,10 +1479,10 @@ function executeAiAssistantCodexRun(payload, context) {
1462
1479
  insertResult = _d.sent();
1463
1480
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1464
1481
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1465
- var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, plannerPrompt, plannerStart, _b, responseText, directiveText, directive, directivePrompt, directiveStart, forcedDirective, _c, initialStart, directivePrompt, forcedStart, forcedDirective, _d, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _e, toolPayload, followupPrompt, followupStart, followupText, _f, error_2, error_3, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
1466
- var _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
1467
- return __generator(this, function (_v) {
1468
- switch (_v.label) {
1482
+ var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, requestedTimeGrain, enforceDatedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, plannerPrompt, plannerStart, _b, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, directivePrompt, directiveStart, forcedDirective, _c, initialStart, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _g, toolPayload, followupPrompt, followupStart, followupText, _h, error_2, error_3, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
1483
+ var _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2;
1484
+ return __generator(this, function (_3) {
1485
+ switch (_3.label) {
1469
1486
  case 0:
1470
1487
  runStart = Date.now();
1471
1488
  if (aiWorkerDebug) {
@@ -1497,6 +1514,10 @@ function executeAiAssistantCodexRun(payload, context) {
1497
1514
  requestClassification = classifyAssistantRequestType(message);
1498
1515
  dataQuestion = requestClassification.dataQuestion;
1499
1516
  lastDirective = null;
1517
+ requestedTimeGrain = null;
1518
+ enforceDatedDirective = false;
1519
+ datedDirectiveRetryUsed = false;
1520
+ datedDirectiveResolved = false;
1500
1521
  toolResponseDebug = null;
1501
1522
  toolError = null;
1502
1523
  termHints = [];
@@ -1533,17 +1554,17 @@ function executeAiAssistantCodexRun(payload, context) {
1533
1554
  codexUsage.output_tokens += outputTokens;
1534
1555
  codexUsage.total_tokens += inputTokens + outputTokens;
1535
1556
  };
1536
- contextRoute = normalizeOptionalString((_g = input === null || input === void 0 ? void 0 : input.context) === null || _g === void 0 ? void 0 : _g.route);
1537
- contextMode = normalizeOptionalString((_h = input === null || input === void 0 ? void 0 : input.context) === null || _h === void 0 ? void 0 : _h.mode);
1557
+ contextRoute = normalizeOptionalString((_j = input === null || input === void 0 ? void 0 : input.context) === null || _j === void 0 ? void 0 : _j.route);
1558
+ contextMode = normalizeOptionalString((_k = input === null || input === void 0 ? void 0 : input.context) === null || _k === void 0 ? void 0 : _k.mode);
1538
1559
  recordStep('Queued', { requestId: requestId || undefined });
1539
1560
  recordStep('Planning: request classification', {
1540
1561
  type: requestClassification.type,
1541
1562
  source: requestClassification.source,
1542
1563
  dataQuestion: dataQuestion
1543
1564
  });
1544
- _v.label = 1;
1565
+ _3.label = 1;
1545
1566
  case 1:
1546
- _v.trys.push([1, 34, 35, 36]);
1567
+ _3.trys.push([1, 42, 43, 44]);
1547
1568
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1548
1569
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1549
1570
  hintText = termExpansion.expanded || hintSeed;
@@ -1564,19 +1585,19 @@ function executeAiAssistantCodexRun(payload, context) {
1564
1585
  recordStep('Planning: term expansion', {
1565
1586
  termMatches: termExpansion.matches.length ? termExpansion.matches : undefined
1566
1587
  });
1567
- _v.label = 2;
1588
+ _3.label = 2;
1568
1589
  case 2:
1569
- _v.trys.push([2, 4, , 5]);
1590
+ _3.trys.push([2, 4, , 5]);
1570
1591
  dbName = resolveAssistantDatabaseName(undefined, input.mongo);
1571
1592
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
1572
1593
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
1573
1594
  case 3:
1574
- collectionNames = _v.sent();
1595
+ collectionNames = _3.sent();
1575
1596
  collectionHints = resolveCollectionHintsFromTokens(expandedTokens, collectionNames, 5);
1576
1597
  collectionRanking = buildCollectionRankingDebugFromTokens(expandedTokens, collectionNames, 8);
1577
1598
  return [3 /*break*/, 5];
1578
1599
  case 4:
1579
- _a = _v.sent();
1600
+ _a = _3.sent();
1580
1601
  collectionHints = [];
1581
1602
  collectionRanking = collectionRanking || ((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens)
1582
1603
  ? buildCollectionRankingDebugFromTokens(collectionTokenization.expandedTokens || [], [], 0)
@@ -1612,7 +1633,7 @@ function executeAiAssistantCodexRun(payload, context) {
1612
1633
  prompt_1 = buildAssistantCodexPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1613
1634
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
1614
1635
  case 6:
1615
- workspaceRoot = _v.sent();
1636
+ workspaceRoot = _3.sent();
1616
1637
  codexConfig = resolveCodexSettings({
1617
1638
  model: codexModel,
1618
1639
  fallbackModels: codexFallbackModels
@@ -1647,44 +1668,54 @@ function executeAiAssistantCodexRun(payload, context) {
1647
1668
  fieldHints: fieldHints,
1648
1669
  inputClientId: input.id_client
1649
1670
  });
1650
- _v.label = 7;
1671
+ _3.label = 7;
1651
1672
  case 7:
1652
- _v.trys.push([7, 9, , 10]);
1673
+ _3.trys.push([7, 9, , 10]);
1653
1674
  plannerStart = Date.now();
1654
1675
  return [4 /*yield*/, runCodexInWorkerThread(plannerPrompt, runOptions, codexConfig, streamProgress)];
1655
1676
  case 8:
1656
- plannerRaw = _v.sent();
1677
+ plannerRaw = _3.sent();
1657
1678
  accumulateCodexUsage(plannerPrompt, plannerRaw);
1658
1679
  timingBreakdown.plannerMs = Date.now() - plannerStart;
1659
1680
  plannerOutput = parseJsonObject(plannerRaw);
1660
1681
  recordStep('Planning: planner result', { parsed: !!plannerOutput });
1661
1682
  return [3 /*break*/, 10];
1662
1683
  case 9:
1663
- _b = _v.sent();
1684
+ _b = _3.sent();
1664
1685
  recordStep('Planning: planner result', { parsed: false });
1665
1686
  return [3 /*break*/, 10];
1666
1687
  case 10:
1667
1688
  requestClassification = classifyAssistantRequestType(message, plannerOutput || undefined);
1668
1689
  dataQuestion = requestClassification.dataQuestion;
1690
+ requestedTimeGrain = resolveAssistantRequestedTimeGrain(message, plannerOutput || undefined);
1691
+ enforceDatedDirective = shouldEnforceAssistantDatedDirective(message, plannerOutput || undefined, requestClassification);
1692
+ directiveStyleHint = buildAssistantDirectiveStyleHint({
1693
+ enforceDated: enforceDatedDirective,
1694
+ requestedTimeGrain: requestedTimeGrain
1695
+ });
1696
+ directivePromptMode = enforceDatedDirective ? 'aggregate_only' : 'any';
1697
+ datedDirectiveRetryUsed = false;
1669
1698
  recordStep('Planning: request classification', {
1670
1699
  type: requestClassification.type,
1671
1700
  source: requestClassification.source,
1672
1701
  plannerIntentType: requestClassification.plannerIntentType || undefined,
1673
- dataQuestion: dataQuestion
1702
+ dataQuestion: dataQuestion,
1703
+ reportStyle: enforceDatedDirective ? 'dated' : undefined,
1704
+ timeGrain: requestedTimeGrain || undefined
1674
1705
  });
1675
1706
  responseText = '';
1676
1707
  directiveText = '';
1677
1708
  directive = null;
1678
1709
  if (!dataQuestion) return [3 /*break*/, 14];
1679
1710
  recordStep('Directive: determine tool', { type: 'data-question' });
1680
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1681
- _v.label = 11;
1711
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1712
+ _3.label = 11;
1682
1713
  case 11:
1683
- _v.trys.push([11, 13, , 14]);
1714
+ _3.trys.push([11, 13, , 14]);
1684
1715
  directiveStart = Date.now();
1685
1716
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1686
1717
  case 12:
1687
- directiveText = _v.sent();
1718
+ directiveText = _3.sent();
1688
1719
  accumulateCodexUsage(directivePrompt, directiveText);
1689
1720
  timingBreakdown.directiveMs = Date.now() - directiveStart;
1690
1721
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1692,17 +1723,17 @@ function executeAiAssistantCodexRun(payload, context) {
1692
1723
  directive = forcedDirective;
1693
1724
  directiveSource = 'model';
1694
1725
  lastDirective = forcedDirective;
1695
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_j = directive.payload) === null || _j === void 0 ? void 0 : _j.collection) || '');
1726
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.collection) || '');
1696
1727
  recordStep('Directive resolved', {
1697
1728
  source: directiveSource,
1698
1729
  type: directive.type,
1699
- collection: normalizeOptionalString((_k = directive.payload) === null || _k === void 0 ? void 0 : _k.collection) || undefined,
1700
- permissionView: normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.permissionView) || undefined
1730
+ collection: normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1731
+ permissionView: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.permissionView) || undefined
1701
1732
  });
1702
1733
  }
1703
1734
  return [3 /*break*/, 14];
1704
1735
  case 13:
1705
- _c = _v.sent();
1736
+ _c = _3.sent();
1706
1737
  return [3 /*break*/, 14];
1707
1738
  case 14:
1708
1739
  if (!!directive) return [3 /*break*/, 16];
@@ -1710,33 +1741,33 @@ function executeAiAssistantCodexRun(payload, context) {
1710
1741
  initialStart = Date.now();
1711
1742
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
1712
1743
  case 15:
1713
- responseText = _v.sent();
1744
+ responseText = _3.sent();
1714
1745
  accumulateCodexUsage(prompt_1, responseText);
1715
1746
  timingBreakdown.initialResponseMs = Date.now() - initialStart;
1716
1747
  directive = extractAssistantMongoDirective(responseText);
1717
1748
  if (directive) {
1718
1749
  directiveSource = 'model';
1719
1750
  lastDirective = directive;
1720
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || '');
1751
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || '');
1721
1752
  recordStep('Directive resolved', {
1722
1753
  source: directiveSource,
1723
1754
  type: directive.type,
1724
- collection: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.collection) || undefined,
1725
- permissionView: normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.permissionView) || undefined
1755
+ collection: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || undefined,
1756
+ permissionView: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.permissionView) || undefined
1726
1757
  });
1727
1758
  }
1728
- _v.label = 16;
1759
+ _3.label = 16;
1729
1760
  case 16:
1730
1761
  if (!(!directive && dataQuestion)) return [3 /*break*/, 20];
1731
1762
  recordStep('Directive: forced retry', { mode: 'directive-only' });
1732
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1733
- _v.label = 17;
1763
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1764
+ _3.label = 17;
1734
1765
  case 17:
1735
- _v.trys.push([17, 19, , 20]);
1766
+ _3.trys.push([17, 19, , 20]);
1736
1767
  forcedStart = Date.now();
1737
1768
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1738
1769
  case 18:
1739
- directiveText = _v.sent();
1770
+ directiveText = _3.sent();
1740
1771
  accumulateCodexUsage(directivePrompt, directiveText);
1741
1772
  timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
1742
1773
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1744,26 +1775,108 @@ function executeAiAssistantCodexRun(payload, context) {
1744
1775
  directive = forcedDirective;
1745
1776
  directiveSource = 'forced';
1746
1777
  lastDirective = forcedDirective;
1747
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || '');
1778
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || '');
1748
1779
  recordStep('Directive resolved', {
1749
1780
  source: directiveSource,
1750
1781
  type: directive.type,
1751
- collection: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.collection) || undefined,
1752
- permissionView: normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.permissionView) || undefined
1782
+ collection: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection) || undefined,
1783
+ permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || undefined
1753
1784
  });
1754
1785
  }
1755
1786
  return [3 /*break*/, 20];
1756
1787
  case 19:
1757
- _d = _v.sent();
1788
+ _d = _3.sent();
1758
1789
  return [3 /*break*/, 20];
1759
1790
  case 20:
1791
+ if (!(directive && enforceDatedDirective && !isAssistantDirectiveDated(directive))) return [3 /*break*/, 24];
1792
+ recordStep('Directive: dated retry', {
1793
+ currentType: directive.type,
1794
+ timeGrain: requestedTimeGrain || undefined
1795
+ });
1796
+ strictDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1797
+ enforceDated: true,
1798
+ requestedTimeGrain: requestedTimeGrain,
1799
+ strict: true
1800
+ }), 'aggregate_only');
1801
+ _3.label = 21;
1802
+ case 21:
1803
+ _3.trys.push([21, 23, , 24]);
1804
+ strictStart = Date.now();
1805
+ return [4 /*yield*/, runCodexInWorkerThread(strictDirectivePrompt, runOptions, codexConfig, streamProgress)];
1806
+ case 22:
1807
+ strictDirectiveText = _3.sent();
1808
+ accumulateCodexUsage(strictDirectivePrompt, strictDirectiveText);
1809
+ timingBreakdown.forcedDirectiveMs += Date.now() - strictStart;
1810
+ strictDirective = extractAssistantMongoDirective(strictDirectiveText);
1811
+ strictDirectiveIsDated = strictDirective ? isAssistantDirectiveDated(strictDirective) : false;
1812
+ shouldUseStrictDirective = !!strictDirective && strictDirective.type === 'aggregate';
1813
+ if (shouldUseStrictDirective && strictDirective) {
1814
+ directive = strictDirective;
1815
+ directiveSource = 'forced';
1816
+ lastDirective = strictDirective;
1817
+ datedDirectiveRetryUsed = true;
1818
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || '');
1819
+ recordStep('Directive resolved', {
1820
+ source: directiveSource,
1821
+ type: directive.type,
1822
+ collection: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.collection) || undefined,
1823
+ permissionView: normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.permissionView) || undefined,
1824
+ reportStyle: strictDirectiveIsDated ? 'dated' : 'aggregate_fallback',
1825
+ timeGrain: requestedTimeGrain || undefined
1826
+ });
1827
+ }
1828
+ return [3 /*break*/, 24];
1829
+ case 23:
1830
+ _e = _3.sent();
1831
+ return [3 /*break*/, 24];
1832
+ case 24:
1833
+ if (!(directive && enforceDatedDirective && directive.type === 'read')) return [3 /*break*/, 28];
1834
+ recordStep('Directive: dated guard retry', {
1835
+ currentType: directive.type,
1836
+ timeGrain: requestedTimeGrain || undefined
1837
+ });
1838
+ guardDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1839
+ enforceDated: true,
1840
+ requestedTimeGrain: requestedTimeGrain,
1841
+ strict: true
1842
+ }), 'aggregate_only');
1843
+ _3.label = 25;
1844
+ case 25:
1845
+ _3.trys.push([25, 27, , 28]);
1846
+ guardStart = Date.now();
1847
+ return [4 /*yield*/, runCodexInWorkerThread(guardDirectivePrompt, runOptions, codexConfig, streamProgress)];
1848
+ case 26:
1849
+ guardDirectiveText = _3.sent();
1850
+ accumulateCodexUsage(guardDirectivePrompt, guardDirectiveText);
1851
+ timingBreakdown.forcedDirectiveMs += Date.now() - guardStart;
1852
+ guardDirective = extractAssistantMongoDirective(guardDirectiveText);
1853
+ if (guardDirective && guardDirective.type === 'aggregate') {
1854
+ directive = guardDirective;
1855
+ directiveSource = 'forced';
1856
+ lastDirective = guardDirective;
1857
+ datedDirectiveRetryUsed = true;
1858
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || '');
1859
+ recordStep('Directive resolved', {
1860
+ source: directiveSource,
1861
+ type: directive.type,
1862
+ collection: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.collection) || undefined,
1863
+ permissionView: normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.permissionView) || undefined,
1864
+ reportStyle: isAssistantDirectiveDated(guardDirective) ? 'dated' : 'aggregate_fallback',
1865
+ timeGrain: requestedTimeGrain || undefined
1866
+ });
1867
+ }
1868
+ return [3 /*break*/, 28];
1869
+ case 27:
1870
+ _f = _3.sent();
1871
+ return [3 /*break*/, 28];
1872
+ case 28:
1760
1873
  if (directive) {
1761
- requestedCollection = normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection);
1874
+ requestedCollection = normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection);
1762
1875
  collectionOverride = resolveCollectionOverrideWithContext({
1763
1876
  message: message,
1764
1877
  collectionRanking: collectionRanking,
1765
1878
  requestedCollection: requestedCollection,
1766
- permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || contextRoute,
1879
+ permissionView: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.permissionView) || contextRoute,
1767
1880
  collectionNames: collectionNames
1768
1881
  });
1769
1882
  if (collectionOverride) {
@@ -1775,11 +1888,12 @@ function executeAiAssistantCodexRun(payload, context) {
1775
1888
  });
1776
1889
  }
1777
1890
  }
1891
+ datedDirectiveResolved = directive ? isAssistantDirectiveDated(directive) : false;
1778
1892
  cleanedResponseText = (directive === null || directive === void 0 ? void 0 : directive.cleaned) || responseText;
1779
1893
  if (cleanedResponseText) {
1780
1894
  assistantContent = sanitizeAssistantResponse(cleanedResponseText);
1781
1895
  }
1782
- if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 32];
1896
+ if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 40];
1783
1897
  effectiveDirective = collectionOverride
1784
1898
  ? __assign(__assign({}, directive), { payload: __assign(__assign({}, (directive.payload || {})), { collection: collectionOverride.to }) }) : directive;
1785
1899
  toolRequest = buildAssistantToolRequest(effectiveDirective, input);
@@ -1789,21 +1903,21 @@ function executeAiAssistantCodexRun(payload, context) {
1789
1903
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
1790
1904
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
1791
1905
  });
1792
- _v.label = 21;
1793
- case 21:
1794
- _v.trys.push([21, 30, , 31]);
1906
+ _3.label = 29;
1907
+ case 29:
1908
+ _3.trys.push([29, 38, , 39]);
1795
1909
  toolStart = Date.now();
1796
- if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 23];
1910
+ if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 31];
1797
1911
  return [4 /*yield*/, executeAiAssistantReportBuilderAggregate(toolRequest, context)];
1798
- case 22:
1799
- _e = _v.sent();
1800
- return [3 /*break*/, 25];
1801
- case 23: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
1802
- case 24:
1803
- _e = _v.sent();
1804
- _v.label = 25;
1805
- case 25:
1806
- toolResponse = _e;
1912
+ case 30:
1913
+ _g = _3.sent();
1914
+ return [3 /*break*/, 33];
1915
+ case 31: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
1916
+ case 32:
1917
+ _g = _3.sent();
1918
+ _3.label = 33;
1919
+ case 33:
1920
+ toolResponse = _g;
1807
1921
  timingBreakdown.toolMs = Date.now() - toolStart;
1808
1922
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
1809
1923
  ? toolResponse.debug
@@ -1818,43 +1932,43 @@ function executeAiAssistantCodexRun(payload, context) {
1818
1932
  progressTracker.push('Drafting response');
1819
1933
  recordStep('Drafting response');
1820
1934
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
1821
- _v.label = 26;
1822
- case 26:
1823
- _v.trys.push([26, 28, , 29]);
1935
+ _3.label = 34;
1936
+ case 34:
1937
+ _3.trys.push([34, 36, , 37]);
1824
1938
  followupStart = Date.now();
1825
1939
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
1826
- case 27:
1827
- followupText = _v.sent();
1940
+ case 35:
1941
+ followupText = _3.sent();
1828
1942
  accumulateCodexUsage(followupPrompt, followupText);
1829
1943
  timingBreakdown.followupMs = Date.now() - followupStart;
1830
1944
  assistantContent = sanitizeAssistantResponse(followupText);
1831
1945
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
1832
- return [3 /*break*/, 29];
1833
- case 28:
1834
- _f = _v.sent();
1946
+ return [3 /*break*/, 37];
1947
+ case 36:
1948
+ _h = _3.sent();
1835
1949
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
1836
- return [3 /*break*/, 29];
1837
- case 29: return [3 /*break*/, 31];
1838
- case 30:
1839
- error_2 = _v.sent();
1950
+ return [3 /*break*/, 37];
1951
+ case 37: return [3 /*break*/, 39];
1952
+ case 38:
1953
+ error_2 = _3.sent();
1840
1954
  assistantContent = buildAssistantToolErrorMessage(error_2);
1841
1955
  toolError = error_2;
1842
- return [3 /*break*/, 31];
1843
- case 31: return [3 /*break*/, 33];
1844
- case 32:
1956
+ return [3 /*break*/, 39];
1957
+ case 39: return [3 /*break*/, 41];
1958
+ case 40:
1845
1959
  progressTracker.push('Drafting response');
1846
1960
  recordStep('Drafting response');
1847
- _v.label = 33;
1848
- case 33: return [3 /*break*/, 36];
1849
- case 34:
1850
- error_3 = _v.sent();
1961
+ _3.label = 41;
1962
+ case 41: return [3 /*break*/, 44];
1963
+ case 42:
1964
+ error_3 = _3.sent();
1851
1965
  assistantContent = buildAssistantCodexErrorMessage(error_3);
1852
1966
  recordStep('Error', { message: normalizeOptionalString(error_3 === null || error_3 === void 0 ? void 0 : error_3.message) || 'Unknown error' });
1853
- return [3 /*break*/, 36];
1854
- case 35:
1967
+ return [3 /*break*/, 44];
1968
+ case 43:
1855
1969
  progressTracker.stop();
1856
1970
  return [7 /*endfinally*/];
1857
- case 36:
1971
+ case 44:
1858
1972
  if (!assistantContent) {
1859
1973
  assistantContent = buildAssistantCodexErrorMessage(null);
1860
1974
  }
@@ -1890,6 +2004,10 @@ function executeAiAssistantCodexRun(payload, context) {
1890
2004
  requestTypeSource: requestClassification.source,
1891
2005
  plannerIntentType: requestClassification.plannerIntentType,
1892
2006
  dataQuestion: dataQuestion,
2007
+ reportStyleIntent: enforceDatedDirective ? 'dated' : null,
2008
+ requestedTimeGrain: requestedTimeGrain,
2009
+ datedDirectiveRetryUsed: datedDirectiveRetryUsed,
2010
+ datedDirectiveResolved: datedDirectiveResolved,
1893
2011
  directive: lastDirective,
1894
2012
  directiveSource: directiveSource,
1895
2013
  toolResult: toolResult,
@@ -1940,14 +2058,14 @@ function executeAiAssistantCodexRun(payload, context) {
1940
2058
  output_tokens: codexUsage.output_tokens,
1941
2059
  total_tokens: codexUsage.total_tokens
1942
2060
  } : null;
1943
- if (!finalUsage) return [3 /*break*/, 41];
2061
+ if (!finalUsage) return [3 /*break*/, 49];
1944
2062
  return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
1945
- case 37:
1946
- usageClientId = _v.sent();
1947
- if (!usageClientId) return [3 /*break*/, 41];
1948
- _v.label = 38;
1949
- case 38:
1950
- _v.trys.push([38, 40, , 41]);
2063
+ case 45:
2064
+ usageClientId = _3.sent();
2065
+ if (!usageClientId) return [3 /*break*/, 49];
2066
+ _3.label = 46;
2067
+ case 46:
2068
+ _3.trys.push([46, 48, , 49]);
1951
2069
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
1952
2070
  id_client: usageClientId,
1953
2071
  model: finalUsage.model,
@@ -1958,16 +2076,16 @@ function executeAiAssistantCodexRun(payload, context) {
1958
2076
  id_request: requestId || undefined,
1959
2077
  id_conversation: conversation._id
1960
2078
  })];
1961
- case 39:
1962
- _v.sent();
1963
- return [3 /*break*/, 41];
1964
- case 40:
1965
- usageError_1 = _v.sent();
2079
+ case 47:
2080
+ _3.sent();
2081
+ return [3 /*break*/, 49];
2082
+ case 48:
2083
+ usageError_1 = _3.sent();
1966
2084
  console.error(new Date(), 'Failed to record codex usage', usageError_1);
1967
- return [3 /*break*/, 41];
1968
- case 41:
2085
+ return [3 /*break*/, 49];
2086
+ case 49:
1969
2087
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
1970
- if (!assistantMessageId) return [3 /*break*/, 43];
2088
+ if (!assistantMessageId) return [3 /*break*/, 51];
1971
2089
  setPayload = {
1972
2090
  content: assistantContent,
1973
2091
  metadata: finalMetadata,
@@ -1979,18 +2097,18 @@ function executeAiAssistantCodexRun(payload, context) {
1979
2097
  return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: assistantMessageId }, {
1980
2098
  $set: setPayload
1981
2099
  })];
1982
- case 42:
1983
- _v.sent();
1984
- _v.label = 43;
1985
- case 43: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
1986
- case 44:
1987
- _v.sent();
1988
- if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 46];
2100
+ case 50:
2101
+ _3.sent();
2102
+ _3.label = 51;
2103
+ case 51: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2104
+ case 52:
2105
+ _3.sent();
2106
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 54];
1989
2107
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
1990
- case 45:
1991
- _v.sent();
1992
- _v.label = 46;
1993
- case 46: return [2 /*return*/, finalAssistantDoc];
2108
+ case 53:
2109
+ _3.sent();
2110
+ _3.label = 54;
2111
+ case 54: return [2 /*return*/, finalAssistantDoc];
1994
2112
  }
1995
2113
  });
1996
2114
  }); });
@@ -2125,7 +2243,7 @@ function executeAiAssistantMongoRead(payload, context) {
2125
2243
  _q.label = 8;
2126
2244
  case 8:
2127
2245
  if (!!documents.length) return [3 /*break*/, 10];
2128
- expanded = expandQueryDateFallbacks(executedQuery);
2246
+ expanded = expandQueryDateFallbacks(executedQuery, schemaFields);
2129
2247
  if (!expanded) return [3 /*break*/, 10];
2130
2248
  fallbackMeta.dateFieldsExpanded = {
2131
2249
  fields: expanded.fields,
@@ -2668,7 +2786,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
2668
2786
  _q.label = 10;
2669
2787
  case 10:
2670
2788
  if (!!documents.length) return [3 /*break*/, 12];
2671
- expanded = expandAggregateDateMatchFallback(executedPipeline);
2789
+ expanded = expandAggregateDateMatchFallback(executedPipeline, schemaFields);
2672
2790
  if (!expanded) return [3 /*break*/, 12];
2673
2791
  fallbackMeta.dateFieldsExpanded = {
2674
2792
  fields: expanded.fields,
@@ -3978,7 +4096,7 @@ function applyAssistantVerificationNotes(value, toolResult) {
3978
4096
  return content || value || '';
3979
4097
  }
3980
4098
  var normalizedLower = String(content || '').toLowerCase();
3981
- var missing = warnings.filter(function (warning) { return !normalizedLower.includes(String(warning).toLowerCase()); });
4099
+ var missing = warnings.filter(function (warning) { return !hasAssistantEquivalentVerificationWarning(normalizedLower, warning); });
3982
4100
  if (!missing.length) {
3983
4101
  return content || value || '';
3984
4102
  }
@@ -3989,6 +4107,29 @@ function applyAssistantVerificationNotes(value, toolResult) {
3989
4107
  }
3990
4108
  return "".concat(content, "\n\n").concat(noteLines.join('\n')).trim();
3991
4109
  }
4110
+ function hasAssistantEquivalentVerificationWarning(contentLower, warning) {
4111
+ var warningLower = normalizeOptionalString(warning).toLowerCase();
4112
+ if (!warningLower) {
4113
+ return false;
4114
+ }
4115
+ if (contentLower.includes(warningLower)) {
4116
+ return true;
4117
+ }
4118
+ if (!warningLower.includes('changes monthly totals by')) {
4119
+ return false;
4120
+ }
4121
+ var pctMatch = warningLower.match(/([0-9]+(?:\.[0-9]+)?)%/);
4122
+ if (!pctMatch) {
4123
+ return false;
4124
+ }
4125
+ if (!/date[_\s-]?paid/.test(warningLower) || !/date[_\s-]?invoice/.test(warningLower)) {
4126
+ return false;
4127
+ }
4128
+ return contentLower.includes('changes monthly totals by')
4129
+ && contentLower.includes("".concat(pctMatch[1], "%"))
4130
+ && /date[_\s-]?paid/.test(contentLower)
4131
+ && /date[_\s-]?invoice/.test(contentLower);
4132
+ }
3992
4133
  function applyAssistantDatedReportWindow(value, toolResult) {
3993
4134
  var content = normalizeOptionalString(value);
3994
4135
  var window = resolveAssistantDatedReportWindow(toolResult);
@@ -4105,6 +4246,18 @@ function buildAssistantDebugPayload(params) {
4105
4246
  if (params.dataQuestion) {
4106
4247
  notes.push('Detected a data request; tool call required.');
4107
4248
  }
4249
+ if (params.reportStyleIntent === 'dated') {
4250
+ notes.push("Report style intent: dated".concat(params.requestedTimeGrain ? " (".concat(params.requestedTimeGrain, ")") : '', "."));
4251
+ if (params.datedDirectiveRetryUsed) {
4252
+ notes.push('Retried directive generation to enforce dated report style.');
4253
+ }
4254
+ if (params.datedDirectiveResolved) {
4255
+ notes.push('Directive includes time-based aggregate grouping.');
4256
+ }
4257
+ else {
4258
+ notes.push('Directive did not include explicit time-based grouping.');
4259
+ }
4260
+ }
4108
4261
  if (params.directiveSource === 'forced') {
4109
4262
  notes.push('Assistant response omitted a REPORT_BUILDER_* directive; ran a directive-only pass.');
4110
4263
  }
@@ -4240,6 +4393,10 @@ function buildAssistantDebugPayload(params) {
4240
4393
  requestTypeSource: params.requestTypeSource,
4241
4394
  plannerIntentType: params.plannerIntentType || undefined,
4242
4395
  dataQuestion: params.dataQuestion,
4396
+ reportStyleIntent: params.reportStyleIntent || undefined,
4397
+ timeGrain: params.requestedTimeGrain || undefined,
4398
+ datedDirectiveRetryUsed: params.datedDirectiveRetryUsed === true ? true : undefined,
4399
+ datedDirectiveResolved: params.datedDirectiveResolved === true ? true : undefined,
4243
4400
  directiveSource: params.directiveSource
4244
4401
  },
4245
4402
  directive: directive ? {
@@ -5686,13 +5843,138 @@ function flattenForTable(doc, options) {
5686
5843
  });
5687
5844
  return result;
5688
5845
  }
5846
+ function normalizeAssistantComparableDateDisplayValue(value) {
5847
+ if (value === null || value === undefined) {
5848
+ return '';
5849
+ }
5850
+ if (value instanceof Date) {
5851
+ return Number.isNaN(value.getTime()) ? '' : value.toISOString();
5852
+ }
5853
+ if (typeof value === 'number' && Number.isFinite(value)) {
5854
+ var epochMs = value >= 1e11 ? value : value >= 1e9 ? value * 1000 : null;
5855
+ if (epochMs !== null) {
5856
+ var parsed_1 = new Date(epochMs);
5857
+ if (!Number.isNaN(parsed_1.getTime())) {
5858
+ return parsed_1.toISOString();
5859
+ }
5860
+ }
5861
+ return String(value);
5862
+ }
5863
+ var text = String(value).trim();
5864
+ if (!text) {
5865
+ return '';
5866
+ }
5867
+ var parsed = Date.parse(text);
5868
+ if (!Number.isNaN(parsed)) {
5869
+ return new Date(parsed).toISOString();
5870
+ }
5871
+ return text.toLowerCase();
5872
+ }
5873
+ function shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField) {
5874
+ var preferredNonEmpty = 0;
5875
+ var candidateNonEmpty = 0;
5876
+ var overlap = 0;
5877
+ var equalOverlap = 0;
5878
+ rows.forEach(function (row) {
5879
+ var preferredValue = row === null || row === void 0 ? void 0 : row[preferredField];
5880
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
5881
+ var preferredHasValue = !isEmptyDisplayValue(preferredValue);
5882
+ var candidateHasValue = !isEmptyDisplayValue(candidateValue);
5883
+ if (preferredHasValue) {
5884
+ preferredNonEmpty += 1;
5885
+ }
5886
+ if (candidateHasValue) {
5887
+ candidateNonEmpty += 1;
5888
+ }
5889
+ if (preferredHasValue && candidateHasValue) {
5890
+ overlap += 1;
5891
+ if (normalizeAssistantComparableDateDisplayValue(preferredValue)
5892
+ === normalizeAssistantComparableDateDisplayValue(candidateValue)) {
5893
+ equalOverlap += 1;
5894
+ }
5895
+ }
5896
+ });
5897
+ if (!candidateNonEmpty) {
5898
+ return false;
5899
+ }
5900
+ if (!preferredNonEmpty) {
5901
+ return true;
5902
+ }
5903
+ if (!overlap) {
5904
+ return false;
5905
+ }
5906
+ return (equalOverlap / overlap) >= 0.8;
5907
+ }
5908
+ function coalesceAssistantDisplayDuplicateFields(rowsRaw) {
5909
+ if (!Array.isArray(rowsRaw) || !rowsRaw.length) {
5910
+ return Array.isArray(rowsRaw) ? rowsRaw : [];
5911
+ }
5912
+ var rows = rowsRaw.map(function (row) { return (__assign({}, (row || {}))); });
5913
+ var collectKeys = function () {
5914
+ var keySet = new Set();
5915
+ rows.forEach(function (row) {
5916
+ Object.keys(row || {}).forEach(function (key) {
5917
+ if (key) {
5918
+ keySet.add(key);
5919
+ }
5920
+ });
5921
+ });
5922
+ return keySet;
5923
+ };
5924
+ var keys = collectKeys();
5925
+ Array.from(keys).forEach(function (key) {
5926
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
5927
+ if (!leaf || !/_string$/i.test(leaf)) {
5928
+ return;
5929
+ }
5930
+ var baseLeaf = leaf.replace(/_string$/i, '');
5931
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
5932
+ if (!keys.has(basePath)) {
5933
+ return;
5934
+ }
5935
+ rows.forEach(function (row) {
5936
+ var stringValue = row === null || row === void 0 ? void 0 : row[key];
5937
+ if (!isEmptyDisplayValue(stringValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[basePath])) {
5938
+ row[basePath] = stringValue;
5939
+ }
5940
+ delete row[key];
5941
+ });
5942
+ });
5943
+ keys = collectKeys();
5944
+ var mergeDateGroup = function (preferredOrder) {
5945
+ var preferredField = preferredOrder.find(function (field) { return keys.has(field); });
5946
+ if (!preferredField) {
5947
+ return;
5948
+ }
5949
+ preferredOrder.forEach(function (candidateField) {
5950
+ if (candidateField === preferredField || !keys.has(candidateField)) {
5951
+ return;
5952
+ }
5953
+ if (!shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField)) {
5954
+ return;
5955
+ }
5956
+ rows.forEach(function (row) {
5957
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
5958
+ if (!isEmptyDisplayValue(candidateValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[preferredField])) {
5959
+ row[preferredField] = candidateValue;
5960
+ }
5961
+ delete row[candidateField];
5962
+ });
5963
+ keys.delete(candidateField);
5964
+ });
5965
+ };
5966
+ mergeDateGroup(['createdAt', 'created_at', 'date_created', 'created_date', 'date']);
5967
+ mergeDateGroup(['updatedAt', 'updated_at', 'date_updated', 'updated_date']);
5968
+ return rows;
5969
+ }
5689
5970
  function buildDisplayTable(docs, options) {
5690
- var rowsRaw = Array.isArray(docs)
5971
+ var rowsRawInitial = Array.isArray(docs)
5691
5972
  ? docs.map(function (doc) { return flattenForTable(doc, {
5692
5973
  includeIds: (options === null || options === void 0 ? void 0 : options.includeIds) === true,
5693
5974
  includeGroupFromId: (options === null || options === void 0 ? void 0 : options.includeGroupFromId) === true
5694
5975
  }); })
5695
5976
  : [];
5977
+ var rowsRaw = coalesceAssistantDisplayDuplicateFields(rowsRawInitial);
5696
5978
  var stats = new Map();
5697
5979
  rowsRaw.forEach(function (row) {
5698
5980
  Object.keys(row).forEach(function (key) {
@@ -5826,12 +6108,31 @@ function resolveAssistantNumericValue(value) {
5826
6108
  return value;
5827
6109
  }
5828
6110
  if (typeof value === 'string') {
5829
- var cleaned = value.replace(/[^0-9.+-]/g, '');
5830
- if (!cleaned) {
6111
+ var trimmed = value.trim();
6112
+ if (!trimmed) {
6113
+ return null;
6114
+ }
6115
+ var negative = false;
6116
+ var candidate = trimmed;
6117
+ var accountingMatch = candidate.match(/^\((.+)\)$/);
6118
+ if (accountingMatch === null || accountingMatch === void 0 ? void 0 : accountingMatch[1]) {
6119
+ negative = true;
6120
+ candidate = accountingMatch[1].trim();
6121
+ }
6122
+ candidate = candidate.replace(/^\$/, '').replace(/,/g, '');
6123
+ if (!candidate || !/^[+-]?(?:\d+|\d*\.\d+)%?$/.test(candidate) || !/[0-9]/.test(candidate)) {
5831
6124
  return null;
5832
6125
  }
5833
- var parsed = Number(cleaned);
5834
- return Number.isFinite(parsed) ? parsed : null;
6126
+ var normalized = candidate.endsWith('%') ? candidate.slice(0, -1) : candidate;
6127
+ var parsed = Number(normalized);
6128
+ if (!Number.isFinite(parsed)) {
6129
+ return null;
6130
+ }
6131
+ var signed = negative ? -parsed : parsed;
6132
+ if (!Number.isFinite(signed)) {
6133
+ return null;
6134
+ }
6135
+ return signed;
5835
6136
  }
5836
6137
  return null;
5837
6138
  }
@@ -6130,7 +6431,7 @@ function normalizeAssistantFindOptions(options) {
6130
6431
  var maxLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_MAX_LIMIT;
6131
6432
  var defaultLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_DEFAULT_LIMIT;
6132
6433
  var projection = sanitizeAssistantProjection(normalized.projection);
6133
- var sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
6434
+ var sort = sanitizeAssistantSort(normalized.sort);
6134
6435
  var limit = typeof normalized.limit === 'number'
6135
6436
  ? Math.min(Math.max(normalized.limit, 0), maxLimit)
6136
6437
  : defaultLimit;
@@ -6149,28 +6450,194 @@ function sanitizeAssistantProjection(projection) {
6149
6450
  if (!projection || typeof projection !== 'object') {
6150
6451
  return undefined;
6151
6452
  }
6152
- var keys = Object.keys(projection);
6453
+ var sanitized = __assign({}, projection);
6454
+ var keys = Object.keys(sanitized);
6153
6455
  if (!keys.length) {
6154
6456
  return undefined;
6155
6457
  }
6156
6458
  var hasInclude = false;
6157
- var hasExclude = false;
6459
+ var hasNonIdExclude = false;
6158
6460
  keys.forEach(function (key) {
6159
- var value = projection[key];
6461
+ var value = sanitized[key];
6160
6462
  if (value === 0 || value === false) {
6161
- hasExclude = true;
6463
+ if (key !== '_id') {
6464
+ hasNonIdExclude = true;
6465
+ }
6162
6466
  }
6163
6467
  else if (value === 1 || value === true) {
6164
6468
  hasInclude = true;
6165
6469
  }
6166
6470
  });
6167
- if (hasInclude && !hasExclude) {
6168
- var onlyIds = keys.every(function (key) { return isAssistantIdField(key); });
6471
+ if (hasInclude && !hasNonIdExclude) {
6472
+ var includeKeys = keys.filter(function (key) {
6473
+ var value = sanitized[key];
6474
+ return value === 1 || value === true;
6475
+ });
6476
+ var dedupedIncludeKeys = dedupeAssistantFieldKeys(includeKeys);
6477
+ if (dedupedIncludeKeys.length !== includeKeys.length) {
6478
+ var includeSet_1 = new Set(dedupedIncludeKeys);
6479
+ var next_2 = {};
6480
+ keys.forEach(function (key) {
6481
+ var value = sanitized[key];
6482
+ if (value === 1 || value === true) {
6483
+ if (includeSet_1.has(key)) {
6484
+ next_2[key] = value;
6485
+ }
6486
+ return;
6487
+ }
6488
+ if (key === '_id' && (value === 0 || value === false)) {
6489
+ next_2[key] = value;
6490
+ }
6491
+ });
6492
+ sanitized = next_2;
6493
+ keys = Object.keys(sanitized);
6494
+ }
6495
+ var includeAfterDedupe = keys.filter(function (key) {
6496
+ var value = sanitized[key];
6497
+ return value === 1 || value === true;
6498
+ });
6499
+ var onlyIds = includeAfterDedupe.length > 0
6500
+ && includeAfterDedupe.every(function (key) { return isAssistantIdField(key); });
6169
6501
  if (onlyIds) {
6170
6502
  return undefined;
6171
6503
  }
6172
6504
  }
6173
- return projection;
6505
+ return sanitized;
6506
+ }
6507
+ function sanitizeAssistantSort(sort) {
6508
+ if (!sort || typeof sort !== 'object') {
6509
+ return undefined;
6510
+ }
6511
+ var keys = Object.keys(sort);
6512
+ if (!keys.length) {
6513
+ return undefined;
6514
+ }
6515
+ var dedupedKeys = dedupeAssistantFieldKeys(keys);
6516
+ if (dedupedKeys.length === keys.length) {
6517
+ return sort;
6518
+ }
6519
+ var keepSet = new Set(dedupedKeys);
6520
+ var next = {};
6521
+ keys.forEach(function (key) {
6522
+ if (keepSet.has(key)) {
6523
+ next[key] = sort[key];
6524
+ }
6525
+ });
6526
+ return Object.keys(next).length ? next : undefined;
6527
+ }
6528
+ function splitAssistantFieldPath(fieldPath) {
6529
+ var normalized = normalizeOptionalString(fieldPath);
6530
+ if (!normalized) {
6531
+ return { parent: '', leaf: '' };
6532
+ }
6533
+ var segments = normalized.split('.');
6534
+ var leaf = segments.pop() || '';
6535
+ var parent = segments.join('.');
6536
+ return { parent: parent, leaf: leaf };
6537
+ }
6538
+ function getAssistantCreatedFieldRank(leaf) {
6539
+ var normalized = normalizeFieldMatchKey(leaf);
6540
+ if (normalized === 'createdat') {
6541
+ return 1;
6542
+ }
6543
+ if (normalized === 'createddate') {
6544
+ return 2;
6545
+ }
6546
+ if (normalized === 'datecreated') {
6547
+ return 3;
6548
+ }
6549
+ if (normalized === 'created') {
6550
+ return 4;
6551
+ }
6552
+ return 0;
6553
+ }
6554
+ function getAssistantUpdatedFieldRank(leaf) {
6555
+ var normalized = normalizeFieldMatchKey(leaf);
6556
+ if (normalized === 'updatedat') {
6557
+ return 1;
6558
+ }
6559
+ if (normalized === 'updateddate') {
6560
+ return 2;
6561
+ }
6562
+ if (normalized === 'dateupdated') {
6563
+ return 3;
6564
+ }
6565
+ if (normalized === 'updated') {
6566
+ return 4;
6567
+ }
6568
+ return 0;
6569
+ }
6570
+ function dedupeAssistantFieldKeys(fieldKeys) {
6571
+ if (!Array.isArray(fieldKeys) || !fieldKeys.length) {
6572
+ return [];
6573
+ }
6574
+ var keys = fieldKeys.filter(Boolean);
6575
+ if (!keys.length) {
6576
+ return [];
6577
+ }
6578
+ var keySet = new Set(keys);
6579
+ var dropSet = new Set();
6580
+ var preferByParent = function (entries, parent, key, rank) {
6581
+ var current = entries.get(parent);
6582
+ if (!current || rank < current.rank) {
6583
+ if (current) {
6584
+ dropSet.add(current.key);
6585
+ }
6586
+ entries.set(parent, { key: key, rank: rank });
6587
+ return;
6588
+ }
6589
+ dropSet.add(key);
6590
+ };
6591
+ keys.forEach(function (key) {
6592
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6593
+ if (!leaf) {
6594
+ return;
6595
+ }
6596
+ if (/_string$/i.test(leaf)) {
6597
+ var baseLeaf = leaf.replace(/_string$/i, '');
6598
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
6599
+ if (keySet.has(basePath)) {
6600
+ dropSet.add(key);
6601
+ }
6602
+ }
6603
+ });
6604
+ var createdByParent = new Map();
6605
+ var updatedByParent = new Map();
6606
+ var dateByParent = new Map();
6607
+ keys.forEach(function (key) {
6608
+ if (dropSet.has(key)) {
6609
+ return;
6610
+ }
6611
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6612
+ if (!leaf) {
6613
+ return;
6614
+ }
6615
+ var normalizedLeaf = normalizeFieldMatchKey(leaf);
6616
+ if (normalizedLeaf === 'date') {
6617
+ if (dateByParent.has(parent)) {
6618
+ dropSet.add(key);
6619
+ }
6620
+ else {
6621
+ dateByParent.set(parent, key);
6622
+ }
6623
+ return;
6624
+ }
6625
+ var createdRank = getAssistantCreatedFieldRank(leaf);
6626
+ if (createdRank > 0) {
6627
+ preferByParent(createdByParent, parent, key, createdRank);
6628
+ return;
6629
+ }
6630
+ var updatedRank = getAssistantUpdatedFieldRank(leaf);
6631
+ if (updatedRank > 0) {
6632
+ preferByParent(updatedByParent, parent, key, updatedRank);
6633
+ }
6634
+ });
6635
+ dateByParent.forEach(function (dateKey, parent) {
6636
+ if (createdByParent.has(parent)) {
6637
+ dropSet.add(dateKey);
6638
+ }
6639
+ });
6640
+ return keys.filter(function (key) { return !dropSet.has(key); });
6174
6641
  }
6175
6642
  var AGG_MATCH_EXPR_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte']);
6176
6643
  var ASSISTANT_NOW_RELATIVE_PATTERN = /^\$\$NOW_(MINUS|PLUS)_([0-9]+)_(MINUTES?|HOURS?|DAYS?|WEEKS?|MONTHS?|YEARS?)$/i;
@@ -7329,6 +7796,126 @@ function extractExpressionFieldPaths(value) {
7329
7796
  visit(value);
7330
7797
  return results.filter(Boolean);
7331
7798
  }
7799
+ function hasAssistantDateGroupingOperator(value) {
7800
+ if (Array.isArray(value)) {
7801
+ return value.some(function (entry) { return hasAssistantDateGroupingOperator(entry); });
7802
+ }
7803
+ if (!value || typeof value !== 'object') {
7804
+ return false;
7805
+ }
7806
+ var dateTrunc = value.$dateTrunc;
7807
+ if (dateTrunc && typeof dateTrunc === 'object' && !Array.isArray(dateTrunc)) {
7808
+ var unit = normalizeOptionalString(dateTrunc.unit).toLowerCase();
7809
+ if (unit === 'day' || unit === 'week' || unit === 'month' || unit === 'quarter' || unit === 'year') {
7810
+ return true;
7811
+ }
7812
+ }
7813
+ var dateToString = value.$dateToString;
7814
+ if (dateToString && typeof dateToString === 'object' && !Array.isArray(dateToString)) {
7815
+ var format = normalizeOptionalString(dateToString.format);
7816
+ if (/%[djmUVWYGy]/i.test(format)) {
7817
+ return true;
7818
+ }
7819
+ }
7820
+ var directDateOps = ['$year', '$month', '$week', '$isoWeek', '$isoWeekYear', '$dayOfMonth', '$dayOfYear', '$dateToParts'];
7821
+ if (directDateOps.some(function (op) { return Object.prototype.hasOwnProperty.call(value, op); })) {
7822
+ return true;
7823
+ }
7824
+ return Object.keys(value).some(function (key) { return hasAssistantDateGroupingOperator(value[key]); });
7825
+ }
7826
+ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths) {
7827
+ var e_16, _a, e_17, _b;
7828
+ if (!Array.isArray(pipeline) || groupIndex <= 0 || !groupPaths.length) {
7829
+ return false;
7830
+ }
7831
+ var groupFields = new Set();
7832
+ groupPaths.forEach(function (pathValue) {
7833
+ var normalizedPath = normalizeOptionalString(pathValue);
7834
+ if (!normalizedPath) {
7835
+ return;
7836
+ }
7837
+ groupFields.add(normalizedPath);
7838
+ var rootSegment = normalizedPath.split('.')[0];
7839
+ if (rootSegment) {
7840
+ groupFields.add(rootSegment);
7841
+ }
7842
+ });
7843
+ if (!groupFields.size) {
7844
+ return false;
7845
+ }
7846
+ var stageKeys = ['$addFields', '$set', '$project'];
7847
+ for (var i = groupIndex - 1; i >= 0; i -= 1) {
7848
+ var stage = pipeline[i];
7849
+ if (!stage || typeof stage !== 'object') {
7850
+ continue;
7851
+ }
7852
+ try {
7853
+ for (var stageKeys_1 = (e_16 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
7854
+ var stageKey = stageKeys_1_1.value;
7855
+ var payload = stage[stageKey];
7856
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
7857
+ continue;
7858
+ }
7859
+ try {
7860
+ for (var groupFields_1 = (e_17 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
7861
+ var groupField = groupFields_1_1.value;
7862
+ if (!Object.prototype.hasOwnProperty.call(payload, groupField)) {
7863
+ continue;
7864
+ }
7865
+ if (hasAssistantDateGroupingOperator(payload[groupField])) {
7866
+ return true;
7867
+ }
7868
+ }
7869
+ }
7870
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
7871
+ finally {
7872
+ try {
7873
+ if (groupFields_1_1 && !groupFields_1_1.done && (_b = groupFields_1.return)) _b.call(groupFields_1);
7874
+ }
7875
+ finally { if (e_17) throw e_17.error; }
7876
+ }
7877
+ }
7878
+ }
7879
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
7880
+ finally {
7881
+ try {
7882
+ if (stageKeys_1_1 && !stageKeys_1_1.done && (_a = stageKeys_1.return)) _a.call(stageKeys_1);
7883
+ }
7884
+ finally { if (e_16) throw e_16.error; }
7885
+ }
7886
+ }
7887
+ return false;
7888
+ }
7889
+ function isAssistantTimeGroupedAggregatePipeline(pipeline) {
7890
+ if (!Array.isArray(pipeline) || !pipeline.length) {
7891
+ return false;
7892
+ }
7893
+ var groupIndex = findAggregateGroupIndex(pipeline);
7894
+ if (groupIndex === -1) {
7895
+ return false;
7896
+ }
7897
+ var groupStage = pipeline[groupIndex];
7898
+ var groupPayload = groupStage === null || groupStage === void 0 ? void 0 : groupStage.$group;
7899
+ if (!groupPayload || typeof groupPayload !== 'object') {
7900
+ return false;
7901
+ }
7902
+ var groupPaths = extractGroupFieldPaths(groupPayload);
7903
+ if (groupPaths.some(function (field) { return /(date|time|created|updated|paid|invoice|timestamp|_at|month|quarter|week|year|day)/i.test(field); })) {
7904
+ return true;
7905
+ }
7906
+ if (hasAssistantDateGroupingOperator(groupPayload === null || groupPayload === void 0 ? void 0 : groupPayload._id)) {
7907
+ return true;
7908
+ }
7909
+ return isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths);
7910
+ }
7911
+ function isAssistantDirectiveDated(directive) {
7912
+ var _a;
7913
+ if (!directive || directive.type !== 'aggregate') {
7914
+ return false;
7915
+ }
7916
+ var pipeline = Array.isArray((_a = directive.payload) === null || _a === void 0 ? void 0 : _a.pipeline) ? directive.payload.pipeline : [];
7917
+ return isAssistantTimeGroupedAggregatePipeline(pipeline);
7918
+ }
7332
7919
  function findCommonPathPrefix(paths) {
7333
7920
  var _a;
7334
7921
  if (!paths.length) {
@@ -7387,7 +7974,7 @@ function isRegexMatchCondition(value) {
7387
7974
  return false;
7388
7975
  }
7389
7976
  function findRegexMatchInMatchObject(match, prefix) {
7390
- var e_16, _a, e_17, _b;
7977
+ var e_18, _a, e_19, _b;
7391
7978
  if (prefix === void 0) { prefix = ''; }
7392
7979
  if (Array.isArray(match)) {
7393
7980
  try {
@@ -7399,12 +7986,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7399
7986
  }
7400
7987
  }
7401
7988
  }
7402
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
7989
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
7403
7990
  finally {
7404
7991
  try {
7405
7992
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
7406
7993
  }
7407
- finally { if (e_16) throw e_16.error; }
7994
+ finally { if (e_18) throw e_18.error; }
7408
7995
  }
7409
7996
  return null;
7410
7997
  }
@@ -7435,12 +8022,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7435
8022
  }
7436
8023
  }
7437
8024
  }
7438
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
8025
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
7439
8026
  finally {
7440
8027
  try {
7441
8028
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
7442
8029
  }
7443
- finally { if (e_17) throw e_17.error; }
8030
+ finally { if (e_19) throw e_19.error; }
7444
8031
  }
7445
8032
  return null;
7446
8033
  }
@@ -7664,7 +8251,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
7664
8251
  return results;
7665
8252
  }
7666
8253
  function findMatchConditionForField(match, targetField, prefix) {
7667
- var e_18, _a, e_19, _b;
8254
+ var e_20, _a, e_21, _b;
7668
8255
  if (prefix === void 0) { prefix = ''; }
7669
8256
  if (!match || typeof match !== 'object') {
7670
8257
  return undefined;
@@ -7679,12 +8266,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7679
8266
  }
7680
8267
  }
7681
8268
  }
7682
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
8269
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
7683
8270
  finally {
7684
8271
  try {
7685
8272
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
7686
8273
  }
7687
- finally { if (e_18) throw e_18.error; }
8274
+ finally { if (e_20) throw e_20.error; }
7688
8275
  }
7689
8276
  return undefined;
7690
8277
  }
@@ -7711,12 +8298,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7711
8298
  }
7712
8299
  }
7713
8300
  }
7714
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
8301
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
7715
8302
  finally {
7716
8303
  try {
7717
8304
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
7718
8305
  }
7719
- finally { if (e_19) throw e_19.error; }
8306
+ finally { if (e_21) throw e_21.error; }
7720
8307
  }
7721
8308
  return undefined;
7722
8309
  }
@@ -7759,7 +8346,7 @@ function detectIdLikeValue(value) {
7759
8346
  return false;
7760
8347
  }
7761
8348
  function detectChemicalIdFromProbe(probeDocs, fields) {
7762
- var e_20, _a, e_21, _b;
8349
+ var e_22, _a, e_23, _b;
7763
8350
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
7764
8351
  return false;
7765
8352
  }
@@ -7771,7 +8358,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7771
8358
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
7772
8359
  var doc = probeDocs_1_1.value;
7773
8360
  try {
7774
- 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()) {
8361
+ for (var targets_1 = (e_23 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
7775
8362
  var field = targets_1_1.value;
7776
8363
  var value = getValueAtPath(doc, field);
7777
8364
  if (Array.isArray(value)) {
@@ -7784,21 +8371,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7784
8371
  }
7785
8372
  }
7786
8373
  }
7787
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
8374
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
7788
8375
  finally {
7789
8376
  try {
7790
8377
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
7791
8378
  }
7792
- finally { if (e_21) throw e_21.error; }
8379
+ finally { if (e_23) throw e_23.error; }
7793
8380
  }
7794
8381
  }
7795
8382
  }
7796
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
8383
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
7797
8384
  finally {
7798
8385
  try {
7799
8386
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
7800
8387
  }
7801
- finally { if (e_20) throw e_20.error; }
8388
+ finally { if (e_22) throw e_22.error; }
7802
8389
  }
7803
8390
  return false;
7804
8391
  }
@@ -8019,8 +8606,8 @@ function buildChemicalIdFieldCandidates(field) {
8019
8606
  }
8020
8607
  function applyChemicalNameLookupFallbackToQuery(params) {
8021
8608
  return __awaiter(this, void 0, void 0, function () {
8022
- 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;
8023
- var e_22, _a;
8609
+ 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_24_1;
8610
+ var e_24, _a;
8024
8611
  var _b;
8025
8612
  return __generator(this, function (_c) {
8026
8613
  switch (_c.label) {
@@ -8133,14 +8720,14 @@ function applyChemicalNameLookupFallbackToQuery(params) {
8133
8720
  return [3 /*break*/, 3];
8134
8721
  case 6: return [3 /*break*/, 9];
8135
8722
  case 7:
8136
- e_22_1 = _c.sent();
8137
- e_22 = { error: e_22_1 };
8723
+ e_24_1 = _c.sent();
8724
+ e_24 = { error: e_24_1 };
8138
8725
  return [3 /*break*/, 9];
8139
8726
  case 8:
8140
8727
  try {
8141
8728
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
8142
8729
  }
8143
- finally { if (e_22) throw e_22.error; }
8730
+ finally { if (e_24) throw e_24.error; }
8144
8731
  return [7 /*endfinally*/];
8145
8732
  case 9: return [2 /*return*/, null];
8146
8733
  }
@@ -8234,8 +8821,8 @@ function lookupIdsForNameMatch(params) {
8234
8821
  }
8235
8822
  function applyIdLookupFallbackToQuery(params) {
8236
8823
  return __awaiter(this, void 0, void 0, function () {
8237
- 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;
8238
- var e_24, _c, e_23, _d;
8824
+ 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_25_1, e_26_1;
8825
+ var e_26, _c, e_25, _d;
8239
8826
  var _e;
8240
8827
  return __generator(this, function (_f) {
8241
8828
  switch (_f.label) {
@@ -8305,7 +8892,7 @@ function applyIdLookupFallbackToQuery(params) {
8305
8892
  _f.label = 5;
8306
8893
  case 5:
8307
8894
  _f.trys.push([5, 14, 15, 16]);
8308
- candidates_3 = (e_23 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8895
+ candidates_3 = (e_25 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8309
8896
  _f.label = 6;
8310
8897
  case 6:
8311
8898
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -8372,28 +8959,28 @@ function applyIdLookupFallbackToQuery(params) {
8372
8959
  return [3 /*break*/, 6];
8373
8960
  case 13: return [3 /*break*/, 16];
8374
8961
  case 14:
8375
- e_23_1 = _f.sent();
8376
- e_23 = { error: e_23_1 };
8962
+ e_25_1 = _f.sent();
8963
+ e_25 = { error: e_25_1 };
8377
8964
  return [3 /*break*/, 16];
8378
8965
  case 15:
8379
8966
  try {
8380
8967
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
8381
8968
  }
8382
- finally { if (e_23) throw e_23.error; }
8969
+ finally { if (e_25) throw e_25.error; }
8383
8970
  return [7 /*endfinally*/];
8384
8971
  case 16:
8385
8972
  conditions_1_1 = conditions_1.next();
8386
8973
  return [3 /*break*/, 4];
8387
8974
  case 17: return [3 /*break*/, 20];
8388
8975
  case 18:
8389
- e_24_1 = _f.sent();
8390
- e_24 = { error: e_24_1 };
8976
+ e_26_1 = _f.sent();
8977
+ e_26 = { error: e_26_1 };
8391
8978
  return [3 /*break*/, 20];
8392
8979
  case 19:
8393
8980
  try {
8394
8981
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
8395
8982
  }
8396
- finally { if (e_24) throw e_24.error; }
8983
+ finally { if (e_26) throw e_26.error; }
8397
8984
  return [7 /*endfinally*/];
8398
8985
  case 20: return [2 /*return*/, null];
8399
8986
  }
@@ -8479,12 +9066,12 @@ function replaceAggregateDateField(pipeline, fromField, toField) {
8479
9066
  return value;
8480
9067
  }
8481
9068
  if (value && typeof value === 'object') {
8482
- var next_2 = {};
9069
+ var next_3 = {};
8483
9070
  Object.keys(value).forEach(function (key) {
8484
9071
  var nextKey = key === fromField ? toField : key;
8485
- next_2[nextKey] = replacer(value[key]);
9072
+ next_3[nextKey] = replacer(value[key]);
8486
9073
  });
8487
- return next_2;
9074
+ return next_3;
8488
9075
  }
8489
9076
  if (typeof value === 'string') {
8490
9077
  var fromRef = "$".concat(fromField);
@@ -9245,7 +9832,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection) {
9245
9832
  throw new Error('AI assistant report builder bridge: Collection is not configured for report builder.');
9246
9833
  }
9247
9834
  function findQueryDateField(query) {
9248
- var e_25, _a, e_26, _b;
9835
+ var e_27, _a, e_28, _b;
9249
9836
  if (!query || typeof query !== 'object') {
9250
9837
  return null;
9251
9838
  }
@@ -9259,12 +9846,12 @@ function findQueryDateField(query) {
9259
9846
  }
9260
9847
  }
9261
9848
  }
9262
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
9849
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
9263
9850
  finally {
9264
9851
  try {
9265
9852
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
9266
9853
  }
9267
- finally { if (e_25) throw e_25.error; }
9854
+ finally { if (e_27) throw e_27.error; }
9268
9855
  }
9269
9856
  return null;
9270
9857
  }
@@ -9283,12 +9870,12 @@ function findQueryDateField(query) {
9283
9870
  }
9284
9871
  }
9285
9872
  }
9286
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
9873
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
9287
9874
  finally {
9288
9875
  try {
9289
9876
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
9290
9877
  }
9291
- finally { if (e_26) throw e_26.error; }
9878
+ finally { if (e_28) throw e_28.error; }
9292
9879
  }
9293
9880
  return null;
9294
9881
  }
@@ -9326,7 +9913,7 @@ function extractDateRangeConditions(query) {
9326
9913
  });
9327
9914
  return results;
9328
9915
  }
9329
- function expandQueryDateFallbacks(query) {
9916
+ function expandQueryDateFallbacks(query, schemaFields) {
9330
9917
  if (!query || typeof query !== 'object') {
9331
9918
  return null;
9332
9919
  }
@@ -9359,21 +9946,16 @@ function expandQueryDateFallbacks(query) {
9359
9946
  }
9360
9947
  var dateConditions = extractDateRangeConditions(entry);
9361
9948
  dateConditions.forEach(function (condition) {
9362
- var fallback = AI_ASSISTANT_DATE_FALLBACKS[condition.field];
9363
- if (fallback && !existingFields.has(fallback)) {
9364
- extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, fallback)], false);
9365
- existingFields.add(fallback);
9366
- pushField(fallback);
9367
- }
9949
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
9950
+ expansions.forEach(function (field) {
9951
+ if (existingFields.has(field)) {
9952
+ return;
9953
+ }
9954
+ extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, field)], false);
9955
+ existingFields.add(field);
9956
+ pushField(field);
9957
+ });
9368
9958
  });
9369
- if (!existingFields.has('date_original')) {
9370
- var candidate = dateConditions.find(function (condition) { return condition.field.startsWith('date_') && condition.field !== 'date_original'; });
9371
- if (candidate) {
9372
- extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, candidate.field, 'date_original')], false);
9373
- existingFields.add('date_original');
9374
- pushField('date_original');
9375
- }
9376
- }
9377
9959
  });
9378
9960
  return extended;
9379
9961
  };
@@ -9417,11 +9999,12 @@ function expandQueryDateFallbacks(query) {
9417
9999
  }
9418
10000
  return { query: result.value, fields: addedFields };
9419
10001
  }
9420
- function buildDateFieldExpansionList(field) {
10002
+ function buildDateFieldExpansionList(field, schemaFields) {
9421
10003
  var normalized = normalizeOptionalString(field);
9422
10004
  if (!normalized) {
9423
10005
  return [];
9424
10006
  }
10007
+ var normalizedLower = normalized.toLowerCase();
9425
10008
  var expansions = new Set();
9426
10009
  var add = function (value) {
9427
10010
  if (value && value !== normalized) {
@@ -9432,15 +10015,46 @@ function buildDateFieldExpansionList(field) {
9432
10015
  if (fallback) {
9433
10016
  add(fallback);
9434
10017
  }
9435
- if (normalized.startsWith('date_') || normalized === 'date' || normalized.endsWith('_date')) {
10018
+ if (normalizedLower.startsWith('date_')
10019
+ || normalizedLower === 'date'
10020
+ || normalizedLower.endsWith('_date')
10021
+ || normalizedLower.includes('_date_')) {
9436
10022
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9437
10023
  }
9438
- if (normalized === 'createdAt' || normalized === 'updatedAt') {
10024
+ if (normalizedLower === 'createdat' || normalizedLower === 'updatedat') {
9439
10025
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9440
10026
  }
10027
+ var normalizedSchemaFields = Array.isArray(schemaFields)
10028
+ ? schemaFields
10029
+ .map(function (value) { return normalizeOptionalString(value); })
10030
+ .filter(Boolean)
10031
+ : [];
10032
+ if (normalizedSchemaFields.length) {
10033
+ var dateFieldPattern_1 = /(^|\.)(date($|_)|createdat$|updatedat$|[a-z0-9_]+_at$|[a-z0-9_]+_date$|[a-z0-9_]+_date_[a-z0-9_]*$)/i;
10034
+ var addedFromSchema_1 = 0;
10035
+ normalizedSchemaFields.forEach(function (schemaField) {
10036
+ if (addedFromSchema_1 >= AI_ASSISTANT_DATE_EXPANSION_SCHEMA_MAX_FIELDS) {
10037
+ return;
10038
+ }
10039
+ if (schemaField.includes('$')) {
10040
+ return;
10041
+ }
10042
+ if (!dateFieldPattern_1.test(schemaField)) {
10043
+ return;
10044
+ }
10045
+ if (schemaField === normalized) {
10046
+ return;
10047
+ }
10048
+ var beforeSize = expansions.size;
10049
+ add(schemaField);
10050
+ if (expansions.size > beforeSize) {
10051
+ addedFromSchema_1 += 1;
10052
+ }
10053
+ });
10054
+ }
9441
10055
  return Array.from(expansions);
9442
10056
  }
9443
- function expandAggregateDateMatchFallback(pipeline) {
10057
+ function expandAggregateDateMatchFallback(pipeline, schemaFields) {
9444
10058
  if (!Array.isArray(pipeline)) {
9445
10059
  return null;
9446
10060
  }
@@ -9473,7 +10087,7 @@ function expandAggregateDateMatchFallback(pipeline) {
9473
10087
  }
9474
10088
  var conditions = extractDateRangeConditions(entry);
9475
10089
  conditions.forEach(function (condition) {
9476
- var expansions = buildDateFieldExpansionList(condition.field);
10090
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
9477
10091
  expansions.forEach(function (field) {
9478
10092
  if (existingFields.has(field)) {
9479
10093
  return;
@@ -9510,7 +10124,7 @@ function resolveQueryDateFieldFallback(query) {
9510
10124
  return { from: dateField, to: fallback };
9511
10125
  }
9512
10126
  function containsForbiddenMongoOperators(value) {
9513
- var e_27, _a;
10127
+ var e_29, _a;
9514
10128
  if (!value || typeof value !== 'object') {
9515
10129
  return false;
9516
10130
  }
@@ -9529,12 +10143,12 @@ function containsForbiddenMongoOperators(value) {
9529
10143
  }
9530
10144
  }
9531
10145
  }
9532
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
10146
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
9533
10147
  finally {
9534
10148
  try {
9535
10149
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9536
10150
  }
9537
- finally { if (e_27) throw e_27.error; }
10151
+ finally { if (e_29) throw e_29.error; }
9538
10152
  }
9539
10153
  return false;
9540
10154
  }
@@ -9969,8 +10583,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
9969
10583
  }
9970
10584
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
9971
10585
  return __awaiter(this, void 0, void 0, function () {
9972
- var _a, _b, _c, _d, message, payload, status_1, e_28_1;
9973
- var _e, e_28, _f, _g;
10586
+ var _a, _b, _c, _d, message, payload, status_1, e_30_1;
10587
+ var _e, e_30, _f, _g;
9974
10588
  return __generator(this, function (_h) {
9975
10589
  switch (_h.label) {
9976
10590
  case 0:
@@ -9997,8 +10611,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
9997
10611
  return [3 /*break*/, 1];
9998
10612
  case 4: return [3 /*break*/, 11];
9999
10613
  case 5:
10000
- e_28_1 = _h.sent();
10001
- e_28 = { error: e_28_1 };
10614
+ e_30_1 = _h.sent();
10615
+ e_30 = { error: e_30_1 };
10002
10616
  return [3 /*break*/, 11];
10003
10617
  case 6:
10004
10618
  _h.trys.push([6, , 9, 10]);
@@ -10009,7 +10623,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10009
10623
  _h.label = 8;
10010
10624
  case 8: return [3 /*break*/, 10];
10011
10625
  case 9:
10012
- if (e_28) throw e_28.error;
10626
+ if (e_30) throw e_30.error;
10013
10627
  return [7 /*endfinally*/];
10014
10628
  case 10: return [7 /*endfinally*/];
10015
10629
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -10437,9 +11051,19 @@ var AI_ASSISTANT_DATA_REQUEST_PATTERNS = [
10437
11051
  /\bmissing\b/,
10438
11052
  /\bgroup(ed)? by\b/,
10439
11053
  /\bbreakdown\b/,
11054
+ /\bby day\b/,
11055
+ /\bby week\b/,
11056
+ /\bby month\b/,
11057
+ /\bby quarter\b/,
11058
+ /\bby year\b/,
11059
+ /\bby (time|date)\s+period\b/,
10440
11060
  /\bper day\b/,
10441
11061
  /\bper week\b/,
10442
- /\bper month\b/
11062
+ /\bper month\b/,
11063
+ /\bper quarter\b/,
11064
+ /\bper year\b/,
11065
+ /\bover the last\b/,
11066
+ /\bpast\s+\d+\b/
10443
11067
  ];
10444
11068
  var AI_ASSISTANT_NAVIGATION_REQUEST_PATTERNS = [
10445
11069
  /\bwhere\b/,
@@ -10592,13 +11216,79 @@ function classifyAssistantRequestType(message, plannerOutput) {
10592
11216
  plannerIntentType: plannerIntentRaw || undefined
10593
11217
  };
10594
11218
  }
10595
- function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText) {
11219
+ function resolveAssistantRequestedTimeGrain(message, plannerOutput) {
11220
+ var _a, _b;
11221
+ var plannerGrain = normalizeOptionalString((_b = (_a = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _a === void 0 ? void 0 : _a.timeRange) === null || _b === void 0 ? void 0 : _b.grain).toLowerCase();
11222
+ if (plannerGrain === 'day' || plannerGrain === 'week' || plannerGrain === 'month' || plannerGrain === 'quarter' || plannerGrain === 'year') {
11223
+ return plannerGrain;
11224
+ }
11225
+ var text = normalizeOptionalString(message).toLowerCase();
11226
+ if (!text) {
11227
+ return null;
11228
+ }
11229
+ var mapping = [
11230
+ { grain: 'quarter', pattern: /\b(quarter|quarters|quarterly|qoq)\b/i },
11231
+ { grain: 'month', pattern: /\b(month|months|monthly|mom)\b/i },
11232
+ { grain: 'week', pattern: /\b(week|weeks|weekly|wow)\b/i },
11233
+ { grain: 'day', pattern: /\b(day|days|daily)\b/i },
11234
+ { grain: 'year', pattern: /\b(year|years|yearly|yoy)\b/i }
11235
+ ];
11236
+ var match = mapping.find(function (entry) { return entry.pattern.test(text); });
11237
+ return (match === null || match === void 0 ? void 0 : match.grain) || null;
11238
+ }
11239
+ function hasAssistantDatedLanguage(message) {
11240
+ var text = normalizeOptionalString(message).toLowerCase();
11241
+ if (!text) {
11242
+ return false;
11243
+ }
11244
+ var patterns = [
11245
+ /\b(by|per)\s+(day|week|month|quarter|year|time\s*period|date\s*period)\b/i,
11246
+ /\b(over|across)\s+time\b/i,
11247
+ /\btime\s*series\b/i,
11248
+ /\btrend(?:ing|s)?\b/i,
11249
+ /\b(last|past|previous|recent)\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(day|week|month|quarter|year)s?\b/i,
11250
+ /\bover\s+the\s+last\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(day|week|month|quarter|year)s?\b/i,
11251
+ /\bmonth\s+over\s+month\b/i,
11252
+ /\bquarter\s+over\s+quarter\b/i,
11253
+ /\byear\s+over\s+year\b/i
11254
+ ];
11255
+ return patterns.some(function (pattern) { return pattern.test(text); });
11256
+ }
11257
+ function shouldEnforceAssistantDatedDirective(message, plannerOutput, requestClassification) {
11258
+ if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
11259
+ return false;
11260
+ }
11261
+ if (resolveAssistantRequestedTimeGrain(message, plannerOutput)) {
11262
+ return true;
11263
+ }
11264
+ return hasAssistantDatedLanguage(message);
11265
+ }
11266
+ function buildAssistantDirectiveStyleHint(params) {
11267
+ if (!params.enforceDated) {
11268
+ return '';
11269
+ }
11270
+ var grainLabel = params.requestedTimeGrain || 'time period';
11271
+ return [
11272
+ 'Report style intent: Dated.',
11273
+ "Requested time grain: ".concat(grainLabel, "."),
11274
+ '- Return REPORT_BUILDER_AGG (not REPORT_BUILDER_READ).',
11275
+ '- Ensure the pipeline groups by the requested time grain and requested breakdown dimensions.',
11276
+ '- For "last/past N" windows, use full completed calendar-period bounds in UTC unless the user asks for period-to-date.',
11277
+ params.strict ? '- STRICT: if unsure, still prefer REPORT_BUILDER_AGG.' : ''
11278
+ ].filter(Boolean).join('\n');
11279
+ }
11280
+ function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText, directiveStyleHintText, mode) {
11281
+ if (mode === void 0) { mode = 'any'; }
10596
11282
  var trimmedContext = normalizeOptionalString(contextText);
10597
11283
  var contextBlock = trimmedContext ? "\n\nContext:\n".concat(trimmedContext) : '';
10598
11284
  var trimmedHistory = normalizeOptionalString(historyText);
10599
11285
  var historyBlock = trimmedHistory ? "\n\nConversation so far:\n".concat(trimmedHistory) : '';
10600
- var instruction = '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_READ or REPORT_BUILDER_AGG directive line. Do not include any other text.';
10601
- return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(instruction).trim();
11286
+ var trimmedStyleHint = normalizeOptionalString(directiveStyleHintText);
11287
+ var styleHintBlock = trimmedStyleHint ? "\n\nDirective style hints:\n".concat(trimmedStyleHint) : '';
11288
+ var instruction = mode === 'aggregate_only'
11289
+ ? '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_AGG directive line. Do not include any other text.'
11290
+ : '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_READ or REPORT_BUILDER_AGG directive line. Do not include any other text.';
11291
+ return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock).concat(styleHintBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(instruction).trim();
10602
11292
  }
10603
11293
  function buildAssistantCodexPrompt(message, attachmentText, historyText, contextText) {
10604
11294
  var trimmedContext = normalizeOptionalString(contextText);
@@ -10615,7 +11305,7 @@ function resolveAssistantPlannerEnabled() {
10615
11305
  return raw === undefined ? true : raw === true;
10616
11306
  }
10617
11307
  function resolveAssistantPlannerKnownRoutes() {
10618
- var e_29, _a;
11308
+ var e_31, _a;
10619
11309
  var _b;
10620
11310
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10621
11311
  var unique = new Set();
@@ -10628,12 +11318,12 @@ function resolveAssistantPlannerKnownRoutes() {
10628
11318
  }
10629
11319
  }
10630
11320
  }
10631
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
11321
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
10632
11322
  finally {
10633
11323
  try {
10634
11324
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
10635
11325
  }
10636
- finally { if (e_29) throw e_29.error; }
11326
+ finally { if (e_31) throw e_31.error; }
10637
11327
  }
10638
11328
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
10639
11329
  }
@@ -10876,7 +11566,7 @@ function normalizeRouteMatchKey(value) {
10876
11566
  return normalizeRouteKey(value).toLowerCase();
10877
11567
  }
10878
11568
  function buildClientRouteIndex() {
10879
- var e_30, _a;
11569
+ var e_32, _a;
10880
11570
  var _b;
10881
11571
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10882
11572
  var set = new Set();
@@ -10895,12 +11585,12 @@ function buildClientRouteIndex() {
10895
11585
  }
10896
11586
  }
10897
11587
  }
10898
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
11588
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
10899
11589
  finally {
10900
11590
  try {
10901
11591
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
10902
11592
  }
10903
- finally { if (e_30) throw e_30.error; }
11593
+ finally { if (e_32) throw e_32.error; }
10904
11594
  }
10905
11595
  return { set: set, map: map, size: routes.length };
10906
11596
  }
@@ -11041,7 +11731,7 @@ function sanitizeAssistantResponse(value) {
11041
11731
  return normalizeAssistantRoutes(normalizedCurrency);
11042
11732
  }
11043
11733
  function evaluateAssistantGuardrails(message) {
11044
- var e_31, _a;
11734
+ var e_33, _a;
11045
11735
  var normalized = String(message || '').toLowerCase();
11046
11736
  var patterns = [
11047
11737
  {
@@ -11087,12 +11777,12 @@ function evaluateAssistantGuardrails(message) {
11087
11777
  }
11088
11778
  }
11089
11779
  }
11090
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
11780
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
11091
11781
  finally {
11092
11782
  try {
11093
11783
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
11094
11784
  }
11095
- finally { if (e_31) throw e_31.error; }
11785
+ finally { if (e_33) throw e_33.error; }
11096
11786
  }
11097
11787
  return null;
11098
11788
  }
@@ -11207,7 +11897,7 @@ function tokenizeArithmeticExpression(expression) {
11207
11897
  return tokens;
11208
11898
  }
11209
11899
  function evaluateArithmeticExpression(expression) {
11210
- var e_32, _a, e_33, _b;
11900
+ var e_34, _a, e_35, _b;
11211
11901
  var tokens = tokenizeArithmeticExpression(expression);
11212
11902
  if (!tokens || !tokens.length) {
11213
11903
  return null;
@@ -11264,12 +11954,12 @@ function evaluateArithmeticExpression(expression) {
11264
11954
  prevToken = token;
11265
11955
  }
11266
11956
  }
11267
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
11957
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
11268
11958
  finally {
11269
11959
  try {
11270
11960
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
11271
11961
  }
11272
- finally { if (e_32) throw e_32.error; }
11962
+ finally { if (e_34) throw e_34.error; }
11273
11963
  }
11274
11964
  while (ops.length) {
11275
11965
  var op = ops.pop();
@@ -11309,12 +11999,12 @@ function evaluateArithmeticExpression(expression) {
11309
11999
  stack.push(Number(token));
11310
12000
  }
11311
12001
  }
11312
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
12002
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
11313
12003
  finally {
11314
12004
  try {
11315
12005
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
11316
12006
  }
11317
- finally { if (e_33) throw e_33.error; }
12007
+ finally { if (e_35) throw e_35.error; }
11318
12008
  }
11319
12009
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
11320
12010
  return null;
@@ -11498,8 +12188,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
11498
12188
  }
11499
12189
  function readAttachmentContents(attachments) {
11500
12190
  return __awaiter(this, void 0, void 0, function () {
11501
- 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;
11502
- var e_34, _b;
12191
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_36_1;
12192
+ var e_36, _b;
11503
12193
  return __generator(this, function (_c) {
11504
12194
  switch (_c.label) {
11505
12195
  case 0:
@@ -11578,14 +12268,14 @@ function readAttachmentContents(attachments) {
11578
12268
  return [3 /*break*/, 2];
11579
12269
  case 10: return [3 /*break*/, 13];
11580
12270
  case 11:
11581
- e_34_1 = _c.sent();
11582
- e_34 = { error: e_34_1 };
12271
+ e_36_1 = _c.sent();
12272
+ e_36 = { error: e_36_1 };
11583
12273
  return [3 /*break*/, 13];
11584
12274
  case 12:
11585
12275
  try {
11586
12276
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
11587
12277
  }
11588
- finally { if (e_34) throw e_34.error; }
12278
+ finally { if (e_36) throw e_36.error; }
11589
12279
  return [7 /*endfinally*/];
11590
12280
  case 13: return [2 /*return*/, {
11591
12281
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -11826,7 +12516,7 @@ function estimateUsage(messages, responseText, model) {
11826
12516
  };
11827
12517
  }
11828
12518
  function evaluateGuardrails(message) {
11829
- var e_35, _a;
12519
+ var e_37, _a;
11830
12520
  var normalized = String(message || '').toLowerCase();
11831
12521
  var patterns = [
11832
12522
  { 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.' },
@@ -11848,12 +12538,12 @@ function evaluateGuardrails(message) {
11848
12538
  }
11849
12539
  }
11850
12540
  }
11851
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
12541
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
11852
12542
  finally {
11853
12543
  try {
11854
12544
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
11855
12545
  }
11856
- finally { if (e_35) throw e_35.error; }
12546
+ finally { if (e_37) throw e_37.error; }
11857
12547
  }
11858
12548
  return null;
11859
12549
  }