@resolveio/server-lib 22.0.21 → 22.0.23

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',
@@ -1463,10 +1479,10 @@ function executeAiAssistantCodexRun(payload, context) {
1463
1479
  insertResult = _d.sent();
1464
1480
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1465
1481
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1466
- 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;
1467
- var _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
1468
- return __generator(this, function (_v) {
1469
- 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, preferListDirective, 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) {
1470
1486
  case 0:
1471
1487
  runStart = Date.now();
1472
1488
  if (aiWorkerDebug) {
@@ -1498,6 +1514,10 @@ function executeAiAssistantCodexRun(payload, context) {
1498
1514
  requestClassification = classifyAssistantRequestType(message);
1499
1515
  dataQuestion = requestClassification.dataQuestion;
1500
1516
  lastDirective = null;
1517
+ requestedTimeGrain = null;
1518
+ enforceDatedDirective = false;
1519
+ datedDirectiveRetryUsed = false;
1520
+ datedDirectiveResolved = false;
1501
1521
  toolResponseDebug = null;
1502
1522
  toolError = null;
1503
1523
  termHints = [];
@@ -1534,17 +1554,17 @@ function executeAiAssistantCodexRun(payload, context) {
1534
1554
  codexUsage.output_tokens += outputTokens;
1535
1555
  codexUsage.total_tokens += inputTokens + outputTokens;
1536
1556
  };
1537
- contextRoute = normalizeOptionalString((_g = input === null || input === void 0 ? void 0 : input.context) === null || _g === void 0 ? void 0 : _g.route);
1538
- 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);
1539
1559
  recordStep('Queued', { requestId: requestId || undefined });
1540
1560
  recordStep('Planning: request classification', {
1541
1561
  type: requestClassification.type,
1542
1562
  source: requestClassification.source,
1543
1563
  dataQuestion: dataQuestion
1544
1564
  });
1545
- _v.label = 1;
1565
+ _3.label = 1;
1546
1566
  case 1:
1547
- _v.trys.push([1, 34, 35, 36]);
1567
+ _3.trys.push([1, 42, 43, 44]);
1548
1568
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1549
1569
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1550
1570
  hintText = termExpansion.expanded || hintSeed;
@@ -1565,19 +1585,19 @@ function executeAiAssistantCodexRun(payload, context) {
1565
1585
  recordStep('Planning: term expansion', {
1566
1586
  termMatches: termExpansion.matches.length ? termExpansion.matches : undefined
1567
1587
  });
1568
- _v.label = 2;
1588
+ _3.label = 2;
1569
1589
  case 2:
1570
- _v.trys.push([2, 4, , 5]);
1590
+ _3.trys.push([2, 4, , 5]);
1571
1591
  dbName = resolveAssistantDatabaseName(undefined, input.mongo);
1572
1592
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
1573
1593
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
1574
1594
  case 3:
1575
- collectionNames = _v.sent();
1595
+ collectionNames = _3.sent();
1576
1596
  collectionHints = resolveCollectionHintsFromTokens(expandedTokens, collectionNames, 5);
1577
1597
  collectionRanking = buildCollectionRankingDebugFromTokens(expandedTokens, collectionNames, 8);
1578
1598
  return [3 /*break*/, 5];
1579
1599
  case 4:
1580
- _a = _v.sent();
1600
+ _a = _3.sent();
1581
1601
  collectionHints = [];
1582
1602
  collectionRanking = collectionRanking || ((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens)
1583
1603
  ? buildCollectionRankingDebugFromTokens(collectionTokenization.expandedTokens || [], [], 0)
@@ -1613,7 +1633,7 @@ function executeAiAssistantCodexRun(payload, context) {
1613
1633
  prompt_1 = buildAssistantCodexPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1614
1634
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
1615
1635
  case 6:
1616
- workspaceRoot = _v.sent();
1636
+ workspaceRoot = _3.sent();
1617
1637
  codexConfig = resolveCodexSettings({
1618
1638
  model: codexModel,
1619
1639
  fallbackModels: codexFallbackModels
@@ -1648,44 +1668,56 @@ function executeAiAssistantCodexRun(payload, context) {
1648
1668
  fieldHints: fieldHints,
1649
1669
  inputClientId: input.id_client
1650
1670
  });
1651
- _v.label = 7;
1671
+ _3.label = 7;
1652
1672
  case 7:
1653
- _v.trys.push([7, 9, , 10]);
1673
+ _3.trys.push([7, 9, , 10]);
1654
1674
  plannerStart = Date.now();
1655
1675
  return [4 /*yield*/, runCodexInWorkerThread(plannerPrompt, runOptions, codexConfig, streamProgress)];
1656
1676
  case 8:
1657
- plannerRaw = _v.sent();
1677
+ plannerRaw = _3.sent();
1658
1678
  accumulateCodexUsage(plannerPrompt, plannerRaw);
1659
1679
  timingBreakdown.plannerMs = Date.now() - plannerStart;
1660
1680
  plannerOutput = parseJsonObject(plannerRaw);
1661
1681
  recordStep('Planning: planner result', { parsed: !!plannerOutput });
1662
1682
  return [3 /*break*/, 10];
1663
1683
  case 9:
1664
- _b = _v.sent();
1684
+ _b = _3.sent();
1665
1685
  recordStep('Planning: planner result', { parsed: false });
1666
1686
  return [3 /*break*/, 10];
1667
1687
  case 10:
1668
1688
  requestClassification = classifyAssistantRequestType(message, plannerOutput || undefined);
1669
1689
  dataQuestion = requestClassification.dataQuestion;
1690
+ requestedTimeGrain = resolveAssistantRequestedTimeGrain(message, plannerOutput || undefined);
1691
+ preferListDirective = shouldPreferAssistantListDirective(message, plannerOutput || undefined, requestClassification);
1692
+ enforceDatedDirective = shouldEnforceAssistantDatedDirective(message, plannerOutput || undefined, requestClassification);
1693
+ directiveStyleHint = buildAssistantDirectiveStyleHint({
1694
+ enforceDated: enforceDatedDirective,
1695
+ requestedTimeGrain: requestedTimeGrain,
1696
+ preferList: preferListDirective
1697
+ });
1698
+ directivePromptMode = enforceDatedDirective ? 'aggregate_only' : 'any';
1699
+ datedDirectiveRetryUsed = false;
1670
1700
  recordStep('Planning: request classification', {
1671
1701
  type: requestClassification.type,
1672
1702
  source: requestClassification.source,
1673
1703
  plannerIntentType: requestClassification.plannerIntentType || undefined,
1674
- dataQuestion: dataQuestion
1704
+ dataQuestion: dataQuestion,
1705
+ reportStyle: enforceDatedDirective ? 'dated' : undefined,
1706
+ timeGrain: requestedTimeGrain || undefined
1675
1707
  });
1676
1708
  responseText = '';
1677
1709
  directiveText = '';
1678
1710
  directive = null;
1679
1711
  if (!dataQuestion) return [3 /*break*/, 14];
1680
1712
  recordStep('Directive: determine tool', { type: 'data-question' });
1681
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1682
- _v.label = 11;
1713
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1714
+ _3.label = 11;
1683
1715
  case 11:
1684
- _v.trys.push([11, 13, , 14]);
1716
+ _3.trys.push([11, 13, , 14]);
1685
1717
  directiveStart = Date.now();
1686
1718
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1687
1719
  case 12:
1688
- directiveText = _v.sent();
1720
+ directiveText = _3.sent();
1689
1721
  accumulateCodexUsage(directivePrompt, directiveText);
1690
1722
  timingBreakdown.directiveMs = Date.now() - directiveStart;
1691
1723
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1693,17 +1725,17 @@ function executeAiAssistantCodexRun(payload, context) {
1693
1725
  directive = forcedDirective;
1694
1726
  directiveSource = 'model';
1695
1727
  lastDirective = forcedDirective;
1696
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_j = directive.payload) === null || _j === void 0 ? void 0 : _j.collection) || '');
1728
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.collection) || '');
1697
1729
  recordStep('Directive resolved', {
1698
1730
  source: directiveSource,
1699
1731
  type: directive.type,
1700
- collection: normalizeOptionalString((_k = directive.payload) === null || _k === void 0 ? void 0 : _k.collection) || undefined,
1701
- permissionView: normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.permissionView) || undefined
1732
+ collection: normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1733
+ permissionView: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.permissionView) || undefined
1702
1734
  });
1703
1735
  }
1704
1736
  return [3 /*break*/, 14];
1705
1737
  case 13:
1706
- _c = _v.sent();
1738
+ _c = _3.sent();
1707
1739
  return [3 /*break*/, 14];
1708
1740
  case 14:
1709
1741
  if (!!directive) return [3 /*break*/, 16];
@@ -1711,33 +1743,33 @@ function executeAiAssistantCodexRun(payload, context) {
1711
1743
  initialStart = Date.now();
1712
1744
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
1713
1745
  case 15:
1714
- responseText = _v.sent();
1746
+ responseText = _3.sent();
1715
1747
  accumulateCodexUsage(prompt_1, responseText);
1716
1748
  timingBreakdown.initialResponseMs = Date.now() - initialStart;
1717
1749
  directive = extractAssistantMongoDirective(responseText);
1718
1750
  if (directive) {
1719
1751
  directiveSource = 'model';
1720
1752
  lastDirective = directive;
1721
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || '');
1753
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || '');
1722
1754
  recordStep('Directive resolved', {
1723
1755
  source: directiveSource,
1724
1756
  type: directive.type,
1725
- collection: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.collection) || undefined,
1726
- permissionView: normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.permissionView) || undefined
1757
+ collection: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || undefined,
1758
+ permissionView: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.permissionView) || undefined
1727
1759
  });
1728
1760
  }
1729
- _v.label = 16;
1761
+ _3.label = 16;
1730
1762
  case 16:
1731
1763
  if (!(!directive && dataQuestion)) return [3 /*break*/, 20];
1732
1764
  recordStep('Directive: forced retry', { mode: 'directive-only' });
1733
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1734
- _v.label = 17;
1765
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1766
+ _3.label = 17;
1735
1767
  case 17:
1736
- _v.trys.push([17, 19, , 20]);
1768
+ _3.trys.push([17, 19, , 20]);
1737
1769
  forcedStart = Date.now();
1738
1770
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1739
1771
  case 18:
1740
- directiveText = _v.sent();
1772
+ directiveText = _3.sent();
1741
1773
  accumulateCodexUsage(directivePrompt, directiveText);
1742
1774
  timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
1743
1775
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1745,26 +1777,108 @@ function executeAiAssistantCodexRun(payload, context) {
1745
1777
  directive = forcedDirective;
1746
1778
  directiveSource = 'forced';
1747
1779
  lastDirective = forcedDirective;
1748
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || '');
1780
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || '');
1749
1781
  recordStep('Directive resolved', {
1750
1782
  source: directiveSource,
1751
1783
  type: directive.type,
1752
- collection: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.collection) || undefined,
1753
- permissionView: normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.permissionView) || undefined
1784
+ collection: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection) || undefined,
1785
+ permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || undefined
1754
1786
  });
1755
1787
  }
1756
1788
  return [3 /*break*/, 20];
1757
1789
  case 19:
1758
- _d = _v.sent();
1790
+ _d = _3.sent();
1759
1791
  return [3 /*break*/, 20];
1760
1792
  case 20:
1793
+ if (!(directive && enforceDatedDirective && !isAssistantDirectiveDated(directive))) return [3 /*break*/, 24];
1794
+ recordStep('Directive: dated retry', {
1795
+ currentType: directive.type,
1796
+ timeGrain: requestedTimeGrain || undefined
1797
+ });
1798
+ strictDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1799
+ enforceDated: true,
1800
+ requestedTimeGrain: requestedTimeGrain,
1801
+ strict: true
1802
+ }), 'aggregate_only');
1803
+ _3.label = 21;
1804
+ case 21:
1805
+ _3.trys.push([21, 23, , 24]);
1806
+ strictStart = Date.now();
1807
+ return [4 /*yield*/, runCodexInWorkerThread(strictDirectivePrompt, runOptions, codexConfig, streamProgress)];
1808
+ case 22:
1809
+ strictDirectiveText = _3.sent();
1810
+ accumulateCodexUsage(strictDirectivePrompt, strictDirectiveText);
1811
+ timingBreakdown.forcedDirectiveMs += Date.now() - strictStart;
1812
+ strictDirective = extractAssistantMongoDirective(strictDirectiveText);
1813
+ strictDirectiveIsDated = strictDirective ? isAssistantDirectiveDated(strictDirective) : false;
1814
+ shouldUseStrictDirective = !!strictDirective && strictDirective.type === 'aggregate';
1815
+ if (shouldUseStrictDirective && strictDirective) {
1816
+ directive = strictDirective;
1817
+ directiveSource = 'forced';
1818
+ lastDirective = strictDirective;
1819
+ datedDirectiveRetryUsed = true;
1820
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || '');
1821
+ recordStep('Directive resolved', {
1822
+ source: directiveSource,
1823
+ type: directive.type,
1824
+ collection: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.collection) || undefined,
1825
+ permissionView: normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.permissionView) || undefined,
1826
+ reportStyle: strictDirectiveIsDated ? 'dated' : 'aggregate_fallback',
1827
+ timeGrain: requestedTimeGrain || undefined
1828
+ });
1829
+ }
1830
+ return [3 /*break*/, 24];
1831
+ case 23:
1832
+ _e = _3.sent();
1833
+ return [3 /*break*/, 24];
1834
+ case 24:
1835
+ if (!(directive && enforceDatedDirective && directive.type === 'read')) return [3 /*break*/, 28];
1836
+ recordStep('Directive: dated guard retry', {
1837
+ currentType: directive.type,
1838
+ timeGrain: requestedTimeGrain || undefined
1839
+ });
1840
+ guardDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1841
+ enforceDated: true,
1842
+ requestedTimeGrain: requestedTimeGrain,
1843
+ strict: true
1844
+ }), 'aggregate_only');
1845
+ _3.label = 25;
1846
+ case 25:
1847
+ _3.trys.push([25, 27, , 28]);
1848
+ guardStart = Date.now();
1849
+ return [4 /*yield*/, runCodexInWorkerThread(guardDirectivePrompt, runOptions, codexConfig, streamProgress)];
1850
+ case 26:
1851
+ guardDirectiveText = _3.sent();
1852
+ accumulateCodexUsage(guardDirectivePrompt, guardDirectiveText);
1853
+ timingBreakdown.forcedDirectiveMs += Date.now() - guardStart;
1854
+ guardDirective = extractAssistantMongoDirective(guardDirectiveText);
1855
+ if (guardDirective && guardDirective.type === 'aggregate') {
1856
+ directive = guardDirective;
1857
+ directiveSource = 'forced';
1858
+ lastDirective = guardDirective;
1859
+ datedDirectiveRetryUsed = true;
1860
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || '');
1861
+ recordStep('Directive resolved', {
1862
+ source: directiveSource,
1863
+ type: directive.type,
1864
+ collection: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.collection) || undefined,
1865
+ permissionView: normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.permissionView) || undefined,
1866
+ reportStyle: isAssistantDirectiveDated(guardDirective) ? 'dated' : 'aggregate_fallback',
1867
+ timeGrain: requestedTimeGrain || undefined
1868
+ });
1869
+ }
1870
+ return [3 /*break*/, 28];
1871
+ case 27:
1872
+ _f = _3.sent();
1873
+ return [3 /*break*/, 28];
1874
+ case 28:
1761
1875
  if (directive) {
1762
- requestedCollection = normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection);
1876
+ requestedCollection = normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection);
1763
1877
  collectionOverride = resolveCollectionOverrideWithContext({
1764
1878
  message: message,
1765
1879
  collectionRanking: collectionRanking,
1766
1880
  requestedCollection: requestedCollection,
1767
- permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || contextRoute,
1881
+ permissionView: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.permissionView) || contextRoute,
1768
1882
  collectionNames: collectionNames
1769
1883
  });
1770
1884
  if (collectionOverride) {
@@ -1776,11 +1890,12 @@ function executeAiAssistantCodexRun(payload, context) {
1776
1890
  });
1777
1891
  }
1778
1892
  }
1893
+ datedDirectiveResolved = directive ? isAssistantDirectiveDated(directive) : false;
1779
1894
  cleanedResponseText = (directive === null || directive === void 0 ? void 0 : directive.cleaned) || responseText;
1780
1895
  if (cleanedResponseText) {
1781
1896
  assistantContent = sanitizeAssistantResponse(cleanedResponseText);
1782
1897
  }
1783
- if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 32];
1898
+ if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 40];
1784
1899
  effectiveDirective = collectionOverride
1785
1900
  ? __assign(__assign({}, directive), { payload: __assign(__assign({}, (directive.payload || {})), { collection: collectionOverride.to }) }) : directive;
1786
1901
  toolRequest = buildAssistantToolRequest(effectiveDirective, input);
@@ -1790,21 +1905,21 @@ function executeAiAssistantCodexRun(payload, context) {
1790
1905
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
1791
1906
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
1792
1907
  });
1793
- _v.label = 21;
1794
- case 21:
1795
- _v.trys.push([21, 30, , 31]);
1908
+ _3.label = 29;
1909
+ case 29:
1910
+ _3.trys.push([29, 38, , 39]);
1796
1911
  toolStart = Date.now();
1797
- if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 23];
1912
+ if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 31];
1798
1913
  return [4 /*yield*/, executeAiAssistantReportBuilderAggregate(toolRequest, context)];
1799
- case 22:
1800
- _e = _v.sent();
1801
- return [3 /*break*/, 25];
1802
- case 23: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
1803
- case 24:
1804
- _e = _v.sent();
1805
- _v.label = 25;
1806
- case 25:
1807
- toolResponse = _e;
1914
+ case 30:
1915
+ _g = _3.sent();
1916
+ return [3 /*break*/, 33];
1917
+ case 31: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
1918
+ case 32:
1919
+ _g = _3.sent();
1920
+ _3.label = 33;
1921
+ case 33:
1922
+ toolResponse = _g;
1808
1923
  timingBreakdown.toolMs = Date.now() - toolStart;
1809
1924
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
1810
1925
  ? toolResponse.debug
@@ -1819,48 +1934,49 @@ function executeAiAssistantCodexRun(payload, context) {
1819
1934
  progressTracker.push('Drafting response');
1820
1935
  recordStep('Drafting response');
1821
1936
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
1822
- _v.label = 26;
1823
- case 26:
1824
- _v.trys.push([26, 28, , 29]);
1937
+ _3.label = 34;
1938
+ case 34:
1939
+ _3.trys.push([34, 36, , 37]);
1825
1940
  followupStart = Date.now();
1826
1941
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
1827
- case 27:
1828
- followupText = _v.sent();
1942
+ case 35:
1943
+ followupText = _3.sent();
1829
1944
  accumulateCodexUsage(followupPrompt, followupText);
1830
1945
  timingBreakdown.followupMs = Date.now() - followupStart;
1831
1946
  assistantContent = sanitizeAssistantResponse(followupText);
1832
1947
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
1833
- return [3 /*break*/, 29];
1834
- case 28:
1835
- _f = _v.sent();
1948
+ return [3 /*break*/, 37];
1949
+ case 36:
1950
+ _h = _3.sent();
1836
1951
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
1837
- return [3 /*break*/, 29];
1838
- case 29: return [3 /*break*/, 31];
1839
- case 30:
1840
- error_2 = _v.sent();
1952
+ return [3 /*break*/, 37];
1953
+ case 37: return [3 /*break*/, 39];
1954
+ case 38:
1955
+ error_2 = _3.sent();
1841
1956
  assistantContent = buildAssistantToolErrorMessage(error_2);
1842
1957
  toolError = error_2;
1843
- return [3 /*break*/, 31];
1844
- case 31: return [3 /*break*/, 33];
1845
- case 32:
1958
+ return [3 /*break*/, 39];
1959
+ case 39: return [3 /*break*/, 41];
1960
+ case 40:
1846
1961
  progressTracker.push('Drafting response');
1847
1962
  recordStep('Drafting response');
1848
- _v.label = 33;
1849
- case 33: return [3 /*break*/, 36];
1850
- case 34:
1851
- error_3 = _v.sent();
1963
+ _3.label = 41;
1964
+ case 41: return [3 /*break*/, 44];
1965
+ case 42:
1966
+ error_3 = _3.sent();
1852
1967
  assistantContent = buildAssistantCodexErrorMessage(error_3);
1853
1968
  recordStep('Error', { message: normalizeOptionalString(error_3 === null || error_3 === void 0 ? void 0 : error_3.message) || 'Unknown error' });
1854
- return [3 /*break*/, 36];
1855
- case 35:
1969
+ return [3 /*break*/, 44];
1970
+ case 43:
1856
1971
  progressTracker.stop();
1857
1972
  return [7 /*endfinally*/];
1858
- case 36:
1973
+ case 44:
1859
1974
  if (!assistantContent) {
1860
1975
  assistantContent = buildAssistantCodexErrorMessage(null);
1861
1976
  }
1862
1977
  assistantContent = applyAssistantVerificationNotes(assistantContent, toolResult);
1863
1978
  assistantContent = applyAssistantDatedReportWindow(assistantContent, toolResult);
1979
+ assistantContent = applyAssistantLotNumberResponseGuard(assistantContent, message, toolResult);
1864
1980
  assistantContent = normalizeAssistantCurrencyText(assistantContent);
1865
1981
  if (aiWorkerDebug) {
1866
1982
  finishedAt = Date.now();
@@ -1891,6 +2007,10 @@ function executeAiAssistantCodexRun(payload, context) {
1891
2007
  requestTypeSource: requestClassification.source,
1892
2008
  plannerIntentType: requestClassification.plannerIntentType,
1893
2009
  dataQuestion: dataQuestion,
2010
+ reportStyleIntent: enforceDatedDirective ? 'dated' : null,
2011
+ requestedTimeGrain: requestedTimeGrain,
2012
+ datedDirectiveRetryUsed: datedDirectiveRetryUsed,
2013
+ datedDirectiveResolved: datedDirectiveResolved,
1894
2014
  directive: lastDirective,
1895
2015
  directiveSource: directiveSource,
1896
2016
  toolResult: toolResult,
@@ -1941,14 +2061,14 @@ function executeAiAssistantCodexRun(payload, context) {
1941
2061
  output_tokens: codexUsage.output_tokens,
1942
2062
  total_tokens: codexUsage.total_tokens
1943
2063
  } : null;
1944
- if (!finalUsage) return [3 /*break*/, 41];
2064
+ if (!finalUsage) return [3 /*break*/, 49];
1945
2065
  return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
1946
- case 37:
1947
- usageClientId = _v.sent();
1948
- if (!usageClientId) return [3 /*break*/, 41];
1949
- _v.label = 38;
1950
- case 38:
1951
- _v.trys.push([38, 40, , 41]);
2066
+ case 45:
2067
+ usageClientId = _3.sent();
2068
+ if (!usageClientId) return [3 /*break*/, 49];
2069
+ _3.label = 46;
2070
+ case 46:
2071
+ _3.trys.push([46, 48, , 49]);
1952
2072
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
1953
2073
  id_client: usageClientId,
1954
2074
  model: finalUsage.model,
@@ -1959,16 +2079,16 @@ function executeAiAssistantCodexRun(payload, context) {
1959
2079
  id_request: requestId || undefined,
1960
2080
  id_conversation: conversation._id
1961
2081
  })];
1962
- case 39:
1963
- _v.sent();
1964
- return [3 /*break*/, 41];
1965
- case 40:
1966
- usageError_1 = _v.sent();
2082
+ case 47:
2083
+ _3.sent();
2084
+ return [3 /*break*/, 49];
2085
+ case 48:
2086
+ usageError_1 = _3.sent();
1967
2087
  console.error(new Date(), 'Failed to record codex usage', usageError_1);
1968
- return [3 /*break*/, 41];
1969
- case 41:
2088
+ return [3 /*break*/, 49];
2089
+ case 49:
1970
2090
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
1971
- if (!assistantMessageId) return [3 /*break*/, 43];
2091
+ if (!assistantMessageId) return [3 /*break*/, 51];
1972
2092
  setPayload = {
1973
2093
  content: assistantContent,
1974
2094
  metadata: finalMetadata,
@@ -1980,18 +2100,18 @@ function executeAiAssistantCodexRun(payload, context) {
1980
2100
  return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: assistantMessageId }, {
1981
2101
  $set: setPayload
1982
2102
  })];
1983
- case 42:
1984
- _v.sent();
1985
- _v.label = 43;
1986
- case 43: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
1987
- case 44:
1988
- _v.sent();
1989
- if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 46];
2103
+ case 50:
2104
+ _3.sent();
2105
+ _3.label = 51;
2106
+ case 51: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2107
+ case 52:
2108
+ _3.sent();
2109
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 54];
1990
2110
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
1991
- case 45:
1992
- _v.sent();
1993
- _v.label = 46;
1994
- case 46: return [2 /*return*/, finalAssistantDoc];
2111
+ case 53:
2112
+ _3.sent();
2113
+ _3.label = 54;
2114
+ case 54: return [2 /*return*/, finalAssistantDoc];
1995
2115
  }
1996
2116
  });
1997
2117
  }); });
@@ -2126,7 +2246,7 @@ function executeAiAssistantMongoRead(payload, context) {
2126
2246
  _q.label = 8;
2127
2247
  case 8:
2128
2248
  if (!!documents.length) return [3 /*break*/, 10];
2129
- expanded = expandQueryDateFallbacks(executedQuery);
2249
+ expanded = expandQueryDateFallbacks(executedQuery, schemaFields);
2130
2250
  if (!expanded) return [3 /*break*/, 10];
2131
2251
  fallbackMeta.dateFieldsExpanded = {
2132
2252
  fields: expanded.fields,
@@ -2669,7 +2789,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
2669
2789
  _q.label = 10;
2670
2790
  case 10:
2671
2791
  if (!!documents.length) return [3 /*break*/, 12];
2672
- expanded = expandAggregateDateMatchFallback(executedPipeline);
2792
+ expanded = expandAggregateDateMatchFallback(executedPipeline, schemaFields);
2673
2793
  if (!expanded) return [3 /*break*/, 12];
2674
2794
  fallbackMeta.dateFieldsExpanded = {
2675
2795
  fields: expanded.fields,
@@ -3119,7 +3239,10 @@ function executeAiAssistantMongoAggregate(payload, context) {
3119
3239
  ? documents
3120
3240
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
3121
3241
  includeIds = ((_p = input.options) === null || _p === void 0 ? void 0 : _p.includeIds) === true;
3122
- displayDocs = sanitizedDocuments;
3242
+ displayDocs = sanitizedDocuments.map(function (doc) { return flattenForTable(doc, {
3243
+ includeGroupFromId: true,
3244
+ includeIds: true
3245
+ }); });
3123
3246
  return [4 /*yield*/, applyIdLookupDisplayEnrichment({
3124
3247
  docs: displayDocs,
3125
3248
  collection: collection,
@@ -3141,7 +3264,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3141
3264
  includeIds: includeIds,
3142
3265
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
3143
3266
  maxRows: normalizedOptions.limit || sanitizedDocuments.length,
3144
- includeGroupFromId: true
3267
+ includeGroupFromId: false
3145
3268
  });
3146
3269
  return [2 /*return*/, __assign(__assign({ documents: sanitizedDocuments, display: display }, (verification ? { verification: verification } : {})), (isSuperAdmin ? {
3147
3270
  debug: __assign(__assign({ collection: collection, collectionRequested: rawCollection, collectionResolved: collection, collectionMatched: collectionResolution.matched, collectionCandidates: collectionResolution.candidates, collectionScore: collectionResolution.score, bridge: 'report-builder', database: dbName, query: scopedQuery, options: normalizedOptions.aggregateOptions, originalPipeline: limitedPipeline, executedPipeline: executedPipeline }, (verification ? { verification: verification } : {})), { fallbacks: fallbackMeta })
@@ -3855,12 +3978,260 @@ function normalizeAssistantPermissionView(permissionView, collection) {
3855
3978
  }
3856
3979
  return normalizedPermission;
3857
3980
  }
3981
+ function extractAssistantProjectedColumnsFromDirectivePayload(directivePayload) {
3982
+ var pipeline = Array.isArray(directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.pipeline) ? directivePayload.pipeline : [];
3983
+ var projected = [];
3984
+ pipeline.forEach(function (stage) {
3985
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage) || !stage.$project || typeof stage.$project !== 'object') {
3986
+ return;
3987
+ }
3988
+ Object.keys(stage.$project).forEach(function (key) {
3989
+ if (key === '_id') {
3990
+ return;
3991
+ }
3992
+ var value = stage.$project[key];
3993
+ if (value === 0 || value === false) {
3994
+ return;
3995
+ }
3996
+ var label = formatDisplayColumnName(key) || key;
3997
+ if (label) {
3998
+ projected.push(label);
3999
+ }
4000
+ });
4001
+ });
4002
+ return projected;
4003
+ }
4004
+ function ensureAssistantDisplayColumns(display, requestedColumns) {
4005
+ if (!display || !Array.isArray(display.columns) || !Array.isArray(display.rows)) {
4006
+ return display;
4007
+ }
4008
+ var normalizedRequested = (Array.isArray(requestedColumns) ? requestedColumns : [])
4009
+ .map(function (column) { return normalizeOptionalString(column); })
4010
+ .filter(Boolean);
4011
+ if (!normalizedRequested.length) {
4012
+ return display;
4013
+ }
4014
+ var existing = new Set(display.columns.map(function (column) { return normalizeFieldMatchKey(column); }));
4015
+ var missing = normalizedRequested.filter(function (column) { return !existing.has(normalizeFieldMatchKey(column)); });
4016
+ if (!missing.length) {
4017
+ return display;
4018
+ }
4019
+ var columns = __spreadArray(__spreadArray([], __read(display.columns), false), __read(missing), false);
4020
+ var rows = display.rows.map(function (row) {
4021
+ var next = __assign({}, (row || {}));
4022
+ missing.forEach(function (column) {
4023
+ if (!Object.prototype.hasOwnProperty.call(next, column)) {
4024
+ next[column] = '';
4025
+ }
4026
+ });
4027
+ return next;
4028
+ });
4029
+ return __assign(__assign({}, display), { columns: columns, rows: rows });
4030
+ }
4031
+ function transformAssistantDisplayForDirective(directive, display) {
4032
+ if (!display || !Array.isArray(display.columns) || !Array.isArray(display.rows)) {
4033
+ return display;
4034
+ }
4035
+ if (!isAssistantDirectiveDated(directive)) {
4036
+ return display;
4037
+ }
4038
+ var pivoted = buildAssistantDatedPivotDisplay(display);
4039
+ return pivoted || display;
4040
+ }
4041
+ function buildAssistantDatedPivotDisplay(display) {
4042
+ var columns = Array.isArray(display === null || display === void 0 ? void 0 : display.columns) ? display.columns : [];
4043
+ var rows = Array.isArray(display === null || display === void 0 ? void 0 : display.rows) ? display.rows : [];
4044
+ if (!columns.length || !rows.length) {
4045
+ return null;
4046
+ }
4047
+ var monthColumn = resolveAssistantPivotMonthColumn(columns, rows);
4048
+ if (!monthColumn) {
4049
+ return null;
4050
+ }
4051
+ var valueColumn = resolveAssistantPivotValueColumn(columns, rows, monthColumn);
4052
+ if (!valueColumn) {
4053
+ return null;
4054
+ }
4055
+ var dimensionColumn = resolveAssistantPivotDimensionColumn(columns, rows, monthColumn, valueColumn);
4056
+ if (!dimensionColumn) {
4057
+ return null;
4058
+ }
4059
+ var monthSet = new Set();
4060
+ var grouped = new Map();
4061
+ rows.forEach(function (row) {
4062
+ var month = normalizeAssistantMonthBucket(row === null || row === void 0 ? void 0 : row[monthColumn]);
4063
+ if (!month) {
4064
+ return;
4065
+ }
4066
+ var dimension = normalizeAssistantPivotDimensionLabel(row === null || row === void 0 ? void 0 : row[dimensionColumn]);
4067
+ var numericValue = resolveAssistantNumericValue(row === null || row === void 0 ? void 0 : row[valueColumn]);
4068
+ if (numericValue === null) {
4069
+ return;
4070
+ }
4071
+ monthSet.add(month);
4072
+ var monthMap = grouped.get(dimension) || new Map();
4073
+ monthMap.set(month, (monthMap.get(month) || 0) + numericValue);
4074
+ grouped.set(dimension, monthMap);
4075
+ });
4076
+ var months = Array.from(monthSet).sort(function (a, b) { return a.localeCompare(b); });
4077
+ if (!months.length || !grouped.size) {
4078
+ return null;
4079
+ }
4080
+ var metricIsCurrency = isAssistantCurrencyColumn(valueColumn);
4081
+ var dimensionValues = Array.from(grouped.keys()).sort(function (a, b) { return a.localeCompare(b); });
4082
+ var pivotRows = dimensionValues.map(function (dimension) {
4083
+ var _a;
4084
+ var nextRow = (_a = {},
4085
+ _a[dimensionColumn] = dimension,
4086
+ _a);
4087
+ var monthMap = grouped.get(dimension) || new Map();
4088
+ months.forEach(function (month) {
4089
+ var value = monthMap.get(month);
4090
+ if (value === undefined) {
4091
+ nextRow[month] = '';
4092
+ return;
4093
+ }
4094
+ if (metricIsCurrency) {
4095
+ nextRow[month] = getAssistantCurrencyFormatter().format(value);
4096
+ return;
4097
+ }
4098
+ nextRow[month] = (0, common_1.round)(value, 2);
4099
+ });
4100
+ return nextRow;
4101
+ });
4102
+ return {
4103
+ columns: __spreadArray([dimensionColumn], __read(months), false),
4104
+ rows: pivotRows,
4105
+ rowCount: pivotRows.length,
4106
+ truncated: display.truncated,
4107
+ includeIds: display.includeIds
4108
+ };
4109
+ }
4110
+ function resolveAssistantPivotMonthColumn(columns, rows) {
4111
+ var loweredColumns = columns.map(function (column) { return normalizeOptionalString(column).toLowerCase(); });
4112
+ var explicitMonthIndex = loweredColumns.findIndex(function (column) { return column.includes('month'); });
4113
+ if (explicitMonthIndex !== -1) {
4114
+ return columns[explicitMonthIndex];
4115
+ }
4116
+ var bestColumn = '';
4117
+ var bestScore = 0;
4118
+ columns.forEach(function (column) {
4119
+ var monthMatches = 0;
4120
+ var nonEmpty = 0;
4121
+ rows.forEach(function (row) {
4122
+ var value = row === null || row === void 0 ? void 0 : row[column];
4123
+ if (value === null || value === undefined || value === '') {
4124
+ return;
4125
+ }
4126
+ nonEmpty += 1;
4127
+ if (normalizeAssistantMonthBucket(value)) {
4128
+ monthMatches += 1;
4129
+ }
4130
+ });
4131
+ if (!nonEmpty) {
4132
+ return;
4133
+ }
4134
+ var score = monthMatches / nonEmpty;
4135
+ if (score > bestScore) {
4136
+ bestScore = score;
4137
+ bestColumn = column;
4138
+ }
4139
+ });
4140
+ return bestScore >= 0.8 ? bestColumn : '';
4141
+ }
4142
+ function resolveAssistantPivotValueColumn(columns, rows, monthColumn) {
4143
+ var bestColumn = '';
4144
+ var bestScore = 0;
4145
+ columns.forEach(function (column) {
4146
+ if (column === monthColumn) {
4147
+ return;
4148
+ }
4149
+ var numericCount = 0;
4150
+ var nonEmptyCount = 0;
4151
+ rows.forEach(function (row) {
4152
+ var value = row === null || row === void 0 ? void 0 : row[column];
4153
+ if (value === null || value === undefined || value === '') {
4154
+ return;
4155
+ }
4156
+ nonEmptyCount += 1;
4157
+ if (resolveAssistantNumericValue(value) !== null) {
4158
+ numericCount += 1;
4159
+ }
4160
+ });
4161
+ if (!nonEmptyCount || !numericCount) {
4162
+ return;
4163
+ }
4164
+ var numericRatio = numericCount / nonEmptyCount;
4165
+ if (numericRatio < 0.8) {
4166
+ return;
4167
+ }
4168
+ var lower = normalizeOptionalString(column).toLowerCase();
4169
+ var semanticBoost = /(revenue|amount|total|sales|billing|paid|grand|cost|fee|charge|profit|count|qty|quantity)/i.test(lower)
4170
+ ? 0.2
4171
+ : 0;
4172
+ var currencyBoost = isAssistantCurrencyColumn(lower) ? 0.1 : 0;
4173
+ var score = numericRatio + semanticBoost + currencyBoost;
4174
+ if (score > bestScore) {
4175
+ bestScore = score;
4176
+ bestColumn = column;
4177
+ }
4178
+ });
4179
+ return bestColumn;
4180
+ }
4181
+ function resolveAssistantPivotDimensionColumn(columns, rows, monthColumn, valueColumn) {
4182
+ var candidates = columns.filter(function (column) { return column !== monthColumn && column !== valueColumn; });
4183
+ if (!candidates.length) {
4184
+ return '';
4185
+ }
4186
+ var bestColumn = '';
4187
+ var bestScore = -1;
4188
+ candidates.forEach(function (column) {
4189
+ var lower = normalizeOptionalString(column).toLowerCase();
4190
+ var nonEmpty = 0;
4191
+ var unique = new Set();
4192
+ var numericCount = 0;
4193
+ rows.forEach(function (row) {
4194
+ var value = row === null || row === void 0 ? void 0 : row[column];
4195
+ if (value === null || value === undefined || value === '') {
4196
+ return;
4197
+ }
4198
+ nonEmpty += 1;
4199
+ if (resolveAssistantNumericValue(value) !== null) {
4200
+ numericCount += 1;
4201
+ }
4202
+ unique.add(normalizeAssistantPivotDimensionLabel(value));
4203
+ });
4204
+ if (!nonEmpty || unique.size <= 1) {
4205
+ return;
4206
+ }
4207
+ var numericRatio = numericCount / nonEmpty;
4208
+ if (numericRatio >= 0.5) {
4209
+ return;
4210
+ }
4211
+ var score = unique.size;
4212
+ if (/(customer|client|account|name|company|group|category|type|segment)/i.test(lower)) {
4213
+ score += 1000;
4214
+ }
4215
+ if (lower.includes('id')) {
4216
+ score -= 100;
4217
+ }
4218
+ if (score > bestScore) {
4219
+ bestScore = score;
4220
+ bestColumn = column;
4221
+ }
4222
+ });
4223
+ return bestColumn;
4224
+ }
4225
+ function normalizeAssistantPivotDimensionLabel(value) {
4226
+ var normalized = normalizeOptionalString(value);
4227
+ return normalized || 'Unknown';
4228
+ }
3858
4229
  function buildAssistantToolResultPayload(directive, toolResponse) {
3859
4230
  var _a, _b, _c;
3860
4231
  var directivePayload = directive.payload || {};
3861
4232
  var documents = Array.isArray(toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.documents) ? toolResponse.documents : [];
3862
4233
  var includeIds = ((_a = directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.options) === null || _a === void 0 ? void 0 : _a.includeIds) === true;
3863
- var display = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.display) && typeof toolResponse.display === 'object'
4234
+ var rawDisplay = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.display) && typeof toolResponse.display === 'object'
3864
4235
  ? toolResponse.display
3865
4236
  : buildDisplayTable(documents, {
3866
4237
  includeIds: includeIds,
@@ -3868,12 +4239,20 @@ function buildAssistantToolResultPayload(directive, toolResponse) {
3868
4239
  maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS,
3869
4240
  includeGroupFromId: directive.type === 'aggregate'
3870
4241
  });
3871
- var trimmedDisplay = trimDisplayTable(display, {
4242
+ var projectedColumns = extractAssistantProjectedColumnsFromDirectivePayload(directivePayload);
4243
+ var display = ensureAssistantDisplayColumns(rawDisplay, projectedColumns);
4244
+ var transformedDisplay = transformAssistantDisplayForDirective(directive, display);
4245
+ var promptDisplay = trimDisplayTable(transformedDisplay, {
3872
4246
  maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
3873
4247
  maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS
3874
4248
  });
4249
+ var responseDisplayMaxRows = resolveAssistantToolResultResponseMaxRows(directive, directivePayload, transformedDisplay.rowCount);
4250
+ var responseDisplay = trimDisplayTable(transformedDisplay, {
4251
+ maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
4252
+ maxRows: responseDisplayMaxRows
4253
+ });
3875
4254
  var total = typeof (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.total) === 'number' ? toolResponse.total : null;
3876
- var rowCount = documents.length || trimmedDisplay.rowCount;
4255
+ var rowCount = documents.length || display.rowCount || responseDisplay.rowCount;
3877
4256
  var requestedCollection = normalizeOptionalString(directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.collection);
3878
4257
  var resolvedCollection = normalizeOptionalString((_b = toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) === null || _b === void 0 ? void 0 : _b.collectionResolved)
3879
4258
  || normalizeOptionalString((_c = toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) === null || _c === void 0 ? void 0 : _c.collection)
@@ -3886,23 +4265,39 @@ function buildAssistantToolResultPayload(directive, toolResponse) {
3886
4265
  type: directive.type === 'aggregate' ? 'mongo_agg' : 'mongo_read',
3887
4266
  input: directivePayload,
3888
4267
  output: {
3889
- display: trimmedDisplay,
4268
+ display: responseDisplay,
3890
4269
  total: total !== null ? total : undefined,
3891
4270
  collection: resolvedCollection || undefined,
3892
4271
  rowCount: rowCount,
3893
- columns: trimmedDisplay.columns,
3894
- truncated: trimmedDisplay.truncated,
4272
+ columns: responseDisplay.columns,
4273
+ truncated: responseDisplay.truncated,
3895
4274
  verification: verification,
3896
4275
  debug: (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object' ? toolResponse.debug : undefined
3897
4276
  }
3898
4277
  };
3899
4278
  return {
3900
4279
  result: result,
3901
- prompt: buildAssistantToolResultPrompt(result)
4280
+ prompt: buildAssistantToolResultPrompt(result, promptDisplay)
3902
4281
  };
3903
4282
  }
3904
- function buildAssistantToolResultPrompt(result) {
3905
- var _a, _b;
4283
+ function resolveAssistantToolResultResponseMaxRows(directive, directivePayload, rowCount) {
4284
+ var _a;
4285
+ if (directive.type !== 'aggregate') {
4286
+ return AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS;
4287
+ }
4288
+ var requestedLimit = typeof ((_a = directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.options) === null || _a === void 0 ? void 0 : _a.limit) === 'number'
4289
+ ? Math.min(Math.max((0, common_1.round)(directivePayload.options.limit), 0), AI_ASSISTANT_MONGO_MAX_LIMIT)
4290
+ : 0;
4291
+ if (requestedLimit > 0) {
4292
+ return requestedLimit;
4293
+ }
4294
+ if (typeof rowCount === 'number' && rowCount > 0) {
4295
+ return Math.min(rowCount, AI_ASSISTANT_MONGO_MAX_LIMIT);
4296
+ }
4297
+ return AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS;
4298
+ }
4299
+ function buildAssistantToolResultPrompt(result, displayPreview) {
4300
+ var _a;
3906
4301
  var lines = ['Tool Result:'];
3907
4302
  lines.push("Type: ".concat(result.type));
3908
4303
  if (result.output.collection) {
@@ -3915,9 +4310,9 @@ function buildAssistantToolResultPrompt(result) {
3915
4310
  if (Array.isArray(result.output.columns) && result.output.columns.length) {
3916
4311
  lines.push("Columns: ".concat(result.output.columns.join(', ')));
3917
4312
  }
3918
- if ((_b = (_a = result.output.display) === null || _a === void 0 ? void 0 : _a.rows) === null || _b === void 0 ? void 0 : _b.length) {
4313
+ if ((_a = displayPreview === null || displayPreview === void 0 ? void 0 : displayPreview.rows) === null || _a === void 0 ? void 0 : _a.length) {
3919
4314
  lines.push('Preview:');
3920
- lines.push(formatDisplayTableMarkdown(result.output.display));
4315
+ lines.push(formatDisplayTableMarkdown(displayPreview));
3921
4316
  }
3922
4317
  else {
3923
4318
  lines.push('Preview: (no rows)');
@@ -3969,6 +4364,45 @@ function buildAssistantToolFallbackResponse(result) {
3969
4364
  }
3970
4365
  return lines.join('\n').trim();
3971
4366
  }
4367
+ function didAssistantRequestLotOrBatch(message) {
4368
+ var normalized = normalizeOptionalString(message).toLowerCase();
4369
+ if (!normalized) {
4370
+ return false;
4371
+ }
4372
+ return /\b(lot|lots|batch|batches)\b/i.test(normalized);
4373
+ }
4374
+ function didAssistantQueryLotFields(toolResult) {
4375
+ if (!(toolResult === null || toolResult === void 0 ? void 0 : toolResult.input) || typeof toolResult.input !== 'object') {
4376
+ return false;
4377
+ }
4378
+ var serialized = '';
4379
+ try {
4380
+ serialized = JSON.stringify(toolResult.input).toLowerCase();
4381
+ }
4382
+ catch (_a) {
4383
+ serialized = '';
4384
+ }
4385
+ if (!serialized) {
4386
+ return false;
4387
+ }
4388
+ return /(lot[_\s-]?number|containers?\.lot|\.lot\b)/i.test(serialized);
4389
+ }
4390
+ function applyAssistantLotNumberResponseGuard(value, requestMessage, toolResult) {
4391
+ var content = normalizeOptionalString(value);
4392
+ if (!content) {
4393
+ return value || '';
4394
+ }
4395
+ if (!didAssistantRequestLotOrBatch(requestMessage) || !didAssistantQueryLotFields(toolResult)) {
4396
+ return content;
4397
+ }
4398
+ var before = content;
4399
+ var next = content;
4400
+ next = next.replace(/^\s*-\s*If you need lot[^.\n]*re-?run[^\n]*$/gim, '');
4401
+ next = next.replace(/^\s*-\s*.*re-?run[^\n]*lot[^\n]*$/gim, '');
4402
+ next = next.replace(/\bI can re-?run[^.\n]*lot[^.\n]*\.?/gi, '');
4403
+ next = next.replace(/\n{3,}/g, '\n\n').trim();
4404
+ return next || before;
4405
+ }
3972
4406
  function applyAssistantVerificationNotes(value, toolResult) {
3973
4407
  var _a, _b, _c, _d;
3974
4408
  var content = normalizeOptionalString(value);
@@ -4129,6 +4563,18 @@ function buildAssistantDebugPayload(params) {
4129
4563
  if (params.dataQuestion) {
4130
4564
  notes.push('Detected a data request; tool call required.');
4131
4565
  }
4566
+ if (params.reportStyleIntent === 'dated') {
4567
+ notes.push("Report style intent: dated".concat(params.requestedTimeGrain ? " (".concat(params.requestedTimeGrain, ")") : '', "."));
4568
+ if (params.datedDirectiveRetryUsed) {
4569
+ notes.push('Retried directive generation to enforce dated report style.');
4570
+ }
4571
+ if (params.datedDirectiveResolved) {
4572
+ notes.push('Directive includes time-based aggregate grouping.');
4573
+ }
4574
+ else {
4575
+ notes.push('Directive did not include explicit time-based grouping.');
4576
+ }
4577
+ }
4132
4578
  if (params.directiveSource === 'forced') {
4133
4579
  notes.push('Assistant response omitted a REPORT_BUILDER_* directive; ran a directive-only pass.');
4134
4580
  }
@@ -4264,6 +4710,10 @@ function buildAssistantDebugPayload(params) {
4264
4710
  requestTypeSource: params.requestTypeSource,
4265
4711
  plannerIntentType: params.plannerIntentType || undefined,
4266
4712
  dataQuestion: params.dataQuestion,
4713
+ reportStyleIntent: params.reportStyleIntent || undefined,
4714
+ timeGrain: params.requestedTimeGrain || undefined,
4715
+ datedDirectiveRetryUsed: params.datedDirectiveRetryUsed === true ? true : undefined,
4716
+ datedDirectiveResolved: params.datedDirectiveResolved === true ? true : undefined,
4267
4717
  directiveSource: params.directiveSource
4268
4718
  },
4269
4719
  directive: directive ? {
@@ -5710,13 +6160,138 @@ function flattenForTable(doc, options) {
5710
6160
  });
5711
6161
  return result;
5712
6162
  }
6163
+ function normalizeAssistantComparableDateDisplayValue(value) {
6164
+ if (value === null || value === undefined) {
6165
+ return '';
6166
+ }
6167
+ if (value instanceof Date) {
6168
+ return Number.isNaN(value.getTime()) ? '' : value.toISOString();
6169
+ }
6170
+ if (typeof value === 'number' && Number.isFinite(value)) {
6171
+ var epochMs = value >= 1e11 ? value : value >= 1e9 ? value * 1000 : null;
6172
+ if (epochMs !== null) {
6173
+ var parsed_1 = new Date(epochMs);
6174
+ if (!Number.isNaN(parsed_1.getTime())) {
6175
+ return parsed_1.toISOString();
6176
+ }
6177
+ }
6178
+ return String(value);
6179
+ }
6180
+ var text = String(value).trim();
6181
+ if (!text) {
6182
+ return '';
6183
+ }
6184
+ var parsed = Date.parse(text);
6185
+ if (!Number.isNaN(parsed)) {
6186
+ return new Date(parsed).toISOString();
6187
+ }
6188
+ return text.toLowerCase();
6189
+ }
6190
+ function shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField) {
6191
+ var preferredNonEmpty = 0;
6192
+ var candidateNonEmpty = 0;
6193
+ var overlap = 0;
6194
+ var equalOverlap = 0;
6195
+ rows.forEach(function (row) {
6196
+ var preferredValue = row === null || row === void 0 ? void 0 : row[preferredField];
6197
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
6198
+ var preferredHasValue = !isEmptyDisplayValue(preferredValue);
6199
+ var candidateHasValue = !isEmptyDisplayValue(candidateValue);
6200
+ if (preferredHasValue) {
6201
+ preferredNonEmpty += 1;
6202
+ }
6203
+ if (candidateHasValue) {
6204
+ candidateNonEmpty += 1;
6205
+ }
6206
+ if (preferredHasValue && candidateHasValue) {
6207
+ overlap += 1;
6208
+ if (normalizeAssistantComparableDateDisplayValue(preferredValue)
6209
+ === normalizeAssistantComparableDateDisplayValue(candidateValue)) {
6210
+ equalOverlap += 1;
6211
+ }
6212
+ }
6213
+ });
6214
+ if (!candidateNonEmpty) {
6215
+ return false;
6216
+ }
6217
+ if (!preferredNonEmpty) {
6218
+ return true;
6219
+ }
6220
+ if (!overlap) {
6221
+ return false;
6222
+ }
6223
+ return (equalOverlap / overlap) >= 0.8;
6224
+ }
6225
+ function coalesceAssistantDisplayDuplicateFields(rowsRaw) {
6226
+ if (!Array.isArray(rowsRaw) || !rowsRaw.length) {
6227
+ return Array.isArray(rowsRaw) ? rowsRaw : [];
6228
+ }
6229
+ var rows = rowsRaw.map(function (row) { return (__assign({}, (row || {}))); });
6230
+ var collectKeys = function () {
6231
+ var keySet = new Set();
6232
+ rows.forEach(function (row) {
6233
+ Object.keys(row || {}).forEach(function (key) {
6234
+ if (key) {
6235
+ keySet.add(key);
6236
+ }
6237
+ });
6238
+ });
6239
+ return keySet;
6240
+ };
6241
+ var keys = collectKeys();
6242
+ Array.from(keys).forEach(function (key) {
6243
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6244
+ if (!leaf || !/_string$/i.test(leaf)) {
6245
+ return;
6246
+ }
6247
+ var baseLeaf = leaf.replace(/_string$/i, '');
6248
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
6249
+ if (!keys.has(basePath)) {
6250
+ return;
6251
+ }
6252
+ rows.forEach(function (row) {
6253
+ var stringValue = row === null || row === void 0 ? void 0 : row[key];
6254
+ if (!isEmptyDisplayValue(stringValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[basePath])) {
6255
+ row[basePath] = stringValue;
6256
+ }
6257
+ delete row[key];
6258
+ });
6259
+ });
6260
+ keys = collectKeys();
6261
+ var mergeDateGroup = function (preferredOrder) {
6262
+ var preferredField = preferredOrder.find(function (field) { return keys.has(field); });
6263
+ if (!preferredField) {
6264
+ return;
6265
+ }
6266
+ preferredOrder.forEach(function (candidateField) {
6267
+ if (candidateField === preferredField || !keys.has(candidateField)) {
6268
+ return;
6269
+ }
6270
+ if (!shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField)) {
6271
+ return;
6272
+ }
6273
+ rows.forEach(function (row) {
6274
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
6275
+ if (!isEmptyDisplayValue(candidateValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[preferredField])) {
6276
+ row[preferredField] = candidateValue;
6277
+ }
6278
+ delete row[candidateField];
6279
+ });
6280
+ keys.delete(candidateField);
6281
+ });
6282
+ };
6283
+ mergeDateGroup(['createdAt', 'created_at', 'date_created', 'created_date', 'date']);
6284
+ mergeDateGroup(['updatedAt', 'updated_at', 'date_updated', 'updated_date']);
6285
+ return rows;
6286
+ }
5713
6287
  function buildDisplayTable(docs, options) {
5714
- var rowsRaw = Array.isArray(docs)
6288
+ var rowsRawInitial = Array.isArray(docs)
5715
6289
  ? docs.map(function (doc) { return flattenForTable(doc, {
5716
6290
  includeIds: (options === null || options === void 0 ? void 0 : options.includeIds) === true,
5717
6291
  includeGroupFromId: (options === null || options === void 0 ? void 0 : options.includeGroupFromId) === true
5718
6292
  }); })
5719
6293
  : [];
6294
+ var rowsRaw = coalesceAssistantDisplayDuplicateFields(rowsRawInitial);
5720
6295
  var stats = new Map();
5721
6296
  rowsRaw.forEach(function (row) {
5722
6297
  Object.keys(row).forEach(function (key) {
@@ -6173,7 +6748,7 @@ function normalizeAssistantFindOptions(options) {
6173
6748
  var maxLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_MAX_LIMIT;
6174
6749
  var defaultLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_DEFAULT_LIMIT;
6175
6750
  var projection = sanitizeAssistantProjection(normalized.projection);
6176
- var sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
6751
+ var sort = sanitizeAssistantSort(normalized.sort);
6177
6752
  var limit = typeof normalized.limit === 'number'
6178
6753
  ? Math.min(Math.max(normalized.limit, 0), maxLimit)
6179
6754
  : defaultLimit;
@@ -6192,28 +6767,194 @@ function sanitizeAssistantProjection(projection) {
6192
6767
  if (!projection || typeof projection !== 'object') {
6193
6768
  return undefined;
6194
6769
  }
6195
- var keys = Object.keys(projection);
6770
+ var sanitized = __assign({}, projection);
6771
+ var keys = Object.keys(sanitized);
6196
6772
  if (!keys.length) {
6197
6773
  return undefined;
6198
6774
  }
6199
6775
  var hasInclude = false;
6200
- var hasExclude = false;
6776
+ var hasNonIdExclude = false;
6201
6777
  keys.forEach(function (key) {
6202
- var value = projection[key];
6778
+ var value = sanitized[key];
6203
6779
  if (value === 0 || value === false) {
6204
- hasExclude = true;
6780
+ if (key !== '_id') {
6781
+ hasNonIdExclude = true;
6782
+ }
6205
6783
  }
6206
6784
  else if (value === 1 || value === true) {
6207
6785
  hasInclude = true;
6208
6786
  }
6209
6787
  });
6210
- if (hasInclude && !hasExclude) {
6211
- var onlyIds = keys.every(function (key) { return isAssistantIdField(key); });
6788
+ if (hasInclude && !hasNonIdExclude) {
6789
+ var includeKeys = keys.filter(function (key) {
6790
+ var value = sanitized[key];
6791
+ return value === 1 || value === true;
6792
+ });
6793
+ var dedupedIncludeKeys = dedupeAssistantFieldKeys(includeKeys);
6794
+ if (dedupedIncludeKeys.length !== includeKeys.length) {
6795
+ var includeSet_1 = new Set(dedupedIncludeKeys);
6796
+ var next_2 = {};
6797
+ keys.forEach(function (key) {
6798
+ var value = sanitized[key];
6799
+ if (value === 1 || value === true) {
6800
+ if (includeSet_1.has(key)) {
6801
+ next_2[key] = value;
6802
+ }
6803
+ return;
6804
+ }
6805
+ if (key === '_id' && (value === 0 || value === false)) {
6806
+ next_2[key] = value;
6807
+ }
6808
+ });
6809
+ sanitized = next_2;
6810
+ keys = Object.keys(sanitized);
6811
+ }
6812
+ var includeAfterDedupe = keys.filter(function (key) {
6813
+ var value = sanitized[key];
6814
+ return value === 1 || value === true;
6815
+ });
6816
+ var onlyIds = includeAfterDedupe.length > 0
6817
+ && includeAfterDedupe.every(function (key) { return isAssistantIdField(key); });
6212
6818
  if (onlyIds) {
6213
6819
  return undefined;
6214
6820
  }
6215
6821
  }
6216
- return projection;
6822
+ return sanitized;
6823
+ }
6824
+ function sanitizeAssistantSort(sort) {
6825
+ if (!sort || typeof sort !== 'object') {
6826
+ return undefined;
6827
+ }
6828
+ var keys = Object.keys(sort);
6829
+ if (!keys.length) {
6830
+ return undefined;
6831
+ }
6832
+ var dedupedKeys = dedupeAssistantFieldKeys(keys);
6833
+ if (dedupedKeys.length === keys.length) {
6834
+ return sort;
6835
+ }
6836
+ var keepSet = new Set(dedupedKeys);
6837
+ var next = {};
6838
+ keys.forEach(function (key) {
6839
+ if (keepSet.has(key)) {
6840
+ next[key] = sort[key];
6841
+ }
6842
+ });
6843
+ return Object.keys(next).length ? next : undefined;
6844
+ }
6845
+ function splitAssistantFieldPath(fieldPath) {
6846
+ var normalized = normalizeOptionalString(fieldPath);
6847
+ if (!normalized) {
6848
+ return { parent: '', leaf: '' };
6849
+ }
6850
+ var segments = normalized.split('.');
6851
+ var leaf = segments.pop() || '';
6852
+ var parent = segments.join('.');
6853
+ return { parent: parent, leaf: leaf };
6854
+ }
6855
+ function getAssistantCreatedFieldRank(leaf) {
6856
+ var normalized = normalizeFieldMatchKey(leaf);
6857
+ if (normalized === 'createdat') {
6858
+ return 1;
6859
+ }
6860
+ if (normalized === 'createddate') {
6861
+ return 2;
6862
+ }
6863
+ if (normalized === 'datecreated') {
6864
+ return 3;
6865
+ }
6866
+ if (normalized === 'created') {
6867
+ return 4;
6868
+ }
6869
+ return 0;
6870
+ }
6871
+ function getAssistantUpdatedFieldRank(leaf) {
6872
+ var normalized = normalizeFieldMatchKey(leaf);
6873
+ if (normalized === 'updatedat') {
6874
+ return 1;
6875
+ }
6876
+ if (normalized === 'updateddate') {
6877
+ return 2;
6878
+ }
6879
+ if (normalized === 'dateupdated') {
6880
+ return 3;
6881
+ }
6882
+ if (normalized === 'updated') {
6883
+ return 4;
6884
+ }
6885
+ return 0;
6886
+ }
6887
+ function dedupeAssistantFieldKeys(fieldKeys) {
6888
+ if (!Array.isArray(fieldKeys) || !fieldKeys.length) {
6889
+ return [];
6890
+ }
6891
+ var keys = fieldKeys.filter(Boolean);
6892
+ if (!keys.length) {
6893
+ return [];
6894
+ }
6895
+ var keySet = new Set(keys);
6896
+ var dropSet = new Set();
6897
+ var preferByParent = function (entries, parent, key, rank) {
6898
+ var current = entries.get(parent);
6899
+ if (!current || rank < current.rank) {
6900
+ if (current) {
6901
+ dropSet.add(current.key);
6902
+ }
6903
+ entries.set(parent, { key: key, rank: rank });
6904
+ return;
6905
+ }
6906
+ dropSet.add(key);
6907
+ };
6908
+ keys.forEach(function (key) {
6909
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6910
+ if (!leaf) {
6911
+ return;
6912
+ }
6913
+ if (/_string$/i.test(leaf)) {
6914
+ var baseLeaf = leaf.replace(/_string$/i, '');
6915
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
6916
+ if (keySet.has(basePath)) {
6917
+ dropSet.add(key);
6918
+ }
6919
+ }
6920
+ });
6921
+ var createdByParent = new Map();
6922
+ var updatedByParent = new Map();
6923
+ var dateByParent = new Map();
6924
+ keys.forEach(function (key) {
6925
+ if (dropSet.has(key)) {
6926
+ return;
6927
+ }
6928
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6929
+ if (!leaf) {
6930
+ return;
6931
+ }
6932
+ var normalizedLeaf = normalizeFieldMatchKey(leaf);
6933
+ if (normalizedLeaf === 'date') {
6934
+ if (dateByParent.has(parent)) {
6935
+ dropSet.add(key);
6936
+ }
6937
+ else {
6938
+ dateByParent.set(parent, key);
6939
+ }
6940
+ return;
6941
+ }
6942
+ var createdRank = getAssistantCreatedFieldRank(leaf);
6943
+ if (createdRank > 0) {
6944
+ preferByParent(createdByParent, parent, key, createdRank);
6945
+ return;
6946
+ }
6947
+ var updatedRank = getAssistantUpdatedFieldRank(leaf);
6948
+ if (updatedRank > 0) {
6949
+ preferByParent(updatedByParent, parent, key, updatedRank);
6950
+ }
6951
+ });
6952
+ dateByParent.forEach(function (dateKey, parent) {
6953
+ if (createdByParent.has(parent)) {
6954
+ dropSet.add(dateKey);
6955
+ }
6956
+ });
6957
+ return keys.filter(function (key) { return !dropSet.has(key); });
6217
6958
  }
6218
6959
  var AGG_MATCH_EXPR_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte']);
6219
6960
  var ASSISTANT_NOW_RELATIVE_PATTERN = /^\$\$NOW_(MINUS|PLUS)_([0-9]+)_(MINUTES?|HOURS?|DAYS?|WEEKS?|MONTHS?|YEARS?)$/i;
@@ -7372,6 +8113,126 @@ function extractExpressionFieldPaths(value) {
7372
8113
  visit(value);
7373
8114
  return results.filter(Boolean);
7374
8115
  }
8116
+ function hasAssistantDateGroupingOperator(value) {
8117
+ if (Array.isArray(value)) {
8118
+ return value.some(function (entry) { return hasAssistantDateGroupingOperator(entry); });
8119
+ }
8120
+ if (!value || typeof value !== 'object') {
8121
+ return false;
8122
+ }
8123
+ var dateTrunc = value.$dateTrunc;
8124
+ if (dateTrunc && typeof dateTrunc === 'object' && !Array.isArray(dateTrunc)) {
8125
+ var unit = normalizeOptionalString(dateTrunc.unit).toLowerCase();
8126
+ if (unit === 'day' || unit === 'week' || unit === 'month' || unit === 'quarter' || unit === 'year') {
8127
+ return true;
8128
+ }
8129
+ }
8130
+ var dateToString = value.$dateToString;
8131
+ if (dateToString && typeof dateToString === 'object' && !Array.isArray(dateToString)) {
8132
+ var format = normalizeOptionalString(dateToString.format);
8133
+ if (/%[djmUVWYGy]/i.test(format)) {
8134
+ return true;
8135
+ }
8136
+ }
8137
+ var directDateOps = ['$year', '$month', '$week', '$isoWeek', '$isoWeekYear', '$dayOfMonth', '$dayOfYear', '$dateToParts'];
8138
+ if (directDateOps.some(function (op) { return Object.prototype.hasOwnProperty.call(value, op); })) {
8139
+ return true;
8140
+ }
8141
+ return Object.keys(value).some(function (key) { return hasAssistantDateGroupingOperator(value[key]); });
8142
+ }
8143
+ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths) {
8144
+ var e_16, _a, e_17, _b;
8145
+ if (!Array.isArray(pipeline) || groupIndex <= 0 || !groupPaths.length) {
8146
+ return false;
8147
+ }
8148
+ var groupFields = new Set();
8149
+ groupPaths.forEach(function (pathValue) {
8150
+ var normalizedPath = normalizeOptionalString(pathValue);
8151
+ if (!normalizedPath) {
8152
+ return;
8153
+ }
8154
+ groupFields.add(normalizedPath);
8155
+ var rootSegment = normalizedPath.split('.')[0];
8156
+ if (rootSegment) {
8157
+ groupFields.add(rootSegment);
8158
+ }
8159
+ });
8160
+ if (!groupFields.size) {
8161
+ return false;
8162
+ }
8163
+ var stageKeys = ['$addFields', '$set', '$project'];
8164
+ for (var i = groupIndex - 1; i >= 0; i -= 1) {
8165
+ var stage = pipeline[i];
8166
+ if (!stage || typeof stage !== 'object') {
8167
+ continue;
8168
+ }
8169
+ try {
8170
+ 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()) {
8171
+ var stageKey = stageKeys_1_1.value;
8172
+ var payload = stage[stageKey];
8173
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
8174
+ continue;
8175
+ }
8176
+ try {
8177
+ 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()) {
8178
+ var groupField = groupFields_1_1.value;
8179
+ if (!Object.prototype.hasOwnProperty.call(payload, groupField)) {
8180
+ continue;
8181
+ }
8182
+ if (hasAssistantDateGroupingOperator(payload[groupField])) {
8183
+ return true;
8184
+ }
8185
+ }
8186
+ }
8187
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
8188
+ finally {
8189
+ try {
8190
+ if (groupFields_1_1 && !groupFields_1_1.done && (_b = groupFields_1.return)) _b.call(groupFields_1);
8191
+ }
8192
+ finally { if (e_17) throw e_17.error; }
8193
+ }
8194
+ }
8195
+ }
8196
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
8197
+ finally {
8198
+ try {
8199
+ if (stageKeys_1_1 && !stageKeys_1_1.done && (_a = stageKeys_1.return)) _a.call(stageKeys_1);
8200
+ }
8201
+ finally { if (e_16) throw e_16.error; }
8202
+ }
8203
+ }
8204
+ return false;
8205
+ }
8206
+ function isAssistantTimeGroupedAggregatePipeline(pipeline) {
8207
+ if (!Array.isArray(pipeline) || !pipeline.length) {
8208
+ return false;
8209
+ }
8210
+ var groupIndex = findAggregateGroupIndex(pipeline);
8211
+ if (groupIndex === -1) {
8212
+ return false;
8213
+ }
8214
+ var groupStage = pipeline[groupIndex];
8215
+ var groupPayload = groupStage === null || groupStage === void 0 ? void 0 : groupStage.$group;
8216
+ if (!groupPayload || typeof groupPayload !== 'object') {
8217
+ return false;
8218
+ }
8219
+ var groupPaths = extractGroupFieldPaths(groupPayload);
8220
+ if (groupPaths.some(function (field) { return /(date|time|created|updated|paid|invoice|timestamp|_at|month|quarter|week|year|day)/i.test(field); })) {
8221
+ return true;
8222
+ }
8223
+ if (hasAssistantDateGroupingOperator(groupPayload === null || groupPayload === void 0 ? void 0 : groupPayload._id)) {
8224
+ return true;
8225
+ }
8226
+ return isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths);
8227
+ }
8228
+ function isAssistantDirectiveDated(directive) {
8229
+ var _a;
8230
+ if (!directive || directive.type !== 'aggregate') {
8231
+ return false;
8232
+ }
8233
+ var pipeline = Array.isArray((_a = directive.payload) === null || _a === void 0 ? void 0 : _a.pipeline) ? directive.payload.pipeline : [];
8234
+ return isAssistantTimeGroupedAggregatePipeline(pipeline);
8235
+ }
7375
8236
  function findCommonPathPrefix(paths) {
7376
8237
  var _a;
7377
8238
  if (!paths.length) {
@@ -7430,7 +8291,7 @@ function isRegexMatchCondition(value) {
7430
8291
  return false;
7431
8292
  }
7432
8293
  function findRegexMatchInMatchObject(match, prefix) {
7433
- var e_16, _a, e_17, _b;
8294
+ var e_18, _a, e_19, _b;
7434
8295
  if (prefix === void 0) { prefix = ''; }
7435
8296
  if (Array.isArray(match)) {
7436
8297
  try {
@@ -7442,12 +8303,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7442
8303
  }
7443
8304
  }
7444
8305
  }
7445
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
8306
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
7446
8307
  finally {
7447
8308
  try {
7448
8309
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
7449
8310
  }
7450
- finally { if (e_16) throw e_16.error; }
8311
+ finally { if (e_18) throw e_18.error; }
7451
8312
  }
7452
8313
  return null;
7453
8314
  }
@@ -7478,12 +8339,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7478
8339
  }
7479
8340
  }
7480
8341
  }
7481
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
8342
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
7482
8343
  finally {
7483
8344
  try {
7484
8345
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
7485
8346
  }
7486
- finally { if (e_17) throw e_17.error; }
8347
+ finally { if (e_19) throw e_19.error; }
7487
8348
  }
7488
8349
  return null;
7489
8350
  }
@@ -7707,7 +8568,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
7707
8568
  return results;
7708
8569
  }
7709
8570
  function findMatchConditionForField(match, targetField, prefix) {
7710
- var e_18, _a, e_19, _b;
8571
+ var e_20, _a, e_21, _b;
7711
8572
  if (prefix === void 0) { prefix = ''; }
7712
8573
  if (!match || typeof match !== 'object') {
7713
8574
  return undefined;
@@ -7722,12 +8583,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7722
8583
  }
7723
8584
  }
7724
8585
  }
7725
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
8586
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
7726
8587
  finally {
7727
8588
  try {
7728
8589
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
7729
8590
  }
7730
- finally { if (e_18) throw e_18.error; }
8591
+ finally { if (e_20) throw e_20.error; }
7731
8592
  }
7732
8593
  return undefined;
7733
8594
  }
@@ -7754,12 +8615,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7754
8615
  }
7755
8616
  }
7756
8617
  }
7757
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
8618
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
7758
8619
  finally {
7759
8620
  try {
7760
8621
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
7761
8622
  }
7762
- finally { if (e_19) throw e_19.error; }
8623
+ finally { if (e_21) throw e_21.error; }
7763
8624
  }
7764
8625
  return undefined;
7765
8626
  }
@@ -7802,7 +8663,7 @@ function detectIdLikeValue(value) {
7802
8663
  return false;
7803
8664
  }
7804
8665
  function detectChemicalIdFromProbe(probeDocs, fields) {
7805
- var e_20, _a, e_21, _b;
8666
+ var e_22, _a, e_23, _b;
7806
8667
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
7807
8668
  return false;
7808
8669
  }
@@ -7814,7 +8675,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7814
8675
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
7815
8676
  var doc = probeDocs_1_1.value;
7816
8677
  try {
7817
- 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()) {
8678
+ 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()) {
7818
8679
  var field = targets_1_1.value;
7819
8680
  var value = getValueAtPath(doc, field);
7820
8681
  if (Array.isArray(value)) {
@@ -7827,21 +8688,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7827
8688
  }
7828
8689
  }
7829
8690
  }
7830
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
8691
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
7831
8692
  finally {
7832
8693
  try {
7833
8694
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
7834
8695
  }
7835
- finally { if (e_21) throw e_21.error; }
8696
+ finally { if (e_23) throw e_23.error; }
7836
8697
  }
7837
8698
  }
7838
8699
  }
7839
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
8700
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
7840
8701
  finally {
7841
8702
  try {
7842
8703
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
7843
8704
  }
7844
- finally { if (e_20) throw e_20.error; }
8705
+ finally { if (e_22) throw e_22.error; }
7845
8706
  }
7846
8707
  return false;
7847
8708
  }
@@ -8062,8 +8923,8 @@ function buildChemicalIdFieldCandidates(field) {
8062
8923
  }
8063
8924
  function applyChemicalNameLookupFallbackToQuery(params) {
8064
8925
  return __awaiter(this, void 0, void 0, function () {
8065
- 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;
8066
- var e_22, _a;
8926
+ 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;
8927
+ var e_24, _a;
8067
8928
  var _b;
8068
8929
  return __generator(this, function (_c) {
8069
8930
  switch (_c.label) {
@@ -8176,14 +9037,14 @@ function applyChemicalNameLookupFallbackToQuery(params) {
8176
9037
  return [3 /*break*/, 3];
8177
9038
  case 6: return [3 /*break*/, 9];
8178
9039
  case 7:
8179
- e_22_1 = _c.sent();
8180
- e_22 = { error: e_22_1 };
9040
+ e_24_1 = _c.sent();
9041
+ e_24 = { error: e_24_1 };
8181
9042
  return [3 /*break*/, 9];
8182
9043
  case 8:
8183
9044
  try {
8184
9045
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
8185
9046
  }
8186
- finally { if (e_22) throw e_22.error; }
9047
+ finally { if (e_24) throw e_24.error; }
8187
9048
  return [7 /*endfinally*/];
8188
9049
  case 9: return [2 /*return*/, null];
8189
9050
  }
@@ -8277,8 +9138,8 @@ function lookupIdsForNameMatch(params) {
8277
9138
  }
8278
9139
  function applyIdLookupFallbackToQuery(params) {
8279
9140
  return __awaiter(this, void 0, void 0, function () {
8280
- 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;
8281
- var e_24, _c, e_23, _d;
9141
+ 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;
9142
+ var e_26, _c, e_25, _d;
8282
9143
  var _e;
8283
9144
  return __generator(this, function (_f) {
8284
9145
  switch (_f.label) {
@@ -8348,7 +9209,7 @@ function applyIdLookupFallbackToQuery(params) {
8348
9209
  _f.label = 5;
8349
9210
  case 5:
8350
9211
  _f.trys.push([5, 14, 15, 16]);
8351
- candidates_3 = (e_23 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
9212
+ candidates_3 = (e_25 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8352
9213
  _f.label = 6;
8353
9214
  case 6:
8354
9215
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -8415,28 +9276,28 @@ function applyIdLookupFallbackToQuery(params) {
8415
9276
  return [3 /*break*/, 6];
8416
9277
  case 13: return [3 /*break*/, 16];
8417
9278
  case 14:
8418
- e_23_1 = _f.sent();
8419
- e_23 = { error: e_23_1 };
9279
+ e_25_1 = _f.sent();
9280
+ e_25 = { error: e_25_1 };
8420
9281
  return [3 /*break*/, 16];
8421
9282
  case 15:
8422
9283
  try {
8423
9284
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
8424
9285
  }
8425
- finally { if (e_23) throw e_23.error; }
9286
+ finally { if (e_25) throw e_25.error; }
8426
9287
  return [7 /*endfinally*/];
8427
9288
  case 16:
8428
9289
  conditions_1_1 = conditions_1.next();
8429
9290
  return [3 /*break*/, 4];
8430
9291
  case 17: return [3 /*break*/, 20];
8431
9292
  case 18:
8432
- e_24_1 = _f.sent();
8433
- e_24 = { error: e_24_1 };
9293
+ e_26_1 = _f.sent();
9294
+ e_26 = { error: e_26_1 };
8434
9295
  return [3 /*break*/, 20];
8435
9296
  case 19:
8436
9297
  try {
8437
9298
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
8438
9299
  }
8439
- finally { if (e_24) throw e_24.error; }
9300
+ finally { if (e_26) throw e_26.error; }
8440
9301
  return [7 /*endfinally*/];
8441
9302
  case 20: return [2 /*return*/, null];
8442
9303
  }
@@ -8522,12 +9383,12 @@ function replaceAggregateDateField(pipeline, fromField, toField) {
8522
9383
  return value;
8523
9384
  }
8524
9385
  if (value && typeof value === 'object') {
8525
- var next_2 = {};
9386
+ var next_3 = {};
8526
9387
  Object.keys(value).forEach(function (key) {
8527
9388
  var nextKey = key === fromField ? toField : key;
8528
- next_2[nextKey] = replacer(value[key]);
9389
+ next_3[nextKey] = replacer(value[key]);
8529
9390
  });
8530
- return next_2;
9391
+ return next_3;
8531
9392
  }
8532
9393
  if (typeof value === 'string') {
8533
9394
  var fromRef = "$".concat(fromField);
@@ -9288,7 +10149,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection) {
9288
10149
  throw new Error('AI assistant report builder bridge: Collection is not configured for report builder.');
9289
10150
  }
9290
10151
  function findQueryDateField(query) {
9291
- var e_25, _a, e_26, _b;
10152
+ var e_27, _a, e_28, _b;
9292
10153
  if (!query || typeof query !== 'object') {
9293
10154
  return null;
9294
10155
  }
@@ -9302,12 +10163,12 @@ function findQueryDateField(query) {
9302
10163
  }
9303
10164
  }
9304
10165
  }
9305
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
10166
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
9306
10167
  finally {
9307
10168
  try {
9308
10169
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
9309
10170
  }
9310
- finally { if (e_25) throw e_25.error; }
10171
+ finally { if (e_27) throw e_27.error; }
9311
10172
  }
9312
10173
  return null;
9313
10174
  }
@@ -9326,12 +10187,12 @@ function findQueryDateField(query) {
9326
10187
  }
9327
10188
  }
9328
10189
  }
9329
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
10190
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
9330
10191
  finally {
9331
10192
  try {
9332
10193
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
9333
10194
  }
9334
- finally { if (e_26) throw e_26.error; }
10195
+ finally { if (e_28) throw e_28.error; }
9335
10196
  }
9336
10197
  return null;
9337
10198
  }
@@ -9369,7 +10230,7 @@ function extractDateRangeConditions(query) {
9369
10230
  });
9370
10231
  return results;
9371
10232
  }
9372
- function expandQueryDateFallbacks(query) {
10233
+ function expandQueryDateFallbacks(query, schemaFields) {
9373
10234
  if (!query || typeof query !== 'object') {
9374
10235
  return null;
9375
10236
  }
@@ -9402,21 +10263,16 @@ function expandQueryDateFallbacks(query) {
9402
10263
  }
9403
10264
  var dateConditions = extractDateRangeConditions(entry);
9404
10265
  dateConditions.forEach(function (condition) {
9405
- var fallback = AI_ASSISTANT_DATE_FALLBACKS[condition.field];
9406
- if (fallback && !existingFields.has(fallback)) {
9407
- extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, fallback)], false);
9408
- existingFields.add(fallback);
9409
- pushField(fallback);
9410
- }
10266
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
10267
+ expansions.forEach(function (field) {
10268
+ if (existingFields.has(field)) {
10269
+ return;
10270
+ }
10271
+ extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, field)], false);
10272
+ existingFields.add(field);
10273
+ pushField(field);
10274
+ });
9411
10275
  });
9412
- if (!existingFields.has('date_original')) {
9413
- var candidate = dateConditions.find(function (condition) { return condition.field.startsWith('date_') && condition.field !== 'date_original'; });
9414
- if (candidate) {
9415
- extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, candidate.field, 'date_original')], false);
9416
- existingFields.add('date_original');
9417
- pushField('date_original');
9418
- }
9419
- }
9420
10276
  });
9421
10277
  return extended;
9422
10278
  };
@@ -9460,11 +10316,12 @@ function expandQueryDateFallbacks(query) {
9460
10316
  }
9461
10317
  return { query: result.value, fields: addedFields };
9462
10318
  }
9463
- function buildDateFieldExpansionList(field) {
10319
+ function buildDateFieldExpansionList(field, schemaFields) {
9464
10320
  var normalized = normalizeOptionalString(field);
9465
10321
  if (!normalized) {
9466
10322
  return [];
9467
10323
  }
10324
+ var normalizedLower = normalized.toLowerCase();
9468
10325
  var expansions = new Set();
9469
10326
  var add = function (value) {
9470
10327
  if (value && value !== normalized) {
@@ -9475,15 +10332,46 @@ function buildDateFieldExpansionList(field) {
9475
10332
  if (fallback) {
9476
10333
  add(fallback);
9477
10334
  }
9478
- if (normalized.startsWith('date_') || normalized === 'date' || normalized.endsWith('_date')) {
10335
+ if (normalizedLower.startsWith('date_')
10336
+ || normalizedLower === 'date'
10337
+ || normalizedLower.endsWith('_date')
10338
+ || normalizedLower.includes('_date_')) {
9479
10339
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9480
10340
  }
9481
- if (normalized === 'createdAt' || normalized === 'updatedAt') {
10341
+ if (normalizedLower === 'createdat' || normalizedLower === 'updatedat') {
9482
10342
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9483
10343
  }
10344
+ var normalizedSchemaFields = Array.isArray(schemaFields)
10345
+ ? schemaFields
10346
+ .map(function (value) { return normalizeOptionalString(value); })
10347
+ .filter(Boolean)
10348
+ : [];
10349
+ if (normalizedSchemaFields.length) {
10350
+ var dateFieldPattern_1 = /(^|\.)(date($|_)|createdat$|updatedat$|[a-z0-9_]+_at$|[a-z0-9_]+_date$|[a-z0-9_]+_date_[a-z0-9_]*$)/i;
10351
+ var addedFromSchema_1 = 0;
10352
+ normalizedSchemaFields.forEach(function (schemaField) {
10353
+ if (addedFromSchema_1 >= AI_ASSISTANT_DATE_EXPANSION_SCHEMA_MAX_FIELDS) {
10354
+ return;
10355
+ }
10356
+ if (schemaField.includes('$')) {
10357
+ return;
10358
+ }
10359
+ if (!dateFieldPattern_1.test(schemaField)) {
10360
+ return;
10361
+ }
10362
+ if (schemaField === normalized) {
10363
+ return;
10364
+ }
10365
+ var beforeSize = expansions.size;
10366
+ add(schemaField);
10367
+ if (expansions.size > beforeSize) {
10368
+ addedFromSchema_1 += 1;
10369
+ }
10370
+ });
10371
+ }
9484
10372
  return Array.from(expansions);
9485
10373
  }
9486
- function expandAggregateDateMatchFallback(pipeline) {
10374
+ function expandAggregateDateMatchFallback(pipeline, schemaFields) {
9487
10375
  if (!Array.isArray(pipeline)) {
9488
10376
  return null;
9489
10377
  }
@@ -9516,7 +10404,7 @@ function expandAggregateDateMatchFallback(pipeline) {
9516
10404
  }
9517
10405
  var conditions = extractDateRangeConditions(entry);
9518
10406
  conditions.forEach(function (condition) {
9519
- var expansions = buildDateFieldExpansionList(condition.field);
10407
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
9520
10408
  expansions.forEach(function (field) {
9521
10409
  if (existingFields.has(field)) {
9522
10410
  return;
@@ -9553,7 +10441,7 @@ function resolveQueryDateFieldFallback(query) {
9553
10441
  return { from: dateField, to: fallback };
9554
10442
  }
9555
10443
  function containsForbiddenMongoOperators(value) {
9556
- var e_27, _a;
10444
+ var e_29, _a;
9557
10445
  if (!value || typeof value !== 'object') {
9558
10446
  return false;
9559
10447
  }
@@ -9572,12 +10460,12 @@ function containsForbiddenMongoOperators(value) {
9572
10460
  }
9573
10461
  }
9574
10462
  }
9575
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
10463
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
9576
10464
  finally {
9577
10465
  try {
9578
10466
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9579
10467
  }
9580
- finally { if (e_27) throw e_27.error; }
10468
+ finally { if (e_29) throw e_29.error; }
9581
10469
  }
9582
10470
  return false;
9583
10471
  }
@@ -10012,8 +10900,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
10012
10900
  }
10013
10901
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10014
10902
  return __awaiter(this, void 0, void 0, function () {
10015
- var _a, _b, _c, _d, message, payload, status_1, e_28_1;
10016
- var _e, e_28, _f, _g;
10903
+ var _a, _b, _c, _d, message, payload, status_1, e_30_1;
10904
+ var _e, e_30, _f, _g;
10017
10905
  return __generator(this, function (_h) {
10018
10906
  switch (_h.label) {
10019
10907
  case 0:
@@ -10040,8 +10928,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10040
10928
  return [3 /*break*/, 1];
10041
10929
  case 4: return [3 /*break*/, 11];
10042
10930
  case 5:
10043
- e_28_1 = _h.sent();
10044
- e_28 = { error: e_28_1 };
10931
+ e_30_1 = _h.sent();
10932
+ e_30 = { error: e_30_1 };
10045
10933
  return [3 /*break*/, 11];
10046
10934
  case 6:
10047
10935
  _h.trys.push([6, , 9, 10]);
@@ -10052,7 +10940,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10052
10940
  _h.label = 8;
10053
10941
  case 8: return [3 /*break*/, 10];
10054
10942
  case 9:
10055
- if (e_28) throw e_28.error;
10943
+ if (e_30) throw e_30.error;
10056
10944
  return [7 /*endfinally*/];
10057
10945
  case 10: return [7 /*endfinally*/];
10058
10946
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -10480,9 +11368,19 @@ var AI_ASSISTANT_DATA_REQUEST_PATTERNS = [
10480
11368
  /\bmissing\b/,
10481
11369
  /\bgroup(ed)? by\b/,
10482
11370
  /\bbreakdown\b/,
11371
+ /\bby day\b/,
11372
+ /\bby week\b/,
11373
+ /\bby month\b/,
11374
+ /\bby quarter\b/,
11375
+ /\bby year\b/,
11376
+ /\bby (time|date)\s+period\b/,
10483
11377
  /\bper day\b/,
10484
11378
  /\bper week\b/,
10485
- /\bper month\b/
11379
+ /\bper month\b/,
11380
+ /\bper quarter\b/,
11381
+ /\bper year\b/,
11382
+ /\bover the last\b/,
11383
+ /\bpast\s+\d+\b/
10486
11384
  ];
10487
11385
  var AI_ASSISTANT_NAVIGATION_REQUEST_PATTERNS = [
10488
11386
  /\bwhere\b/,
@@ -10635,13 +11533,135 @@ function classifyAssistantRequestType(message, plannerOutput) {
10635
11533
  plannerIntentType: plannerIntentRaw || undefined
10636
11534
  };
10637
11535
  }
10638
- function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText) {
11536
+ function resolveAssistantRequestedTimeGrain(message, plannerOutput) {
11537
+ var _a, _b;
11538
+ 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();
11539
+ if (plannerGrain === 'day' || plannerGrain === 'week' || plannerGrain === 'month' || plannerGrain === 'quarter' || plannerGrain === 'year') {
11540
+ return plannerGrain;
11541
+ }
11542
+ var text = normalizeOptionalString(message).toLowerCase();
11543
+ if (!text) {
11544
+ return null;
11545
+ }
11546
+ var mapping = [
11547
+ { grain: 'quarter', pattern: /\b(quarter|quarters|quarterly|qoq)\b/i },
11548
+ { grain: 'month', pattern: /\b(month|months|monthly|mom)\b/i },
11549
+ { grain: 'week', pattern: /\b(week|weeks|weekly|wow)\b/i },
11550
+ { grain: 'day', pattern: /\b(day|days|daily)\b/i },
11551
+ { grain: 'year', pattern: /\b(year|years|yearly|yoy)\b/i }
11552
+ ];
11553
+ var match = mapping.find(function (entry) { return entry.pattern.test(text); });
11554
+ return (match === null || match === void 0 ? void 0 : match.grain) || null;
11555
+ }
11556
+ function hasAssistantDatedLanguage(message) {
11557
+ var text = normalizeOptionalString(message).toLowerCase();
11558
+ if (!text) {
11559
+ return false;
11560
+ }
11561
+ var patterns = [
11562
+ /\b(by|per)\s+(day|week|month|quarter|year|time\s*period|date\s*period)\b/i,
11563
+ /\b(over|across)\s+time\b/i,
11564
+ /\btime\s*series\b/i,
11565
+ /\btrend(?:ing|s)?\b/i,
11566
+ /\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,
11567
+ /\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,
11568
+ /\bmonth\s+over\s+month\b/i,
11569
+ /\bquarter\s+over\s+quarter\b/i,
11570
+ /\byear\s+over\s+year\b/i
11571
+ ];
11572
+ return patterns.some(function (pattern) { return pattern.test(text); });
11573
+ }
11574
+ function hasAssistantGroupedLanguage(message) {
11575
+ var text = normalizeOptionalString(message).toLowerCase();
11576
+ if (!text) {
11577
+ return false;
11578
+ }
11579
+ var patterns = [
11580
+ /\bbreakdown\b/i,
11581
+ /\bgroup(?:ed)?\s+by\b/i,
11582
+ /\bby\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
11583
+ /\bper\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
11584
+ /\bover\s+time\b/i,
11585
+ /\btime\s*series\b/i,
11586
+ /\btrend(?:ing|s)?\b/i,
11587
+ /\bmonth\s+over\s+month\b/i,
11588
+ /\bquarter\s+over\s+quarter\b/i,
11589
+ /\byear\s+over\s+year\b/i
11590
+ ];
11591
+ return patterns.some(function (pattern) { return pattern.test(text); });
11592
+ }
11593
+ function shouldPreferAssistantListDirective(message, plannerOutput, requestClassification) {
11594
+ var _a, _b, _c, _d, _e;
11595
+ if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
11596
+ return false;
11597
+ }
11598
+ var text = normalizeOptionalString(message).toLowerCase();
11599
+ if (!text) {
11600
+ return false;
11601
+ }
11602
+ if (hasAssistantGroupedLanguage(text)) {
11603
+ return false;
11604
+ }
11605
+ var plannerGroupBy = normalizeOptionalString((_b = (_a = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _a === void 0 ? void 0 : _a.queryPlan) === null || _b === void 0 ? void 0 : _b.groupBy).toLowerCase();
11606
+ if (plannerGroupBy && plannerGroupBy !== 'none' && plannerGroupBy !== 'null') {
11607
+ return false;
11608
+ }
11609
+ var plannerMetric = normalizeOptionalString((_c = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _c === void 0 ? void 0 : _c.metric).toLowerCase();
11610
+ var plannerLimit = normalizeOptionalNumber((_e = (_d = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _d === void 0 ? void 0 : _d.queryPlan) === null || _e === void 0 ? void 0 : _e.limit) || 0;
11611
+ var hasListVerb = /\b(show|list|display|give|get)\b/i.test(text);
11612
+ var hasLimitCue = /\b(last|latest|recent|top)\s+\d+\b/i.test(text) || plannerLimit > 0;
11613
+ var hasWindowCue = /\b(this\s+(day|week|month|quarter|year)|last\s+\d+\s+(day|days|week|weeks|month|months)|past\s+\d+\s+(day|days|week|weeks|month|months))\b/i.test(text);
11614
+ if (plannerMetric.startsWith('last_') && plannerGroupBy !== 'none') {
11615
+ return true;
11616
+ }
11617
+ return hasListVerb && (hasLimitCue || hasWindowCue);
11618
+ }
11619
+ function shouldEnforceAssistantDatedDirective(message, plannerOutput, requestClassification) {
11620
+ if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
11621
+ return false;
11622
+ }
11623
+ if (shouldPreferAssistantListDirective(message, plannerOutput, requestClassification)) {
11624
+ return false;
11625
+ }
11626
+ if (resolveAssistantRequestedTimeGrain(message, plannerOutput)) {
11627
+ return true;
11628
+ }
11629
+ return hasAssistantDatedLanguage(message);
11630
+ }
11631
+ function buildAssistantDirectiveStyleHint(params) {
11632
+ if (params.preferList && !params.enforceDated) {
11633
+ return [
11634
+ 'Report style intent: List.',
11635
+ '- Prefer REPORT_BUILDER_READ for record-level results (not grouped counts).',
11636
+ '- Apply date window filters and sort by the primary date field descending.',
11637
+ '- If user asks for location, include location name fields (location/location_name) and id_location for lookup fallback; do not return only location_type unless explicitly requested.'
11638
+ ].join('\n');
11639
+ }
11640
+ if (!params.enforceDated) {
11641
+ return '';
11642
+ }
11643
+ var grainLabel = params.requestedTimeGrain || 'time period';
11644
+ return [
11645
+ 'Report style intent: Dated.',
11646
+ "Requested time grain: ".concat(grainLabel, "."),
11647
+ '- Return REPORT_BUILDER_AGG (not REPORT_BUILDER_READ).',
11648
+ '- Ensure the pipeline groups by the requested time grain and requested breakdown dimensions.',
11649
+ '- For "last/past N" windows, use full completed calendar-period bounds in UTC unless the user asks for period-to-date.',
11650
+ params.strict ? '- STRICT: if unsure, still prefer REPORT_BUILDER_AGG.' : ''
11651
+ ].filter(Boolean).join('\n');
11652
+ }
11653
+ function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText, directiveStyleHintText, mode) {
11654
+ if (mode === void 0) { mode = 'any'; }
10639
11655
  var trimmedContext = normalizeOptionalString(contextText);
10640
11656
  var contextBlock = trimmedContext ? "\n\nContext:\n".concat(trimmedContext) : '';
10641
11657
  var trimmedHistory = normalizeOptionalString(historyText);
10642
11658
  var historyBlock = trimmedHistory ? "\n\nConversation so far:\n".concat(trimmedHistory) : '';
10643
- var instruction = '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_READ or REPORT_BUILDER_AGG directive line. Do not include any other text.';
10644
- return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(instruction).trim();
11659
+ var trimmedStyleHint = normalizeOptionalString(directiveStyleHintText);
11660
+ var styleHintBlock = trimmedStyleHint ? "\n\nDirective style hints:\n".concat(trimmedStyleHint) : '';
11661
+ var instruction = mode === 'aggregate_only'
11662
+ ? '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_AGG directive line. Do not include any other text.'
11663
+ : '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_READ or REPORT_BUILDER_AGG directive line. Do not include any other text.';
11664
+ return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock).concat(styleHintBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(instruction).trim();
10645
11665
  }
10646
11666
  function buildAssistantCodexPrompt(message, attachmentText, historyText, contextText) {
10647
11667
  var trimmedContext = normalizeOptionalString(contextText);
@@ -10658,7 +11678,7 @@ function resolveAssistantPlannerEnabled() {
10658
11678
  return raw === undefined ? true : raw === true;
10659
11679
  }
10660
11680
  function resolveAssistantPlannerKnownRoutes() {
10661
- var e_29, _a;
11681
+ var e_31, _a;
10662
11682
  var _b;
10663
11683
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10664
11684
  var unique = new Set();
@@ -10671,12 +11691,12 @@ function resolveAssistantPlannerKnownRoutes() {
10671
11691
  }
10672
11692
  }
10673
11693
  }
10674
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
11694
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
10675
11695
  finally {
10676
11696
  try {
10677
11697
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
10678
11698
  }
10679
- finally { if (e_29) throw e_29.error; }
11699
+ finally { if (e_31) throw e_31.error; }
10680
11700
  }
10681
11701
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
10682
11702
  }
@@ -10919,7 +11939,7 @@ function normalizeRouteMatchKey(value) {
10919
11939
  return normalizeRouteKey(value).toLowerCase();
10920
11940
  }
10921
11941
  function buildClientRouteIndex() {
10922
- var e_30, _a;
11942
+ var e_32, _a;
10923
11943
  var _b;
10924
11944
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10925
11945
  var set = new Set();
@@ -10938,12 +11958,12 @@ function buildClientRouteIndex() {
10938
11958
  }
10939
11959
  }
10940
11960
  }
10941
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
11961
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
10942
11962
  finally {
10943
11963
  try {
10944
11964
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
10945
11965
  }
10946
- finally { if (e_30) throw e_30.error; }
11966
+ finally { if (e_32) throw e_32.error; }
10947
11967
  }
10948
11968
  return { set: set, map: map, size: routes.length };
10949
11969
  }
@@ -11084,7 +12104,7 @@ function sanitizeAssistantResponse(value) {
11084
12104
  return normalizeAssistantRoutes(normalizedCurrency);
11085
12105
  }
11086
12106
  function evaluateAssistantGuardrails(message) {
11087
- var e_31, _a;
12107
+ var e_33, _a;
11088
12108
  var normalized = String(message || '').toLowerCase();
11089
12109
  var patterns = [
11090
12110
  {
@@ -11130,12 +12150,12 @@ function evaluateAssistantGuardrails(message) {
11130
12150
  }
11131
12151
  }
11132
12152
  }
11133
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
12153
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
11134
12154
  finally {
11135
12155
  try {
11136
12156
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
11137
12157
  }
11138
- finally { if (e_31) throw e_31.error; }
12158
+ finally { if (e_33) throw e_33.error; }
11139
12159
  }
11140
12160
  return null;
11141
12161
  }
@@ -11250,7 +12270,7 @@ function tokenizeArithmeticExpression(expression) {
11250
12270
  return tokens;
11251
12271
  }
11252
12272
  function evaluateArithmeticExpression(expression) {
11253
- var e_32, _a, e_33, _b;
12273
+ var e_34, _a, e_35, _b;
11254
12274
  var tokens = tokenizeArithmeticExpression(expression);
11255
12275
  if (!tokens || !tokens.length) {
11256
12276
  return null;
@@ -11307,12 +12327,12 @@ function evaluateArithmeticExpression(expression) {
11307
12327
  prevToken = token;
11308
12328
  }
11309
12329
  }
11310
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
12330
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
11311
12331
  finally {
11312
12332
  try {
11313
12333
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
11314
12334
  }
11315
- finally { if (e_32) throw e_32.error; }
12335
+ finally { if (e_34) throw e_34.error; }
11316
12336
  }
11317
12337
  while (ops.length) {
11318
12338
  var op = ops.pop();
@@ -11352,12 +12372,12 @@ function evaluateArithmeticExpression(expression) {
11352
12372
  stack.push(Number(token));
11353
12373
  }
11354
12374
  }
11355
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
12375
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
11356
12376
  finally {
11357
12377
  try {
11358
12378
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
11359
12379
  }
11360
- finally { if (e_33) throw e_33.error; }
12380
+ finally { if (e_35) throw e_35.error; }
11361
12381
  }
11362
12382
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
11363
12383
  return null;
@@ -11541,8 +12561,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
11541
12561
  }
11542
12562
  function readAttachmentContents(attachments) {
11543
12563
  return __awaiter(this, void 0, void 0, function () {
11544
- 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;
11545
- var e_34, _b;
12564
+ 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;
12565
+ var e_36, _b;
11546
12566
  return __generator(this, function (_c) {
11547
12567
  switch (_c.label) {
11548
12568
  case 0:
@@ -11621,14 +12641,14 @@ function readAttachmentContents(attachments) {
11621
12641
  return [3 /*break*/, 2];
11622
12642
  case 10: return [3 /*break*/, 13];
11623
12643
  case 11:
11624
- e_34_1 = _c.sent();
11625
- e_34 = { error: e_34_1 };
12644
+ e_36_1 = _c.sent();
12645
+ e_36 = { error: e_36_1 };
11626
12646
  return [3 /*break*/, 13];
11627
12647
  case 12:
11628
12648
  try {
11629
12649
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
11630
12650
  }
11631
- finally { if (e_34) throw e_34.error; }
12651
+ finally { if (e_36) throw e_36.error; }
11632
12652
  return [7 /*endfinally*/];
11633
12653
  case 13: return [2 /*return*/, {
11634
12654
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -11869,7 +12889,7 @@ function estimateUsage(messages, responseText, model) {
11869
12889
  };
11870
12890
  }
11871
12891
  function evaluateGuardrails(message) {
11872
- var e_35, _a;
12892
+ var e_37, _a;
11873
12893
  var normalized = String(message || '').toLowerCase();
11874
12894
  var patterns = [
11875
12895
  { 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.' },
@@ -11891,12 +12911,12 @@ function evaluateGuardrails(message) {
11891
12911
  }
11892
12912
  }
11893
12913
  }
11894
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
12914
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
11895
12915
  finally {
11896
12916
  try {
11897
12917
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
11898
12918
  }
11899
- finally { if (e_35) throw e_35.error; }
12919
+ finally { if (e_37) throw e_37.error; }
11900
12920
  }
11901
12921
  return null;
11902
12922
  }