@resolveio/server-lib 22.0.21 → 22.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -200,17 +200,33 @@ var AI_ASSISTANT_DATE_FALLBACKS = {
200
200
  date_created: 'createdAt',
201
201
  createdAt: 'date_created',
202
202
  date_invoice: 'date_invoiced',
203
- date_invoiced: 'date_invoice'
203
+ date_invoiced: 'date_invoice',
204
+ date_last: 'date_next',
205
+ date_next: 'date_last',
206
+ date_treated: 'date_scheduled',
207
+ date_scheduled: 'date_treated'
204
208
  };
205
209
  var AI_ASSISTANT_DATE_EXPANSION_FIELDS = [
206
210
  'date',
207
211
  'date_start',
208
212
  'date_end',
209
213
  'date_original',
214
+ 'date_next',
215
+ 'date_last',
216
+ 'date_scheduled',
217
+ 'date_treated',
218
+ 'date_completed',
219
+ 'date_closed',
220
+ 'date_due',
221
+ 'date_paid',
222
+ 'date_invoice',
223
+ 'date_invoiced',
224
+ 'date_updated',
210
225
  'date_created',
211
226
  'createdAt',
212
227
  'updatedAt'
213
228
  ];
229
+ var AI_ASSISTANT_DATE_EXPANSION_SCHEMA_MAX_FIELDS = 12;
214
230
  var AI_ASSISTANT_BLOCKED_COLLECTIONS = new Set([
215
231
  'user-groups',
216
232
  'logged-in-users',
@@ -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, 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,54 @@ 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
+ enforceDatedDirective = shouldEnforceAssistantDatedDirective(message, plannerOutput || undefined, requestClassification);
1692
+ directiveStyleHint = buildAssistantDirectiveStyleHint({
1693
+ enforceDated: enforceDatedDirective,
1694
+ requestedTimeGrain: requestedTimeGrain
1695
+ });
1696
+ directivePromptMode = enforceDatedDirective ? 'aggregate_only' : 'any';
1697
+ datedDirectiveRetryUsed = false;
1670
1698
  recordStep('Planning: request classification', {
1671
1699
  type: requestClassification.type,
1672
1700
  source: requestClassification.source,
1673
1701
  plannerIntentType: requestClassification.plannerIntentType || undefined,
1674
- dataQuestion: dataQuestion
1702
+ dataQuestion: dataQuestion,
1703
+ reportStyle: enforceDatedDirective ? 'dated' : undefined,
1704
+ timeGrain: requestedTimeGrain || undefined
1675
1705
  });
1676
1706
  responseText = '';
1677
1707
  directiveText = '';
1678
1708
  directive = null;
1679
1709
  if (!dataQuestion) return [3 /*break*/, 14];
1680
1710
  recordStep('Directive: determine tool', { type: 'data-question' });
1681
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1682
- _v.label = 11;
1711
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1712
+ _3.label = 11;
1683
1713
  case 11:
1684
- _v.trys.push([11, 13, , 14]);
1714
+ _3.trys.push([11, 13, , 14]);
1685
1715
  directiveStart = Date.now();
1686
1716
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1687
1717
  case 12:
1688
- directiveText = _v.sent();
1718
+ directiveText = _3.sent();
1689
1719
  accumulateCodexUsage(directivePrompt, directiveText);
1690
1720
  timingBreakdown.directiveMs = Date.now() - directiveStart;
1691
1721
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1693,17 +1723,17 @@ function executeAiAssistantCodexRun(payload, context) {
1693
1723
  directive = forcedDirective;
1694
1724
  directiveSource = 'model';
1695
1725
  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) || '');
1726
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_l = directive.payload) === null || _l === void 0 ? void 0 : _l.collection) || '');
1697
1727
  recordStep('Directive resolved', {
1698
1728
  source: directiveSource,
1699
1729
  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
1730
+ collection: normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1731
+ permissionView: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.permissionView) || undefined
1702
1732
  });
1703
1733
  }
1704
1734
  return [3 /*break*/, 14];
1705
1735
  case 13:
1706
- _c = _v.sent();
1736
+ _c = _3.sent();
1707
1737
  return [3 /*break*/, 14];
1708
1738
  case 14:
1709
1739
  if (!!directive) return [3 /*break*/, 16];
@@ -1711,33 +1741,33 @@ function executeAiAssistantCodexRun(payload, context) {
1711
1741
  initialStart = Date.now();
1712
1742
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
1713
1743
  case 15:
1714
- responseText = _v.sent();
1744
+ responseText = _3.sent();
1715
1745
  accumulateCodexUsage(prompt_1, responseText);
1716
1746
  timingBreakdown.initialResponseMs = Date.now() - initialStart;
1717
1747
  directive = extractAssistantMongoDirective(responseText);
1718
1748
  if (directive) {
1719
1749
  directiveSource = 'model';
1720
1750
  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) || '');
1751
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || '');
1722
1752
  recordStep('Directive resolved', {
1723
1753
  source: directiveSource,
1724
1754
  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
1755
+ collection: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || undefined,
1756
+ permissionView: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.permissionView) || undefined
1727
1757
  });
1728
1758
  }
1729
- _v.label = 16;
1759
+ _3.label = 16;
1730
1760
  case 16:
1731
1761
  if (!(!directive && dataQuestion)) return [3 /*break*/, 20];
1732
1762
  recordStep('Directive: forced retry', { mode: 'directive-only' });
1733
- directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1734
- _v.label = 17;
1763
+ directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1764
+ _3.label = 17;
1735
1765
  case 17:
1736
- _v.trys.push([17, 19, , 20]);
1766
+ _3.trys.push([17, 19, , 20]);
1737
1767
  forcedStart = Date.now();
1738
1768
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1739
1769
  case 18:
1740
- directiveText = _v.sent();
1770
+ directiveText = _3.sent();
1741
1771
  accumulateCodexUsage(directivePrompt, directiveText);
1742
1772
  timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
1743
1773
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1745,26 +1775,108 @@ function executeAiAssistantCodexRun(payload, context) {
1745
1775
  directive = forcedDirective;
1746
1776
  directiveSource = 'forced';
1747
1777
  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) || '');
1778
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || '');
1749
1779
  recordStep('Directive resolved', {
1750
1780
  source: directiveSource,
1751
1781
  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
1782
+ collection: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection) || undefined,
1783
+ permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || undefined
1754
1784
  });
1755
1785
  }
1756
1786
  return [3 /*break*/, 20];
1757
1787
  case 19:
1758
- _d = _v.sent();
1788
+ _d = _3.sent();
1759
1789
  return [3 /*break*/, 20];
1760
1790
  case 20:
1791
+ if (!(directive && enforceDatedDirective && !isAssistantDirectiveDated(directive))) return [3 /*break*/, 24];
1792
+ recordStep('Directive: dated retry', {
1793
+ currentType: directive.type,
1794
+ timeGrain: requestedTimeGrain || undefined
1795
+ });
1796
+ strictDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1797
+ enforceDated: true,
1798
+ requestedTimeGrain: requestedTimeGrain,
1799
+ strict: true
1800
+ }), 'aggregate_only');
1801
+ _3.label = 21;
1802
+ case 21:
1803
+ _3.trys.push([21, 23, , 24]);
1804
+ strictStart = Date.now();
1805
+ return [4 /*yield*/, runCodexInWorkerThread(strictDirectivePrompt, runOptions, codexConfig, streamProgress)];
1806
+ case 22:
1807
+ strictDirectiveText = _3.sent();
1808
+ accumulateCodexUsage(strictDirectivePrompt, strictDirectiveText);
1809
+ timingBreakdown.forcedDirectiveMs += Date.now() - strictStart;
1810
+ strictDirective = extractAssistantMongoDirective(strictDirectiveText);
1811
+ strictDirectiveIsDated = strictDirective ? isAssistantDirectiveDated(strictDirective) : false;
1812
+ shouldUseStrictDirective = !!strictDirective && strictDirective.type === 'aggregate';
1813
+ if (shouldUseStrictDirective && strictDirective) {
1814
+ directive = strictDirective;
1815
+ directiveSource = 'forced';
1816
+ lastDirective = strictDirective;
1817
+ datedDirectiveRetryUsed = true;
1818
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || '');
1819
+ recordStep('Directive resolved', {
1820
+ source: directiveSource,
1821
+ type: directive.type,
1822
+ collection: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.collection) || undefined,
1823
+ permissionView: normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.permissionView) || undefined,
1824
+ reportStyle: strictDirectiveIsDated ? 'dated' : 'aggregate_fallback',
1825
+ timeGrain: requestedTimeGrain || undefined
1826
+ });
1827
+ }
1828
+ return [3 /*break*/, 24];
1829
+ case 23:
1830
+ _e = _3.sent();
1831
+ return [3 /*break*/, 24];
1832
+ case 24:
1833
+ if (!(directive && enforceDatedDirective && directive.type === 'read')) return [3 /*break*/, 28];
1834
+ recordStep('Directive: dated guard retry', {
1835
+ currentType: directive.type,
1836
+ timeGrain: requestedTimeGrain || undefined
1837
+ });
1838
+ guardDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1839
+ enforceDated: true,
1840
+ requestedTimeGrain: requestedTimeGrain,
1841
+ strict: true
1842
+ }), 'aggregate_only');
1843
+ _3.label = 25;
1844
+ case 25:
1845
+ _3.trys.push([25, 27, , 28]);
1846
+ guardStart = Date.now();
1847
+ return [4 /*yield*/, runCodexInWorkerThread(guardDirectivePrompt, runOptions, codexConfig, streamProgress)];
1848
+ case 26:
1849
+ guardDirectiveText = _3.sent();
1850
+ accumulateCodexUsage(guardDirectivePrompt, guardDirectiveText);
1851
+ timingBreakdown.forcedDirectiveMs += Date.now() - guardStart;
1852
+ guardDirective = extractAssistantMongoDirective(guardDirectiveText);
1853
+ if (guardDirective && guardDirective.type === 'aggregate') {
1854
+ directive = guardDirective;
1855
+ directiveSource = 'forced';
1856
+ lastDirective = guardDirective;
1857
+ datedDirectiveRetryUsed = true;
1858
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || '');
1859
+ recordStep('Directive resolved', {
1860
+ source: directiveSource,
1861
+ type: directive.type,
1862
+ collection: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.collection) || undefined,
1863
+ permissionView: normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.permissionView) || undefined,
1864
+ reportStyle: isAssistantDirectiveDated(guardDirective) ? 'dated' : 'aggregate_fallback',
1865
+ timeGrain: requestedTimeGrain || undefined
1866
+ });
1867
+ }
1868
+ return [3 /*break*/, 28];
1869
+ case 27:
1870
+ _f = _3.sent();
1871
+ return [3 /*break*/, 28];
1872
+ case 28:
1761
1873
  if (directive) {
1762
- requestedCollection = normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection);
1874
+ requestedCollection = normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection);
1763
1875
  collectionOverride = resolveCollectionOverrideWithContext({
1764
1876
  message: message,
1765
1877
  collectionRanking: collectionRanking,
1766
1878
  requestedCollection: requestedCollection,
1767
- permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || contextRoute,
1879
+ permissionView: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.permissionView) || contextRoute,
1768
1880
  collectionNames: collectionNames
1769
1881
  });
1770
1882
  if (collectionOverride) {
@@ -1776,11 +1888,12 @@ function executeAiAssistantCodexRun(payload, context) {
1776
1888
  });
1777
1889
  }
1778
1890
  }
1891
+ datedDirectiveResolved = directive ? isAssistantDirectiveDated(directive) : false;
1779
1892
  cleanedResponseText = (directive === null || directive === void 0 ? void 0 : directive.cleaned) || responseText;
1780
1893
  if (cleanedResponseText) {
1781
1894
  assistantContent = sanitizeAssistantResponse(cleanedResponseText);
1782
1895
  }
1783
- if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 32];
1896
+ if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 40];
1784
1897
  effectiveDirective = collectionOverride
1785
1898
  ? __assign(__assign({}, directive), { payload: __assign(__assign({}, (directive.payload || {})), { collection: collectionOverride.to }) }) : directive;
1786
1899
  toolRequest = buildAssistantToolRequest(effectiveDirective, input);
@@ -1790,21 +1903,21 @@ function executeAiAssistantCodexRun(payload, context) {
1790
1903
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
1791
1904
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
1792
1905
  });
1793
- _v.label = 21;
1794
- case 21:
1795
- _v.trys.push([21, 30, , 31]);
1906
+ _3.label = 29;
1907
+ case 29:
1908
+ _3.trys.push([29, 38, , 39]);
1796
1909
  toolStart = Date.now();
1797
- if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 23];
1910
+ if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 31];
1798
1911
  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;
1912
+ case 30:
1913
+ _g = _3.sent();
1914
+ return [3 /*break*/, 33];
1915
+ case 31: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
1916
+ case 32:
1917
+ _g = _3.sent();
1918
+ _3.label = 33;
1919
+ case 33:
1920
+ toolResponse = _g;
1808
1921
  timingBreakdown.toolMs = Date.now() - toolStart;
1809
1922
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
1810
1923
  ? toolResponse.debug
@@ -1819,43 +1932,43 @@ function executeAiAssistantCodexRun(payload, context) {
1819
1932
  progressTracker.push('Drafting response');
1820
1933
  recordStep('Drafting response');
1821
1934
  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]);
1935
+ _3.label = 34;
1936
+ case 34:
1937
+ _3.trys.push([34, 36, , 37]);
1825
1938
  followupStart = Date.now();
1826
1939
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
1827
- case 27:
1828
- followupText = _v.sent();
1940
+ case 35:
1941
+ followupText = _3.sent();
1829
1942
  accumulateCodexUsage(followupPrompt, followupText);
1830
1943
  timingBreakdown.followupMs = Date.now() - followupStart;
1831
1944
  assistantContent = sanitizeAssistantResponse(followupText);
1832
1945
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
1833
- return [3 /*break*/, 29];
1834
- case 28:
1835
- _f = _v.sent();
1946
+ return [3 /*break*/, 37];
1947
+ case 36:
1948
+ _h = _3.sent();
1836
1949
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
1837
- return [3 /*break*/, 29];
1838
- case 29: return [3 /*break*/, 31];
1839
- case 30:
1840
- error_2 = _v.sent();
1950
+ return [3 /*break*/, 37];
1951
+ case 37: return [3 /*break*/, 39];
1952
+ case 38:
1953
+ error_2 = _3.sent();
1841
1954
  assistantContent = buildAssistantToolErrorMessage(error_2);
1842
1955
  toolError = error_2;
1843
- return [3 /*break*/, 31];
1844
- case 31: return [3 /*break*/, 33];
1845
- case 32:
1956
+ return [3 /*break*/, 39];
1957
+ case 39: return [3 /*break*/, 41];
1958
+ case 40:
1846
1959
  progressTracker.push('Drafting response');
1847
1960
  recordStep('Drafting response');
1848
- _v.label = 33;
1849
- case 33: return [3 /*break*/, 36];
1850
- case 34:
1851
- error_3 = _v.sent();
1961
+ _3.label = 41;
1962
+ case 41: return [3 /*break*/, 44];
1963
+ case 42:
1964
+ error_3 = _3.sent();
1852
1965
  assistantContent = buildAssistantCodexErrorMessage(error_3);
1853
1966
  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:
1967
+ return [3 /*break*/, 44];
1968
+ case 43:
1856
1969
  progressTracker.stop();
1857
1970
  return [7 /*endfinally*/];
1858
- case 36:
1971
+ case 44:
1859
1972
  if (!assistantContent) {
1860
1973
  assistantContent = buildAssistantCodexErrorMessage(null);
1861
1974
  }
@@ -1891,6 +2004,10 @@ function executeAiAssistantCodexRun(payload, context) {
1891
2004
  requestTypeSource: requestClassification.source,
1892
2005
  plannerIntentType: requestClassification.plannerIntentType,
1893
2006
  dataQuestion: dataQuestion,
2007
+ reportStyleIntent: enforceDatedDirective ? 'dated' : null,
2008
+ requestedTimeGrain: requestedTimeGrain,
2009
+ datedDirectiveRetryUsed: datedDirectiveRetryUsed,
2010
+ datedDirectiveResolved: datedDirectiveResolved,
1894
2011
  directive: lastDirective,
1895
2012
  directiveSource: directiveSource,
1896
2013
  toolResult: toolResult,
@@ -1941,14 +2058,14 @@ function executeAiAssistantCodexRun(payload, context) {
1941
2058
  output_tokens: codexUsage.output_tokens,
1942
2059
  total_tokens: codexUsage.total_tokens
1943
2060
  } : null;
1944
- if (!finalUsage) return [3 /*break*/, 41];
2061
+ if (!finalUsage) return [3 /*break*/, 49];
1945
2062
  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]);
2063
+ case 45:
2064
+ usageClientId = _3.sent();
2065
+ if (!usageClientId) return [3 /*break*/, 49];
2066
+ _3.label = 46;
2067
+ case 46:
2068
+ _3.trys.push([46, 48, , 49]);
1952
2069
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
1953
2070
  id_client: usageClientId,
1954
2071
  model: finalUsage.model,
@@ -1959,16 +2076,16 @@ function executeAiAssistantCodexRun(payload, context) {
1959
2076
  id_request: requestId || undefined,
1960
2077
  id_conversation: conversation._id
1961
2078
  })];
1962
- case 39:
1963
- _v.sent();
1964
- return [3 /*break*/, 41];
1965
- case 40:
1966
- usageError_1 = _v.sent();
2079
+ case 47:
2080
+ _3.sent();
2081
+ return [3 /*break*/, 49];
2082
+ case 48:
2083
+ usageError_1 = _3.sent();
1967
2084
  console.error(new Date(), 'Failed to record codex usage', usageError_1);
1968
- return [3 /*break*/, 41];
1969
- case 41:
2085
+ return [3 /*break*/, 49];
2086
+ case 49:
1970
2087
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
1971
- if (!assistantMessageId) return [3 /*break*/, 43];
2088
+ if (!assistantMessageId) return [3 /*break*/, 51];
1972
2089
  setPayload = {
1973
2090
  content: assistantContent,
1974
2091
  metadata: finalMetadata,
@@ -1980,18 +2097,18 @@ function executeAiAssistantCodexRun(payload, context) {
1980
2097
  return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: assistantMessageId }, {
1981
2098
  $set: setPayload
1982
2099
  })];
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];
2100
+ case 50:
2101
+ _3.sent();
2102
+ _3.label = 51;
2103
+ case 51: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2104
+ case 52:
2105
+ _3.sent();
2106
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 54];
1990
2107
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
1991
- case 45:
1992
- _v.sent();
1993
- _v.label = 46;
1994
- case 46: return [2 /*return*/, finalAssistantDoc];
2108
+ case 53:
2109
+ _3.sent();
2110
+ _3.label = 54;
2111
+ case 54: return [2 /*return*/, finalAssistantDoc];
1995
2112
  }
1996
2113
  });
1997
2114
  }); });
@@ -2126,7 +2243,7 @@ function executeAiAssistantMongoRead(payload, context) {
2126
2243
  _q.label = 8;
2127
2244
  case 8:
2128
2245
  if (!!documents.length) return [3 /*break*/, 10];
2129
- expanded = expandQueryDateFallbacks(executedQuery);
2246
+ expanded = expandQueryDateFallbacks(executedQuery, schemaFields);
2130
2247
  if (!expanded) return [3 /*break*/, 10];
2131
2248
  fallbackMeta.dateFieldsExpanded = {
2132
2249
  fields: expanded.fields,
@@ -2669,7 +2786,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
2669
2786
  _q.label = 10;
2670
2787
  case 10:
2671
2788
  if (!!documents.length) return [3 /*break*/, 12];
2672
- expanded = expandAggregateDateMatchFallback(executedPipeline);
2789
+ expanded = expandAggregateDateMatchFallback(executedPipeline, schemaFields);
2673
2790
  if (!expanded) return [3 /*break*/, 12];
2674
2791
  fallbackMeta.dateFieldsExpanded = {
2675
2792
  fields: expanded.fields,
@@ -4129,6 +4246,18 @@ function buildAssistantDebugPayload(params) {
4129
4246
  if (params.dataQuestion) {
4130
4247
  notes.push('Detected a data request; tool call required.');
4131
4248
  }
4249
+ if (params.reportStyleIntent === 'dated') {
4250
+ notes.push("Report style intent: dated".concat(params.requestedTimeGrain ? " (".concat(params.requestedTimeGrain, ")") : '', "."));
4251
+ if (params.datedDirectiveRetryUsed) {
4252
+ notes.push('Retried directive generation to enforce dated report style.');
4253
+ }
4254
+ if (params.datedDirectiveResolved) {
4255
+ notes.push('Directive includes time-based aggregate grouping.');
4256
+ }
4257
+ else {
4258
+ notes.push('Directive did not include explicit time-based grouping.');
4259
+ }
4260
+ }
4132
4261
  if (params.directiveSource === 'forced') {
4133
4262
  notes.push('Assistant response omitted a REPORT_BUILDER_* directive; ran a directive-only pass.');
4134
4263
  }
@@ -4264,6 +4393,10 @@ function buildAssistantDebugPayload(params) {
4264
4393
  requestTypeSource: params.requestTypeSource,
4265
4394
  plannerIntentType: params.plannerIntentType || undefined,
4266
4395
  dataQuestion: params.dataQuestion,
4396
+ reportStyleIntent: params.reportStyleIntent || undefined,
4397
+ timeGrain: params.requestedTimeGrain || undefined,
4398
+ datedDirectiveRetryUsed: params.datedDirectiveRetryUsed === true ? true : undefined,
4399
+ datedDirectiveResolved: params.datedDirectiveResolved === true ? true : undefined,
4267
4400
  directiveSource: params.directiveSource
4268
4401
  },
4269
4402
  directive: directive ? {
@@ -5710,13 +5843,138 @@ function flattenForTable(doc, options) {
5710
5843
  });
5711
5844
  return result;
5712
5845
  }
5846
+ function normalizeAssistantComparableDateDisplayValue(value) {
5847
+ if (value === null || value === undefined) {
5848
+ return '';
5849
+ }
5850
+ if (value instanceof Date) {
5851
+ return Number.isNaN(value.getTime()) ? '' : value.toISOString();
5852
+ }
5853
+ if (typeof value === 'number' && Number.isFinite(value)) {
5854
+ var epochMs = value >= 1e11 ? value : value >= 1e9 ? value * 1000 : null;
5855
+ if (epochMs !== null) {
5856
+ var parsed_1 = new Date(epochMs);
5857
+ if (!Number.isNaN(parsed_1.getTime())) {
5858
+ return parsed_1.toISOString();
5859
+ }
5860
+ }
5861
+ return String(value);
5862
+ }
5863
+ var text = String(value).trim();
5864
+ if (!text) {
5865
+ return '';
5866
+ }
5867
+ var parsed = Date.parse(text);
5868
+ if (!Number.isNaN(parsed)) {
5869
+ return new Date(parsed).toISOString();
5870
+ }
5871
+ return text.toLowerCase();
5872
+ }
5873
+ function shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField) {
5874
+ var preferredNonEmpty = 0;
5875
+ var candidateNonEmpty = 0;
5876
+ var overlap = 0;
5877
+ var equalOverlap = 0;
5878
+ rows.forEach(function (row) {
5879
+ var preferredValue = row === null || row === void 0 ? void 0 : row[preferredField];
5880
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
5881
+ var preferredHasValue = !isEmptyDisplayValue(preferredValue);
5882
+ var candidateHasValue = !isEmptyDisplayValue(candidateValue);
5883
+ if (preferredHasValue) {
5884
+ preferredNonEmpty += 1;
5885
+ }
5886
+ if (candidateHasValue) {
5887
+ candidateNonEmpty += 1;
5888
+ }
5889
+ if (preferredHasValue && candidateHasValue) {
5890
+ overlap += 1;
5891
+ if (normalizeAssistantComparableDateDisplayValue(preferredValue)
5892
+ === normalizeAssistantComparableDateDisplayValue(candidateValue)) {
5893
+ equalOverlap += 1;
5894
+ }
5895
+ }
5896
+ });
5897
+ if (!candidateNonEmpty) {
5898
+ return false;
5899
+ }
5900
+ if (!preferredNonEmpty) {
5901
+ return true;
5902
+ }
5903
+ if (!overlap) {
5904
+ return false;
5905
+ }
5906
+ return (equalOverlap / overlap) >= 0.8;
5907
+ }
5908
+ function coalesceAssistantDisplayDuplicateFields(rowsRaw) {
5909
+ if (!Array.isArray(rowsRaw) || !rowsRaw.length) {
5910
+ return Array.isArray(rowsRaw) ? rowsRaw : [];
5911
+ }
5912
+ var rows = rowsRaw.map(function (row) { return (__assign({}, (row || {}))); });
5913
+ var collectKeys = function () {
5914
+ var keySet = new Set();
5915
+ rows.forEach(function (row) {
5916
+ Object.keys(row || {}).forEach(function (key) {
5917
+ if (key) {
5918
+ keySet.add(key);
5919
+ }
5920
+ });
5921
+ });
5922
+ return keySet;
5923
+ };
5924
+ var keys = collectKeys();
5925
+ Array.from(keys).forEach(function (key) {
5926
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
5927
+ if (!leaf || !/_string$/i.test(leaf)) {
5928
+ return;
5929
+ }
5930
+ var baseLeaf = leaf.replace(/_string$/i, '');
5931
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
5932
+ if (!keys.has(basePath)) {
5933
+ return;
5934
+ }
5935
+ rows.forEach(function (row) {
5936
+ var stringValue = row === null || row === void 0 ? void 0 : row[key];
5937
+ if (!isEmptyDisplayValue(stringValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[basePath])) {
5938
+ row[basePath] = stringValue;
5939
+ }
5940
+ delete row[key];
5941
+ });
5942
+ });
5943
+ keys = collectKeys();
5944
+ var mergeDateGroup = function (preferredOrder) {
5945
+ var preferredField = preferredOrder.find(function (field) { return keys.has(field); });
5946
+ if (!preferredField) {
5947
+ return;
5948
+ }
5949
+ preferredOrder.forEach(function (candidateField) {
5950
+ if (candidateField === preferredField || !keys.has(candidateField)) {
5951
+ return;
5952
+ }
5953
+ if (!shouldMergeAssistantDisplayDateField(rows, preferredField, candidateField)) {
5954
+ return;
5955
+ }
5956
+ rows.forEach(function (row) {
5957
+ var candidateValue = row === null || row === void 0 ? void 0 : row[candidateField];
5958
+ if (!isEmptyDisplayValue(candidateValue) && isEmptyDisplayValue(row === null || row === void 0 ? void 0 : row[preferredField])) {
5959
+ row[preferredField] = candidateValue;
5960
+ }
5961
+ delete row[candidateField];
5962
+ });
5963
+ keys.delete(candidateField);
5964
+ });
5965
+ };
5966
+ mergeDateGroup(['createdAt', 'created_at', 'date_created', 'created_date', 'date']);
5967
+ mergeDateGroup(['updatedAt', 'updated_at', 'date_updated', 'updated_date']);
5968
+ return rows;
5969
+ }
5713
5970
  function buildDisplayTable(docs, options) {
5714
- var rowsRaw = Array.isArray(docs)
5971
+ var rowsRawInitial = Array.isArray(docs)
5715
5972
  ? docs.map(function (doc) { return flattenForTable(doc, {
5716
5973
  includeIds: (options === null || options === void 0 ? void 0 : options.includeIds) === true,
5717
5974
  includeGroupFromId: (options === null || options === void 0 ? void 0 : options.includeGroupFromId) === true
5718
5975
  }); })
5719
5976
  : [];
5977
+ var rowsRaw = coalesceAssistantDisplayDuplicateFields(rowsRawInitial);
5720
5978
  var stats = new Map();
5721
5979
  rowsRaw.forEach(function (row) {
5722
5980
  Object.keys(row).forEach(function (key) {
@@ -6173,7 +6431,7 @@ function normalizeAssistantFindOptions(options) {
6173
6431
  var maxLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_MAX_LIMIT;
6174
6432
  var defaultLimit = exportMode ? AI_ASSISTANT_MONGO_EXPORT_MAX_LIMIT : AI_ASSISTANT_MONGO_DEFAULT_LIMIT;
6175
6433
  var projection = sanitizeAssistantProjection(normalized.projection);
6176
- var sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
6434
+ var sort = sanitizeAssistantSort(normalized.sort);
6177
6435
  var limit = typeof normalized.limit === 'number'
6178
6436
  ? Math.min(Math.max(normalized.limit, 0), maxLimit)
6179
6437
  : defaultLimit;
@@ -6192,28 +6450,194 @@ function sanitizeAssistantProjection(projection) {
6192
6450
  if (!projection || typeof projection !== 'object') {
6193
6451
  return undefined;
6194
6452
  }
6195
- var keys = Object.keys(projection);
6453
+ var sanitized = __assign({}, projection);
6454
+ var keys = Object.keys(sanitized);
6196
6455
  if (!keys.length) {
6197
6456
  return undefined;
6198
6457
  }
6199
6458
  var hasInclude = false;
6200
- var hasExclude = false;
6459
+ var hasNonIdExclude = false;
6201
6460
  keys.forEach(function (key) {
6202
- var value = projection[key];
6461
+ var value = sanitized[key];
6203
6462
  if (value === 0 || value === false) {
6204
- hasExclude = true;
6463
+ if (key !== '_id') {
6464
+ hasNonIdExclude = true;
6465
+ }
6205
6466
  }
6206
6467
  else if (value === 1 || value === true) {
6207
6468
  hasInclude = true;
6208
6469
  }
6209
6470
  });
6210
- if (hasInclude && !hasExclude) {
6211
- var onlyIds = keys.every(function (key) { return isAssistantIdField(key); });
6471
+ if (hasInclude && !hasNonIdExclude) {
6472
+ var includeKeys = keys.filter(function (key) {
6473
+ var value = sanitized[key];
6474
+ return value === 1 || value === true;
6475
+ });
6476
+ var dedupedIncludeKeys = dedupeAssistantFieldKeys(includeKeys);
6477
+ if (dedupedIncludeKeys.length !== includeKeys.length) {
6478
+ var includeSet_1 = new Set(dedupedIncludeKeys);
6479
+ var next_2 = {};
6480
+ keys.forEach(function (key) {
6481
+ var value = sanitized[key];
6482
+ if (value === 1 || value === true) {
6483
+ if (includeSet_1.has(key)) {
6484
+ next_2[key] = value;
6485
+ }
6486
+ return;
6487
+ }
6488
+ if (key === '_id' && (value === 0 || value === false)) {
6489
+ next_2[key] = value;
6490
+ }
6491
+ });
6492
+ sanitized = next_2;
6493
+ keys = Object.keys(sanitized);
6494
+ }
6495
+ var includeAfterDedupe = keys.filter(function (key) {
6496
+ var value = sanitized[key];
6497
+ return value === 1 || value === true;
6498
+ });
6499
+ var onlyIds = includeAfterDedupe.length > 0
6500
+ && includeAfterDedupe.every(function (key) { return isAssistantIdField(key); });
6212
6501
  if (onlyIds) {
6213
6502
  return undefined;
6214
6503
  }
6215
6504
  }
6216
- return projection;
6505
+ return sanitized;
6506
+ }
6507
+ function sanitizeAssistantSort(sort) {
6508
+ if (!sort || typeof sort !== 'object') {
6509
+ return undefined;
6510
+ }
6511
+ var keys = Object.keys(sort);
6512
+ if (!keys.length) {
6513
+ return undefined;
6514
+ }
6515
+ var dedupedKeys = dedupeAssistantFieldKeys(keys);
6516
+ if (dedupedKeys.length === keys.length) {
6517
+ return sort;
6518
+ }
6519
+ var keepSet = new Set(dedupedKeys);
6520
+ var next = {};
6521
+ keys.forEach(function (key) {
6522
+ if (keepSet.has(key)) {
6523
+ next[key] = sort[key];
6524
+ }
6525
+ });
6526
+ return Object.keys(next).length ? next : undefined;
6527
+ }
6528
+ function splitAssistantFieldPath(fieldPath) {
6529
+ var normalized = normalizeOptionalString(fieldPath);
6530
+ if (!normalized) {
6531
+ return { parent: '', leaf: '' };
6532
+ }
6533
+ var segments = normalized.split('.');
6534
+ var leaf = segments.pop() || '';
6535
+ var parent = segments.join('.');
6536
+ return { parent: parent, leaf: leaf };
6537
+ }
6538
+ function getAssistantCreatedFieldRank(leaf) {
6539
+ var normalized = normalizeFieldMatchKey(leaf);
6540
+ if (normalized === 'createdat') {
6541
+ return 1;
6542
+ }
6543
+ if (normalized === 'createddate') {
6544
+ return 2;
6545
+ }
6546
+ if (normalized === 'datecreated') {
6547
+ return 3;
6548
+ }
6549
+ if (normalized === 'created') {
6550
+ return 4;
6551
+ }
6552
+ return 0;
6553
+ }
6554
+ function getAssistantUpdatedFieldRank(leaf) {
6555
+ var normalized = normalizeFieldMatchKey(leaf);
6556
+ if (normalized === 'updatedat') {
6557
+ return 1;
6558
+ }
6559
+ if (normalized === 'updateddate') {
6560
+ return 2;
6561
+ }
6562
+ if (normalized === 'dateupdated') {
6563
+ return 3;
6564
+ }
6565
+ if (normalized === 'updated') {
6566
+ return 4;
6567
+ }
6568
+ return 0;
6569
+ }
6570
+ function dedupeAssistantFieldKeys(fieldKeys) {
6571
+ if (!Array.isArray(fieldKeys) || !fieldKeys.length) {
6572
+ return [];
6573
+ }
6574
+ var keys = fieldKeys.filter(Boolean);
6575
+ if (!keys.length) {
6576
+ return [];
6577
+ }
6578
+ var keySet = new Set(keys);
6579
+ var dropSet = new Set();
6580
+ var preferByParent = function (entries, parent, key, rank) {
6581
+ var current = entries.get(parent);
6582
+ if (!current || rank < current.rank) {
6583
+ if (current) {
6584
+ dropSet.add(current.key);
6585
+ }
6586
+ entries.set(parent, { key: key, rank: rank });
6587
+ return;
6588
+ }
6589
+ dropSet.add(key);
6590
+ };
6591
+ keys.forEach(function (key) {
6592
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6593
+ if (!leaf) {
6594
+ return;
6595
+ }
6596
+ if (/_string$/i.test(leaf)) {
6597
+ var baseLeaf = leaf.replace(/_string$/i, '');
6598
+ var basePath = parent ? "".concat(parent, ".").concat(baseLeaf) : baseLeaf;
6599
+ if (keySet.has(basePath)) {
6600
+ dropSet.add(key);
6601
+ }
6602
+ }
6603
+ });
6604
+ var createdByParent = new Map();
6605
+ var updatedByParent = new Map();
6606
+ var dateByParent = new Map();
6607
+ keys.forEach(function (key) {
6608
+ if (dropSet.has(key)) {
6609
+ return;
6610
+ }
6611
+ var _a = splitAssistantFieldPath(key), parent = _a.parent, leaf = _a.leaf;
6612
+ if (!leaf) {
6613
+ return;
6614
+ }
6615
+ var normalizedLeaf = normalizeFieldMatchKey(leaf);
6616
+ if (normalizedLeaf === 'date') {
6617
+ if (dateByParent.has(parent)) {
6618
+ dropSet.add(key);
6619
+ }
6620
+ else {
6621
+ dateByParent.set(parent, key);
6622
+ }
6623
+ return;
6624
+ }
6625
+ var createdRank = getAssistantCreatedFieldRank(leaf);
6626
+ if (createdRank > 0) {
6627
+ preferByParent(createdByParent, parent, key, createdRank);
6628
+ return;
6629
+ }
6630
+ var updatedRank = getAssistantUpdatedFieldRank(leaf);
6631
+ if (updatedRank > 0) {
6632
+ preferByParent(updatedByParent, parent, key, updatedRank);
6633
+ }
6634
+ });
6635
+ dateByParent.forEach(function (dateKey, parent) {
6636
+ if (createdByParent.has(parent)) {
6637
+ dropSet.add(dateKey);
6638
+ }
6639
+ });
6640
+ return keys.filter(function (key) { return !dropSet.has(key); });
6217
6641
  }
6218
6642
  var AGG_MATCH_EXPR_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte']);
6219
6643
  var ASSISTANT_NOW_RELATIVE_PATTERN = /^\$\$NOW_(MINUS|PLUS)_([0-9]+)_(MINUTES?|HOURS?|DAYS?|WEEKS?|MONTHS?|YEARS?)$/i;
@@ -7372,6 +7796,126 @@ function extractExpressionFieldPaths(value) {
7372
7796
  visit(value);
7373
7797
  return results.filter(Boolean);
7374
7798
  }
7799
+ function hasAssistantDateGroupingOperator(value) {
7800
+ if (Array.isArray(value)) {
7801
+ return value.some(function (entry) { return hasAssistantDateGroupingOperator(entry); });
7802
+ }
7803
+ if (!value || typeof value !== 'object') {
7804
+ return false;
7805
+ }
7806
+ var dateTrunc = value.$dateTrunc;
7807
+ if (dateTrunc && typeof dateTrunc === 'object' && !Array.isArray(dateTrunc)) {
7808
+ var unit = normalizeOptionalString(dateTrunc.unit).toLowerCase();
7809
+ if (unit === 'day' || unit === 'week' || unit === 'month' || unit === 'quarter' || unit === 'year') {
7810
+ return true;
7811
+ }
7812
+ }
7813
+ var dateToString = value.$dateToString;
7814
+ if (dateToString && typeof dateToString === 'object' && !Array.isArray(dateToString)) {
7815
+ var format = normalizeOptionalString(dateToString.format);
7816
+ if (/%[djmUVWYGy]/i.test(format)) {
7817
+ return true;
7818
+ }
7819
+ }
7820
+ var directDateOps = ['$year', '$month', '$week', '$isoWeek', '$isoWeekYear', '$dayOfMonth', '$dayOfYear', '$dateToParts'];
7821
+ if (directDateOps.some(function (op) { return Object.prototype.hasOwnProperty.call(value, op); })) {
7822
+ return true;
7823
+ }
7824
+ return Object.keys(value).some(function (key) { return hasAssistantDateGroupingOperator(value[key]); });
7825
+ }
7826
+ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths) {
7827
+ var e_16, _a, e_17, _b;
7828
+ if (!Array.isArray(pipeline) || groupIndex <= 0 || !groupPaths.length) {
7829
+ return false;
7830
+ }
7831
+ var groupFields = new Set();
7832
+ groupPaths.forEach(function (pathValue) {
7833
+ var normalizedPath = normalizeOptionalString(pathValue);
7834
+ if (!normalizedPath) {
7835
+ return;
7836
+ }
7837
+ groupFields.add(normalizedPath);
7838
+ var rootSegment = normalizedPath.split('.')[0];
7839
+ if (rootSegment) {
7840
+ groupFields.add(rootSegment);
7841
+ }
7842
+ });
7843
+ if (!groupFields.size) {
7844
+ return false;
7845
+ }
7846
+ var stageKeys = ['$addFields', '$set', '$project'];
7847
+ for (var i = groupIndex - 1; i >= 0; i -= 1) {
7848
+ var stage = pipeline[i];
7849
+ if (!stage || typeof stage !== 'object') {
7850
+ continue;
7851
+ }
7852
+ try {
7853
+ for (var stageKeys_1 = (e_16 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
7854
+ var stageKey = stageKeys_1_1.value;
7855
+ var payload = stage[stageKey];
7856
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
7857
+ continue;
7858
+ }
7859
+ try {
7860
+ for (var groupFields_1 = (e_17 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
7861
+ var groupField = groupFields_1_1.value;
7862
+ if (!Object.prototype.hasOwnProperty.call(payload, groupField)) {
7863
+ continue;
7864
+ }
7865
+ if (hasAssistantDateGroupingOperator(payload[groupField])) {
7866
+ return true;
7867
+ }
7868
+ }
7869
+ }
7870
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
7871
+ finally {
7872
+ try {
7873
+ if (groupFields_1_1 && !groupFields_1_1.done && (_b = groupFields_1.return)) _b.call(groupFields_1);
7874
+ }
7875
+ finally { if (e_17) throw e_17.error; }
7876
+ }
7877
+ }
7878
+ }
7879
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
7880
+ finally {
7881
+ try {
7882
+ if (stageKeys_1_1 && !stageKeys_1_1.done && (_a = stageKeys_1.return)) _a.call(stageKeys_1);
7883
+ }
7884
+ finally { if (e_16) throw e_16.error; }
7885
+ }
7886
+ }
7887
+ return false;
7888
+ }
7889
+ function isAssistantTimeGroupedAggregatePipeline(pipeline) {
7890
+ if (!Array.isArray(pipeline) || !pipeline.length) {
7891
+ return false;
7892
+ }
7893
+ var groupIndex = findAggregateGroupIndex(pipeline);
7894
+ if (groupIndex === -1) {
7895
+ return false;
7896
+ }
7897
+ var groupStage = pipeline[groupIndex];
7898
+ var groupPayload = groupStage === null || groupStage === void 0 ? void 0 : groupStage.$group;
7899
+ if (!groupPayload || typeof groupPayload !== 'object') {
7900
+ return false;
7901
+ }
7902
+ var groupPaths = extractGroupFieldPaths(groupPayload);
7903
+ if (groupPaths.some(function (field) { return /(date|time|created|updated|paid|invoice|timestamp|_at|month|quarter|week|year|day)/i.test(field); })) {
7904
+ return true;
7905
+ }
7906
+ if (hasAssistantDateGroupingOperator(groupPayload === null || groupPayload === void 0 ? void 0 : groupPayload._id)) {
7907
+ return true;
7908
+ }
7909
+ return isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths);
7910
+ }
7911
+ function isAssistantDirectiveDated(directive) {
7912
+ var _a;
7913
+ if (!directive || directive.type !== 'aggregate') {
7914
+ return false;
7915
+ }
7916
+ var pipeline = Array.isArray((_a = directive.payload) === null || _a === void 0 ? void 0 : _a.pipeline) ? directive.payload.pipeline : [];
7917
+ return isAssistantTimeGroupedAggregatePipeline(pipeline);
7918
+ }
7375
7919
  function findCommonPathPrefix(paths) {
7376
7920
  var _a;
7377
7921
  if (!paths.length) {
@@ -7430,7 +7974,7 @@ function isRegexMatchCondition(value) {
7430
7974
  return false;
7431
7975
  }
7432
7976
  function findRegexMatchInMatchObject(match, prefix) {
7433
- var e_16, _a, e_17, _b;
7977
+ var e_18, _a, e_19, _b;
7434
7978
  if (prefix === void 0) { prefix = ''; }
7435
7979
  if (Array.isArray(match)) {
7436
7980
  try {
@@ -7442,12 +7986,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7442
7986
  }
7443
7987
  }
7444
7988
  }
7445
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
7989
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
7446
7990
  finally {
7447
7991
  try {
7448
7992
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
7449
7993
  }
7450
- finally { if (e_16) throw e_16.error; }
7994
+ finally { if (e_18) throw e_18.error; }
7451
7995
  }
7452
7996
  return null;
7453
7997
  }
@@ -7478,12 +8022,12 @@ function findRegexMatchInMatchObject(match, prefix) {
7478
8022
  }
7479
8023
  }
7480
8024
  }
7481
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
8025
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
7482
8026
  finally {
7483
8027
  try {
7484
8028
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
7485
8029
  }
7486
- finally { if (e_17) throw e_17.error; }
8030
+ finally { if (e_19) throw e_19.error; }
7487
8031
  }
7488
8032
  return null;
7489
8033
  }
@@ -7707,7 +8251,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
7707
8251
  return results;
7708
8252
  }
7709
8253
  function findMatchConditionForField(match, targetField, prefix) {
7710
- var e_18, _a, e_19, _b;
8254
+ var e_20, _a, e_21, _b;
7711
8255
  if (prefix === void 0) { prefix = ''; }
7712
8256
  if (!match || typeof match !== 'object') {
7713
8257
  return undefined;
@@ -7722,12 +8266,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7722
8266
  }
7723
8267
  }
7724
8268
  }
7725
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
8269
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
7726
8270
  finally {
7727
8271
  try {
7728
8272
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
7729
8273
  }
7730
- finally { if (e_18) throw e_18.error; }
8274
+ finally { if (e_20) throw e_20.error; }
7731
8275
  }
7732
8276
  return undefined;
7733
8277
  }
@@ -7754,12 +8298,12 @@ function findMatchConditionForField(match, targetField, prefix) {
7754
8298
  }
7755
8299
  }
7756
8300
  }
7757
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
8301
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
7758
8302
  finally {
7759
8303
  try {
7760
8304
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
7761
8305
  }
7762
- finally { if (e_19) throw e_19.error; }
8306
+ finally { if (e_21) throw e_21.error; }
7763
8307
  }
7764
8308
  return undefined;
7765
8309
  }
@@ -7802,7 +8346,7 @@ function detectIdLikeValue(value) {
7802
8346
  return false;
7803
8347
  }
7804
8348
  function detectChemicalIdFromProbe(probeDocs, fields) {
7805
- var e_20, _a, e_21, _b;
8349
+ var e_22, _a, e_23, _b;
7806
8350
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
7807
8351
  return false;
7808
8352
  }
@@ -7814,7 +8358,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7814
8358
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
7815
8359
  var doc = probeDocs_1_1.value;
7816
8360
  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()) {
8361
+ for (var targets_1 = (e_23 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
7818
8362
  var field = targets_1_1.value;
7819
8363
  var value = getValueAtPath(doc, field);
7820
8364
  if (Array.isArray(value)) {
@@ -7827,21 +8371,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
7827
8371
  }
7828
8372
  }
7829
8373
  }
7830
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
8374
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
7831
8375
  finally {
7832
8376
  try {
7833
8377
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
7834
8378
  }
7835
- finally { if (e_21) throw e_21.error; }
8379
+ finally { if (e_23) throw e_23.error; }
7836
8380
  }
7837
8381
  }
7838
8382
  }
7839
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
8383
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
7840
8384
  finally {
7841
8385
  try {
7842
8386
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
7843
8387
  }
7844
- finally { if (e_20) throw e_20.error; }
8388
+ finally { if (e_22) throw e_22.error; }
7845
8389
  }
7846
8390
  return false;
7847
8391
  }
@@ -8062,8 +8606,8 @@ function buildChemicalIdFieldCandidates(field) {
8062
8606
  }
8063
8607
  function applyChemicalNameLookupFallbackToQuery(params) {
8064
8608
  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;
8609
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, chemicalFields, targetField, condition, regex, sampleDocs, collectionNames, candidates, _loop_7, candidates_2, candidates_2_1, candidate, state_5, e_24_1;
8610
+ var e_24, _a;
8067
8611
  var _b;
8068
8612
  return __generator(this, function (_c) {
8069
8613
  switch (_c.label) {
@@ -8176,14 +8720,14 @@ function applyChemicalNameLookupFallbackToQuery(params) {
8176
8720
  return [3 /*break*/, 3];
8177
8721
  case 6: return [3 /*break*/, 9];
8178
8722
  case 7:
8179
- e_22_1 = _c.sent();
8180
- e_22 = { error: e_22_1 };
8723
+ e_24_1 = _c.sent();
8724
+ e_24 = { error: e_24_1 };
8181
8725
  return [3 /*break*/, 9];
8182
8726
  case 8:
8183
8727
  try {
8184
8728
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
8185
8729
  }
8186
- finally { if (e_22) throw e_22.error; }
8730
+ finally { if (e_24) throw e_24.error; }
8187
8731
  return [7 /*endfinally*/];
8188
8732
  case 9: return [2 /*return*/, null];
8189
8733
  }
@@ -8277,8 +8821,8 @@ function lookupIdsForNameMatch(params) {
8277
8821
  }
8278
8822
  function applyIdLookupFallbackToQuery(params) {
8279
8823
  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;
8824
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, conditions, collectionNames, _a, conditions_1, conditions_1_1, condition, regex, baseToken, targetFieldType, nextValue, localNameField, candidates, candidates_3, candidates_3_1, candidate, candidateHasClientScope, _b, candidateProbe, lookup, targetFieldType, normalizedIds, idsForQuery, e_25_1, e_26_1;
8825
+ var e_26, _c, e_25, _d;
8282
8826
  var _e;
8283
8827
  return __generator(this, function (_f) {
8284
8828
  switch (_f.label) {
@@ -8348,7 +8892,7 @@ function applyIdLookupFallbackToQuery(params) {
8348
8892
  _f.label = 5;
8349
8893
  case 5:
8350
8894
  _f.trys.push([5, 14, 15, 16]);
8351
- candidates_3 = (e_23 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8895
+ candidates_3 = (e_25 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
8352
8896
  _f.label = 6;
8353
8897
  case 6:
8354
8898
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -8415,28 +8959,28 @@ function applyIdLookupFallbackToQuery(params) {
8415
8959
  return [3 /*break*/, 6];
8416
8960
  case 13: return [3 /*break*/, 16];
8417
8961
  case 14:
8418
- e_23_1 = _f.sent();
8419
- e_23 = { error: e_23_1 };
8962
+ e_25_1 = _f.sent();
8963
+ e_25 = { error: e_25_1 };
8420
8964
  return [3 /*break*/, 16];
8421
8965
  case 15:
8422
8966
  try {
8423
8967
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
8424
8968
  }
8425
- finally { if (e_23) throw e_23.error; }
8969
+ finally { if (e_25) throw e_25.error; }
8426
8970
  return [7 /*endfinally*/];
8427
8971
  case 16:
8428
8972
  conditions_1_1 = conditions_1.next();
8429
8973
  return [3 /*break*/, 4];
8430
8974
  case 17: return [3 /*break*/, 20];
8431
8975
  case 18:
8432
- e_24_1 = _f.sent();
8433
- e_24 = { error: e_24_1 };
8976
+ e_26_1 = _f.sent();
8977
+ e_26 = { error: e_26_1 };
8434
8978
  return [3 /*break*/, 20];
8435
8979
  case 19:
8436
8980
  try {
8437
8981
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
8438
8982
  }
8439
- finally { if (e_24) throw e_24.error; }
8983
+ finally { if (e_26) throw e_26.error; }
8440
8984
  return [7 /*endfinally*/];
8441
8985
  case 20: return [2 /*return*/, null];
8442
8986
  }
@@ -8522,12 +9066,12 @@ function replaceAggregateDateField(pipeline, fromField, toField) {
8522
9066
  return value;
8523
9067
  }
8524
9068
  if (value && typeof value === 'object') {
8525
- var next_2 = {};
9069
+ var next_3 = {};
8526
9070
  Object.keys(value).forEach(function (key) {
8527
9071
  var nextKey = key === fromField ? toField : key;
8528
- next_2[nextKey] = replacer(value[key]);
9072
+ next_3[nextKey] = replacer(value[key]);
8529
9073
  });
8530
- return next_2;
9074
+ return next_3;
8531
9075
  }
8532
9076
  if (typeof value === 'string') {
8533
9077
  var fromRef = "$".concat(fromField);
@@ -9288,7 +9832,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection) {
9288
9832
  throw new Error('AI assistant report builder bridge: Collection is not configured for report builder.');
9289
9833
  }
9290
9834
  function findQueryDateField(query) {
9291
- var e_25, _a, e_26, _b;
9835
+ var e_27, _a, e_28, _b;
9292
9836
  if (!query || typeof query !== 'object') {
9293
9837
  return null;
9294
9838
  }
@@ -9302,12 +9846,12 @@ function findQueryDateField(query) {
9302
9846
  }
9303
9847
  }
9304
9848
  }
9305
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
9849
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
9306
9850
  finally {
9307
9851
  try {
9308
9852
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
9309
9853
  }
9310
- finally { if (e_25) throw e_25.error; }
9854
+ finally { if (e_27) throw e_27.error; }
9311
9855
  }
9312
9856
  return null;
9313
9857
  }
@@ -9326,12 +9870,12 @@ function findQueryDateField(query) {
9326
9870
  }
9327
9871
  }
9328
9872
  }
9329
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
9873
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
9330
9874
  finally {
9331
9875
  try {
9332
9876
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
9333
9877
  }
9334
- finally { if (e_26) throw e_26.error; }
9878
+ finally { if (e_28) throw e_28.error; }
9335
9879
  }
9336
9880
  return null;
9337
9881
  }
@@ -9369,7 +9913,7 @@ function extractDateRangeConditions(query) {
9369
9913
  });
9370
9914
  return results;
9371
9915
  }
9372
- function expandQueryDateFallbacks(query) {
9916
+ function expandQueryDateFallbacks(query, schemaFields) {
9373
9917
  if (!query || typeof query !== 'object') {
9374
9918
  return null;
9375
9919
  }
@@ -9402,21 +9946,16 @@ function expandQueryDateFallbacks(query) {
9402
9946
  }
9403
9947
  var dateConditions = extractDateRangeConditions(entry);
9404
9948
  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
- }
9949
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
9950
+ expansions.forEach(function (field) {
9951
+ if (existingFields.has(field)) {
9952
+ return;
9953
+ }
9954
+ extended = __spreadArray(__spreadArray([], __read(extended), false), [replaceQueryField(entry, condition.field, field)], false);
9955
+ existingFields.add(field);
9956
+ pushField(field);
9957
+ });
9411
9958
  });
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
9959
  });
9421
9960
  return extended;
9422
9961
  };
@@ -9460,11 +9999,12 @@ function expandQueryDateFallbacks(query) {
9460
9999
  }
9461
10000
  return { query: result.value, fields: addedFields };
9462
10001
  }
9463
- function buildDateFieldExpansionList(field) {
10002
+ function buildDateFieldExpansionList(field, schemaFields) {
9464
10003
  var normalized = normalizeOptionalString(field);
9465
10004
  if (!normalized) {
9466
10005
  return [];
9467
10006
  }
10007
+ var normalizedLower = normalized.toLowerCase();
9468
10008
  var expansions = new Set();
9469
10009
  var add = function (value) {
9470
10010
  if (value && value !== normalized) {
@@ -9475,15 +10015,46 @@ function buildDateFieldExpansionList(field) {
9475
10015
  if (fallback) {
9476
10016
  add(fallback);
9477
10017
  }
9478
- if (normalized.startsWith('date_') || normalized === 'date' || normalized.endsWith('_date')) {
10018
+ if (normalizedLower.startsWith('date_')
10019
+ || normalizedLower === 'date'
10020
+ || normalizedLower.endsWith('_date')
10021
+ || normalizedLower.includes('_date_')) {
9479
10022
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9480
10023
  }
9481
- if (normalized === 'createdAt' || normalized === 'updatedAt') {
10024
+ if (normalizedLower === 'createdat' || normalizedLower === 'updatedat') {
9482
10025
  AI_ASSISTANT_DATE_EXPANSION_FIELDS.forEach(add);
9483
10026
  }
10027
+ var normalizedSchemaFields = Array.isArray(schemaFields)
10028
+ ? schemaFields
10029
+ .map(function (value) { return normalizeOptionalString(value); })
10030
+ .filter(Boolean)
10031
+ : [];
10032
+ if (normalizedSchemaFields.length) {
10033
+ var dateFieldPattern_1 = /(^|\.)(date($|_)|createdat$|updatedat$|[a-z0-9_]+_at$|[a-z0-9_]+_date$|[a-z0-9_]+_date_[a-z0-9_]*$)/i;
10034
+ var addedFromSchema_1 = 0;
10035
+ normalizedSchemaFields.forEach(function (schemaField) {
10036
+ if (addedFromSchema_1 >= AI_ASSISTANT_DATE_EXPANSION_SCHEMA_MAX_FIELDS) {
10037
+ return;
10038
+ }
10039
+ if (schemaField.includes('$')) {
10040
+ return;
10041
+ }
10042
+ if (!dateFieldPattern_1.test(schemaField)) {
10043
+ return;
10044
+ }
10045
+ if (schemaField === normalized) {
10046
+ return;
10047
+ }
10048
+ var beforeSize = expansions.size;
10049
+ add(schemaField);
10050
+ if (expansions.size > beforeSize) {
10051
+ addedFromSchema_1 += 1;
10052
+ }
10053
+ });
10054
+ }
9484
10055
  return Array.from(expansions);
9485
10056
  }
9486
- function expandAggregateDateMatchFallback(pipeline) {
10057
+ function expandAggregateDateMatchFallback(pipeline, schemaFields) {
9487
10058
  if (!Array.isArray(pipeline)) {
9488
10059
  return null;
9489
10060
  }
@@ -9516,7 +10087,7 @@ function expandAggregateDateMatchFallback(pipeline) {
9516
10087
  }
9517
10088
  var conditions = extractDateRangeConditions(entry);
9518
10089
  conditions.forEach(function (condition) {
9519
- var expansions = buildDateFieldExpansionList(condition.field);
10090
+ var expansions = buildDateFieldExpansionList(condition.field, schemaFields);
9520
10091
  expansions.forEach(function (field) {
9521
10092
  if (existingFields.has(field)) {
9522
10093
  return;
@@ -9553,7 +10124,7 @@ function resolveQueryDateFieldFallback(query) {
9553
10124
  return { from: dateField, to: fallback };
9554
10125
  }
9555
10126
  function containsForbiddenMongoOperators(value) {
9556
- var e_27, _a;
10127
+ var e_29, _a;
9557
10128
  if (!value || typeof value !== 'object') {
9558
10129
  return false;
9559
10130
  }
@@ -9572,12 +10143,12 @@ function containsForbiddenMongoOperators(value) {
9572
10143
  }
9573
10144
  }
9574
10145
  }
9575
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
10146
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
9576
10147
  finally {
9577
10148
  try {
9578
10149
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9579
10150
  }
9580
- finally { if (e_27) throw e_27.error; }
10151
+ finally { if (e_29) throw e_29.error; }
9581
10152
  }
9582
10153
  return false;
9583
10154
  }
@@ -10012,8 +10583,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
10012
10583
  }
10013
10584
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10014
10585
  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;
10586
+ var _a, _b, _c, _d, message, payload, status_1, e_30_1;
10587
+ var _e, e_30, _f, _g;
10017
10588
  return __generator(this, function (_h) {
10018
10589
  switch (_h.label) {
10019
10590
  case 0:
@@ -10040,8 +10611,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10040
10611
  return [3 /*break*/, 1];
10041
10612
  case 4: return [3 /*break*/, 11];
10042
10613
  case 5:
10043
- e_28_1 = _h.sent();
10044
- e_28 = { error: e_28_1 };
10614
+ e_30_1 = _h.sent();
10615
+ e_30 = { error: e_30_1 };
10045
10616
  return [3 /*break*/, 11];
10046
10617
  case 6:
10047
10618
  _h.trys.push([6, , 9, 10]);
@@ -10052,7 +10623,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
10052
10623
  _h.label = 8;
10053
10624
  case 8: return [3 /*break*/, 10];
10054
10625
  case 9:
10055
- if (e_28) throw e_28.error;
10626
+ if (e_30) throw e_30.error;
10056
10627
  return [7 /*endfinally*/];
10057
10628
  case 10: return [7 /*endfinally*/];
10058
10629
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -10480,9 +11051,19 @@ var AI_ASSISTANT_DATA_REQUEST_PATTERNS = [
10480
11051
  /\bmissing\b/,
10481
11052
  /\bgroup(ed)? by\b/,
10482
11053
  /\bbreakdown\b/,
11054
+ /\bby day\b/,
11055
+ /\bby week\b/,
11056
+ /\bby month\b/,
11057
+ /\bby quarter\b/,
11058
+ /\bby year\b/,
11059
+ /\bby (time|date)\s+period\b/,
10483
11060
  /\bper day\b/,
10484
11061
  /\bper week\b/,
10485
- /\bper month\b/
11062
+ /\bper month\b/,
11063
+ /\bper quarter\b/,
11064
+ /\bper year\b/,
11065
+ /\bover the last\b/,
11066
+ /\bpast\s+\d+\b/
10486
11067
  ];
10487
11068
  var AI_ASSISTANT_NAVIGATION_REQUEST_PATTERNS = [
10488
11069
  /\bwhere\b/,
@@ -10635,13 +11216,79 @@ function classifyAssistantRequestType(message, plannerOutput) {
10635
11216
  plannerIntentType: plannerIntentRaw || undefined
10636
11217
  };
10637
11218
  }
10638
- function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText) {
11219
+ function resolveAssistantRequestedTimeGrain(message, plannerOutput) {
11220
+ var _a, _b;
11221
+ var plannerGrain = normalizeOptionalString((_b = (_a = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _a === void 0 ? void 0 : _a.timeRange) === null || _b === void 0 ? void 0 : _b.grain).toLowerCase();
11222
+ if (plannerGrain === 'day' || plannerGrain === 'week' || plannerGrain === 'month' || plannerGrain === 'quarter' || plannerGrain === 'year') {
11223
+ return plannerGrain;
11224
+ }
11225
+ var text = normalizeOptionalString(message).toLowerCase();
11226
+ if (!text) {
11227
+ return null;
11228
+ }
11229
+ var mapping = [
11230
+ { grain: 'quarter', pattern: /\b(quarter|quarters|quarterly|qoq)\b/i },
11231
+ { grain: 'month', pattern: /\b(month|months|monthly|mom)\b/i },
11232
+ { grain: 'week', pattern: /\b(week|weeks|weekly|wow)\b/i },
11233
+ { grain: 'day', pattern: /\b(day|days|daily)\b/i },
11234
+ { grain: 'year', pattern: /\b(year|years|yearly|yoy)\b/i }
11235
+ ];
11236
+ var match = mapping.find(function (entry) { return entry.pattern.test(text); });
11237
+ return (match === null || match === void 0 ? void 0 : match.grain) || null;
11238
+ }
11239
+ function hasAssistantDatedLanguage(message) {
11240
+ var text = normalizeOptionalString(message).toLowerCase();
11241
+ if (!text) {
11242
+ return false;
11243
+ }
11244
+ var patterns = [
11245
+ /\b(by|per)\s+(day|week|month|quarter|year|time\s*period|date\s*period)\b/i,
11246
+ /\b(over|across)\s+time\b/i,
11247
+ /\btime\s*series\b/i,
11248
+ /\btrend(?:ing|s)?\b/i,
11249
+ /\b(last|past|previous|recent)\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(day|week|month|quarter|year)s?\b/i,
11250
+ /\bover\s+the\s+last\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(day|week|month|quarter|year)s?\b/i,
11251
+ /\bmonth\s+over\s+month\b/i,
11252
+ /\bquarter\s+over\s+quarter\b/i,
11253
+ /\byear\s+over\s+year\b/i
11254
+ ];
11255
+ return patterns.some(function (pattern) { return pattern.test(text); });
11256
+ }
11257
+ function shouldEnforceAssistantDatedDirective(message, plannerOutput, requestClassification) {
11258
+ if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
11259
+ return false;
11260
+ }
11261
+ if (resolveAssistantRequestedTimeGrain(message, plannerOutput)) {
11262
+ return true;
11263
+ }
11264
+ return hasAssistantDatedLanguage(message);
11265
+ }
11266
+ function buildAssistantDirectiveStyleHint(params) {
11267
+ if (!params.enforceDated) {
11268
+ return '';
11269
+ }
11270
+ var grainLabel = params.requestedTimeGrain || 'time period';
11271
+ return [
11272
+ 'Report style intent: Dated.',
11273
+ "Requested time grain: ".concat(grainLabel, "."),
11274
+ '- Return REPORT_BUILDER_AGG (not REPORT_BUILDER_READ).',
11275
+ '- Ensure the pipeline groups by the requested time grain and requested breakdown dimensions.',
11276
+ '- For "last/past N" windows, use full completed calendar-period bounds in UTC unless the user asks for period-to-date.',
11277
+ params.strict ? '- STRICT: if unsure, still prefer REPORT_BUILDER_AGG.' : ''
11278
+ ].filter(Boolean).join('\n');
11279
+ }
11280
+ function buildAssistantCodexDirectivePrompt(message, attachmentText, historyText, contextText, directiveStyleHintText, mode) {
11281
+ if (mode === void 0) { mode = 'any'; }
10639
11282
  var trimmedContext = normalizeOptionalString(contextText);
10640
11283
  var contextBlock = trimmedContext ? "\n\nContext:\n".concat(trimmedContext) : '';
10641
11284
  var trimmedHistory = normalizeOptionalString(historyText);
10642
11285
  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();
11286
+ var trimmedStyleHint = normalizeOptionalString(directiveStyleHintText);
11287
+ var styleHintBlock = trimmedStyleHint ? "\n\nDirective style hints:\n".concat(trimmedStyleHint) : '';
11288
+ var instruction = mode === 'aggregate_only'
11289
+ ? '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_AGG directive line. Do not include any other text.'
11290
+ : '\n\nInstruction:\nReturn ONLY a single REPORT_BUILDER_READ or REPORT_BUILDER_AGG directive line. Do not include any other text.';
11291
+ return "System:\n".concat(AI_ASSISTANT_SYSTEM_PROMPT).concat(contextBlock).concat(historyBlock).concat(styleHintBlock, "\n\nUser:\n").concat(message).concat(attachmentText || '').concat(instruction).trim();
10645
11292
  }
10646
11293
  function buildAssistantCodexPrompt(message, attachmentText, historyText, contextText) {
10647
11294
  var trimmedContext = normalizeOptionalString(contextText);
@@ -10658,7 +11305,7 @@ function resolveAssistantPlannerEnabled() {
10658
11305
  return raw === undefined ? true : raw === true;
10659
11306
  }
10660
11307
  function resolveAssistantPlannerKnownRoutes() {
10661
- var e_29, _a;
11308
+ var e_31, _a;
10662
11309
  var _b;
10663
11310
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10664
11311
  var unique = new Set();
@@ -10671,12 +11318,12 @@ function resolveAssistantPlannerKnownRoutes() {
10671
11318
  }
10672
11319
  }
10673
11320
  }
10674
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
11321
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
10675
11322
  finally {
10676
11323
  try {
10677
11324
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
10678
11325
  }
10679
- finally { if (e_29) throw e_29.error; }
11326
+ finally { if (e_31) throw e_31.error; }
10680
11327
  }
10681
11328
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
10682
11329
  }
@@ -10919,7 +11566,7 @@ function normalizeRouteMatchKey(value) {
10919
11566
  return normalizeRouteKey(value).toLowerCase();
10920
11567
  }
10921
11568
  function buildClientRouteIndex() {
10922
- var e_30, _a;
11569
+ var e_32, _a;
10923
11570
  var _b;
10924
11571
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
10925
11572
  var set = new Set();
@@ -10938,12 +11585,12 @@ function buildClientRouteIndex() {
10938
11585
  }
10939
11586
  }
10940
11587
  }
10941
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
11588
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
10942
11589
  finally {
10943
11590
  try {
10944
11591
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
10945
11592
  }
10946
- finally { if (e_30) throw e_30.error; }
11593
+ finally { if (e_32) throw e_32.error; }
10947
11594
  }
10948
11595
  return { set: set, map: map, size: routes.length };
10949
11596
  }
@@ -11084,7 +11731,7 @@ function sanitizeAssistantResponse(value) {
11084
11731
  return normalizeAssistantRoutes(normalizedCurrency);
11085
11732
  }
11086
11733
  function evaluateAssistantGuardrails(message) {
11087
- var e_31, _a;
11734
+ var e_33, _a;
11088
11735
  var normalized = String(message || '').toLowerCase();
11089
11736
  var patterns = [
11090
11737
  {
@@ -11130,12 +11777,12 @@ function evaluateAssistantGuardrails(message) {
11130
11777
  }
11131
11778
  }
11132
11779
  }
11133
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
11780
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
11134
11781
  finally {
11135
11782
  try {
11136
11783
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
11137
11784
  }
11138
- finally { if (e_31) throw e_31.error; }
11785
+ finally { if (e_33) throw e_33.error; }
11139
11786
  }
11140
11787
  return null;
11141
11788
  }
@@ -11250,7 +11897,7 @@ function tokenizeArithmeticExpression(expression) {
11250
11897
  return tokens;
11251
11898
  }
11252
11899
  function evaluateArithmeticExpression(expression) {
11253
- var e_32, _a, e_33, _b;
11900
+ var e_34, _a, e_35, _b;
11254
11901
  var tokens = tokenizeArithmeticExpression(expression);
11255
11902
  if (!tokens || !tokens.length) {
11256
11903
  return null;
@@ -11307,12 +11954,12 @@ function evaluateArithmeticExpression(expression) {
11307
11954
  prevToken = token;
11308
11955
  }
11309
11956
  }
11310
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
11957
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
11311
11958
  finally {
11312
11959
  try {
11313
11960
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
11314
11961
  }
11315
- finally { if (e_32) throw e_32.error; }
11962
+ finally { if (e_34) throw e_34.error; }
11316
11963
  }
11317
11964
  while (ops.length) {
11318
11965
  var op = ops.pop();
@@ -11352,12 +11999,12 @@ function evaluateArithmeticExpression(expression) {
11352
11999
  stack.push(Number(token));
11353
12000
  }
11354
12001
  }
11355
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
12002
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
11356
12003
  finally {
11357
12004
  try {
11358
12005
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
11359
12006
  }
11360
- finally { if (e_33) throw e_33.error; }
12007
+ finally { if (e_35) throw e_35.error; }
11361
12008
  }
11362
12009
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
11363
12010
  return null;
@@ -11541,8 +12188,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
11541
12188
  }
11542
12189
  function readAttachmentContents(attachments) {
11543
12190
  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;
12191
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_36_1;
12192
+ var e_36, _b;
11546
12193
  return __generator(this, function (_c) {
11547
12194
  switch (_c.label) {
11548
12195
  case 0:
@@ -11621,14 +12268,14 @@ function readAttachmentContents(attachments) {
11621
12268
  return [3 /*break*/, 2];
11622
12269
  case 10: return [3 /*break*/, 13];
11623
12270
  case 11:
11624
- e_34_1 = _c.sent();
11625
- e_34 = { error: e_34_1 };
12271
+ e_36_1 = _c.sent();
12272
+ e_36 = { error: e_36_1 };
11626
12273
  return [3 /*break*/, 13];
11627
12274
  case 12:
11628
12275
  try {
11629
12276
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
11630
12277
  }
11631
- finally { if (e_34) throw e_34.error; }
12278
+ finally { if (e_36) throw e_36.error; }
11632
12279
  return [7 /*endfinally*/];
11633
12280
  case 13: return [2 /*return*/, {
11634
12281
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -11869,7 +12516,7 @@ function estimateUsage(messages, responseText, model) {
11869
12516
  };
11870
12517
  }
11871
12518
  function evaluateGuardrails(message) {
11872
- var e_35, _a;
12519
+ var e_37, _a;
11873
12520
  var normalized = String(message || '').toLowerCase();
11874
12521
  var patterns = [
11875
12522
  { pattern: /\b(source\s*code|full\s*code|entire\s*code|repo\s*dump|repository|git\s*clone)\b/i, reason: 'Code access is restricted.' },
@@ -11891,12 +12538,12 @@ function evaluateGuardrails(message) {
11891
12538
  }
11892
12539
  }
11893
12540
  }
11894
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
12541
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
11895
12542
  finally {
11896
12543
  try {
11897
12544
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
11898
12545
  }
11899
- finally { if (e_35) throw e_35.error; }
12546
+ finally { if (e_37) throw e_37.error; }
11900
12547
  }
11901
12548
  return null;
11902
12549
  }