@resolveio/server-lib 22.1.1 → 22.1.2

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.
@@ -84,15 +84,6 @@ var __read = (this && this.__read) || function (o, n) {
84
84
  }
85
85
  return ar;
86
86
  };
87
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
88
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
- if (ar || !(i in from)) {
90
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
- ar[i] = from[i];
92
- }
93
- }
94
- return to.concat(ar || Array.prototype.slice.call(from));
95
- };
96
87
  var __values = (this && this.__values) || function(o) {
97
88
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
98
89
  if (m) return m.call(o);
@@ -104,6 +95,15 @@ var __values = (this && this.__values) || function(o) {
104
95
  };
105
96
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
106
97
  };
98
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
99
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
100
+ if (ar || !(i in from)) {
101
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
102
+ ar[i] = from[i];
103
+ }
104
+ }
105
+ return to.concat(ar || Array.prototype.slice.call(from));
106
+ };
107
107
  Object.defineProperty(exports, "__esModule", { value: true });
108
108
  exports.loadAiTerminalMethods = loadAiTerminalMethods;
109
109
  exports.executeAiAssistantMongoRead = executeAiAssistantMongoRead;
@@ -124,6 +124,7 @@ exports.stripQueryFieldPathsDeep = stripQueryFieldPathsDeep;
124
124
  exports.stripScopedFieldsFromPipeline = stripScopedFieldsFromPipeline;
125
125
  exports.rewriteEmbeddedMatchObjects = rewriteEmbeddedMatchObjects;
126
126
  exports.resolveAssistantCollectionOverride = resolveAssistantCollectionOverride;
127
+ exports.resolveAssistantCrossCollectionFallbackCandidates = resolveAssistantCrossCollectionFallbackCandidates;
127
128
  exports.collectUserViewPermissions = collectUserViewPermissions;
128
129
  exports.userHasInvoiceAccess = userHasInvoiceAccess;
129
130
  exports.resolveAssistantUserAccessTier = resolveAssistantUserAccessTier;
@@ -148,6 +149,7 @@ var resolveio_server_app_1 = require("../resolveio-server-app");
148
149
  var user_collection_1 = require("../collections/user.collection");
149
150
  var ai_terminal_conversation_collection_1 = require("../collections/ai-terminal-conversation.collection");
150
151
  var ai_terminal_message_collection_1 = require("../collections/ai-terminal-message.collection");
152
+ var ai_terminal_issue_report_collection_1 = require("../collections/ai-terminal-issue-report.collection");
151
153
  var common_1 = require("../util/common");
152
154
  var tokenizer_1 = require("../util/tokenizer");
153
155
  var openai_client_1 = require("../services/openai-client");
@@ -247,6 +249,7 @@ var AI_ASSISTANT_BLOCKED_COLLECTIONS = new Set([
247
249
  'logged-in-users',
248
250
  'ai-terminal-messages',
249
251
  'ai-terminal-conversations',
252
+ 'ai-terminal-issue-reports',
250
253
  'openai-usage-ledger',
251
254
  'logs',
252
255
  'notifications',
@@ -347,7 +350,8 @@ var AI_ASSISTANT_COLLECTION_DOMAIN_TOKENS = new Set([
347
350
  'sample',
348
351
  'samples',
349
352
  'customer',
350
- 'customers'
353
+ 'customers',
354
+ 'support'
351
355
  ]);
352
356
  var AI_ASSISTANT_COLLECTION_GENERIC_TOKENS = new Set([
353
357
  'ticket',
@@ -406,6 +410,11 @@ var AI_ASSISTANT_TERM_SYNONYMS = [
406
410
  label: 'revenue',
407
411
  pattern: /\b(revenue|sales|billing)\b/i,
408
412
  expansions: ['invoice', 'invoices', 'paid invoices', 'invoice payments', 'billing', 'sales']
413
+ },
414
+ {
415
+ label: 'support tickets',
416
+ pattern: /\bsupport[\s-]*tickets?\b/i,
417
+ expansions: ['support-tickets', 'support ticket', 'ticket hours', 'billable hours']
409
418
  }
410
419
  ];
411
420
  var AI_ASSISTANT_REPORT_BUILDER_EXPERT_PLAYBOOK = [
@@ -1060,6 +1069,24 @@ function loadAiTerminalMethods(methodManager) {
1060
1069
  });
1061
1070
  });
1062
1071
  } }),
1072
+ aiCoderTerminalReportIssue: {
1073
+ check: new simpl_schema_1.default({
1074
+ payload: {
1075
+ type: Object,
1076
+ blackbox: true
1077
+ }
1078
+ }),
1079
+ function: function (payload) {
1080
+ return __awaiter(this, void 0, void 0, function () {
1081
+ return __generator(this, function (_a) {
1082
+ switch (_a.label) {
1083
+ case 0: return [4 /*yield*/, executeAiAssistantReportIssue(payload, this)];
1084
+ case 1: return [2 /*return*/, _a.sent()];
1085
+ }
1086
+ });
1087
+ });
1088
+ }
1089
+ },
1063
1090
  aiAssistantMongoRead: {
1064
1091
  check: new simpl_schema_1.default({
1065
1092
  payload: {
@@ -1587,10 +1614,10 @@ function executeAiAssistantCodexRun(payload, context) {
1587
1614
  insertResult = _e.sent();
1588
1615
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1589
1616
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1590
- var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, heuristicDirectivePrecomputed, usedDeterministicHeuristicFastPath, requestedTimeGrain, enforceDatedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerUsed, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, shouldRunPlanner, plannerPrompt, plannerStart, _b, preferListDirective, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, heuristicDirectiveFastPath, directivePrompt, directiveStart, forcedDirective, _c, initialStart, extractedDirective, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, heuristicDirective, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _g, toolPayload, skipFollowupCodex, followupPrompt, followupStart, followupText, _h, error_2, error_3, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
1591
- var _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
1592
- return __generator(this, function (_9) {
1593
- switch (_9.label) {
1617
+ var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, heuristicDirectivePrecomputed, usedDeterministicHeuristicFastPath, requestedTimeGrain, requestedBreakdownDimensions, enforceDatedDirective, enforceGroupedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerUsed, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, shouldRunPlanner, plannerPrompt, plannerStart, _b, preferListDirective, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, heuristicDirectiveFastPath, directivePrompt, directiveStart, forcedDirective, _c, initialStart, extractedDirective, error_2, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, groupedDirectivePrompt, groupedStart, groupedDirectiveText, groupedDirective, _g, heuristicDirective, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _h, toolPayload, skipFollowupCodex, followupPrompt, followupStart, followupText, _j, error_3, error_4, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
1618
+ var _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
1619
+ return __generator(this, function (_13) {
1620
+ switch (_13.label) {
1594
1621
  case 0:
1595
1622
  runStart = Date.now();
1596
1623
  if (aiWorkerDebug) {
@@ -1625,7 +1652,9 @@ function executeAiAssistantCodexRun(payload, context) {
1625
1652
  heuristicDirectivePrecomputed = null;
1626
1653
  usedDeterministicHeuristicFastPath = false;
1627
1654
  requestedTimeGrain = null;
1655
+ requestedBreakdownDimensions = [];
1628
1656
  enforceDatedDirective = false;
1657
+ enforceGroupedDirective = false;
1629
1658
  datedDirectiveRetryUsed = false;
1630
1659
  datedDirectiveResolved = false;
1631
1660
  toolResponseDebug = null;
@@ -1665,17 +1694,17 @@ function executeAiAssistantCodexRun(payload, context) {
1665
1694
  codexUsage.output_tokens += outputTokens;
1666
1695
  codexUsage.total_tokens += inputTokens + outputTokens;
1667
1696
  };
1668
- contextRoute = normalizeOptionalString((_j = input === null || input === void 0 ? void 0 : input.context) === null || _j === void 0 ? void 0 : _j.route);
1669
- contextMode = normalizeOptionalString((_k = input === null || input === void 0 ? void 0 : input.context) === null || _k === void 0 ? void 0 : _k.mode);
1697
+ contextRoute = normalizeOptionalString((_k = input === null || input === void 0 ? void 0 : input.context) === null || _k === void 0 ? void 0 : _k.route);
1698
+ contextMode = normalizeOptionalString((_l = input === null || input === void 0 ? void 0 : input.context) === null || _l === void 0 ? void 0 : _l.mode);
1670
1699
  recordStep('Queued', { requestId: requestId || undefined });
1671
1700
  recordStep('Planning: request classification', {
1672
1701
  type: requestClassification.type,
1673
1702
  source: requestClassification.source,
1674
1703
  dataQuestion: dataQuestion
1675
1704
  });
1676
- _9.label = 1;
1705
+ _13.label = 1;
1677
1706
  case 1:
1678
- _9.trys.push([1, 43, 44, 45]);
1707
+ _13.trys.push([1, 49, 50, 51]);
1679
1708
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1680
1709
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1681
1710
  hintText = termExpansion.expanded || hintSeed;
@@ -1696,19 +1725,19 @@ function executeAiAssistantCodexRun(payload, context) {
1696
1725
  recordStep('Planning: term expansion', {
1697
1726
  termMatches: termExpansion.matches.length ? termExpansion.matches : undefined
1698
1727
  });
1699
- _9.label = 2;
1728
+ _13.label = 2;
1700
1729
  case 2:
1701
- _9.trys.push([2, 4, , 5]);
1730
+ _13.trys.push([2, 4, , 5]);
1702
1731
  dbName = resolveAssistantDatabaseName(undefined, input.mongo);
1703
1732
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
1704
1733
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
1705
1734
  case 3:
1706
- collectionNames = _9.sent();
1735
+ collectionNames = _13.sent();
1707
1736
  collectionHints = resolveCollectionHintsFromTokens(expandedTokens, collectionNames, 5);
1708
1737
  collectionRanking = buildCollectionRankingDebugFromTokens(expandedTokens, collectionNames, 8);
1709
1738
  return [3 /*break*/, 5];
1710
1739
  case 4:
1711
- _a = _9.sent();
1740
+ _a = _13.sent();
1712
1741
  collectionHints = [];
1713
1742
  collectionRanking = collectionRanking || ((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens)
1714
1743
  ? buildCollectionRankingDebugFromTokens(collectionTokenization.expandedTokens || [], [], 0)
@@ -1751,14 +1780,14 @@ function executeAiAssistantCodexRun(payload, context) {
1751
1780
  if (hasDeterministicHeuristicFastPath) {
1752
1781
  recordStep('Planning: heuristic directive fast path', {
1753
1782
  type: heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.type,
1754
- collection: normalizeOptionalString((_l = heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.payload) === null || _l === void 0 ? void 0 : _l.collection) || undefined,
1783
+ collection: normalizeOptionalString((_m = heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1755
1784
  heuristic: normalizeOptionalString(heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.rawLine) || undefined
1756
1785
  });
1757
1786
  }
1758
1787
  prompt_1 = buildAssistantCodexPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1759
1788
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
1760
1789
  case 6:
1761
- workspaceRoot = _9.sent();
1790
+ workspaceRoot = _13.sent();
1762
1791
  codexConfig = resolveCodexSettings({
1763
1792
  model: codexModel,
1764
1793
  fallbackModels: codexFallbackModels
@@ -1797,41 +1826,48 @@ function executeAiAssistantCodexRun(payload, context) {
1797
1826
  fieldHints: fieldHints,
1798
1827
  inputClientId: input.id_client
1799
1828
  });
1800
- _9.label = 7;
1829
+ _13.label = 7;
1801
1830
  case 7:
1802
- _9.trys.push([7, 9, , 10]);
1831
+ _13.trys.push([7, 9, , 10]);
1803
1832
  plannerStart = Date.now();
1804
1833
  return [4 /*yield*/, runCodexInWorkerThread(plannerPrompt, runOptions, codexConfig, streamProgress)];
1805
1834
  case 8:
1806
- plannerRaw = _9.sent();
1835
+ plannerRaw = _13.sent();
1807
1836
  accumulateCodexUsage(plannerPrompt, plannerRaw);
1808
1837
  timingBreakdown.plannerMs = Date.now() - plannerStart;
1809
1838
  plannerOutput = parseJsonObject(plannerRaw);
1810
1839
  recordStep('Planning: planner result', { parsed: !!plannerOutput });
1811
1840
  return [3 /*break*/, 10];
1812
1841
  case 9:
1813
- _b = _9.sent();
1842
+ _b = _13.sent();
1814
1843
  recordStep('Planning: planner result', { parsed: false });
1815
1844
  return [3 /*break*/, 10];
1816
1845
  case 10:
1817
1846
  requestClassification = classifyAssistantRequestType(message, plannerOutput || undefined);
1818
1847
  dataQuestion = requestClassification.dataQuestion;
1819
1848
  requestedTimeGrain = resolveAssistantRequestedTimeGrain(message, plannerOutput || undefined);
1849
+ requestedBreakdownDimensions = extractAssistantRequestedBreakdownDimensions(message);
1820
1850
  preferListDirective = shouldPreferAssistantListDirective(message, plannerOutput || undefined, requestClassification);
1821
1851
  enforceDatedDirective = shouldEnforceAssistantDatedDirective(message, plannerOutput || undefined, requestClassification);
1852
+ enforceGroupedDirective = shouldEnforceAssistantGroupedDirective(message, plannerOutput || undefined, requestClassification);
1822
1853
  directiveStyleHint = buildAssistantDirectiveStyleHint({
1823
1854
  enforceDated: enforceDatedDirective,
1855
+ enforceGrouped: enforceGroupedDirective,
1824
1856
  requestedTimeGrain: requestedTimeGrain,
1857
+ requestedBreakdowns: requestedBreakdownDimensions,
1825
1858
  preferList: preferListDirective
1826
1859
  });
1827
- directivePromptMode = enforceDatedDirective ? 'aggregate_only' : 'any';
1860
+ directivePromptMode = (enforceDatedDirective || enforceGroupedDirective) ? 'aggregate_only' : 'any';
1828
1861
  datedDirectiveRetryUsed = false;
1829
1862
  recordStep('Planning: request classification', {
1830
1863
  type: requestClassification.type,
1831
1864
  source: requestClassification.source,
1832
1865
  plannerIntentType: requestClassification.plannerIntentType || undefined,
1833
1866
  dataQuestion: dataQuestion,
1834
- reportStyle: enforceDatedDirective ? 'dated' : undefined,
1867
+ reportStyle: enforceDatedDirective
1868
+ ? 'dated'
1869
+ : (enforceGroupedDirective ? 'grouped' : undefined),
1870
+ breakdownDimensions: requestedBreakdownDimensions.length ? requestedBreakdownDimensions : undefined,
1835
1871
  timeGrain: requestedTimeGrain || undefined
1836
1872
  });
1837
1873
  responseText = '';
@@ -1847,12 +1883,12 @@ function executeAiAssistantCodexRun(payload, context) {
1847
1883
  directiveSource = 'forced';
1848
1884
  lastDirective = heuristicDirectiveFastPath;
1849
1885
  usedDeterministicHeuristicFastPath = true;
1850
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_m = directive.payload) === null || _m === void 0 ? void 0 : _m.collection) || '');
1886
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.collection) || '');
1851
1887
  recordStep('Directive resolved', {
1852
1888
  source: directiveSource,
1853
1889
  type: directive.type,
1854
- collection: normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.collection) || undefined,
1855
- permissionView: normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.permissionView) || undefined,
1890
+ collection: normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || undefined,
1891
+ permissionView: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.permissionView) || undefined,
1856
1892
  reportStyle: 'heuristic_fast_path',
1857
1893
  timeGrain: requestedTimeGrain || undefined
1858
1894
  });
@@ -1860,13 +1896,13 @@ function executeAiAssistantCodexRun(payload, context) {
1860
1896
  if (!(dataQuestion && !directive)) return [3 /*break*/, 14];
1861
1897
  recordStep('Directive: determine tool', { type: 'data-question' });
1862
1898
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1863
- _9.label = 11;
1899
+ _13.label = 11;
1864
1900
  case 11:
1865
- _9.trys.push([11, 13, , 14]);
1901
+ _13.trys.push([11, 13, , 14]);
1866
1902
  directiveStart = Date.now();
1867
1903
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1868
1904
  case 12:
1869
- directiveText = _9.sent();
1905
+ directiveText = _13.sent();
1870
1906
  accumulateCodexUsage(directivePrompt, directiveText);
1871
1907
  timingBreakdown.directiveMs = Date.now() - directiveStart;
1872
1908
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1874,25 +1910,28 @@ function executeAiAssistantCodexRun(payload, context) {
1874
1910
  directive = forcedDirective;
1875
1911
  directiveSource = 'model';
1876
1912
  lastDirective = forcedDirective;
1877
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || '');
1913
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.collection) || '');
1878
1914
  recordStep('Directive resolved', {
1879
1915
  source: directiveSource,
1880
1916
  type: directive.type,
1881
- collection: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.collection) || undefined,
1882
- permissionView: normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.permissionView) || undefined
1917
+ collection: normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || undefined,
1918
+ permissionView: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.permissionView) || undefined
1883
1919
  });
1884
1920
  }
1885
1921
  return [3 /*break*/, 14];
1886
1922
  case 13:
1887
- _c = _9.sent();
1923
+ _c = _13.sent();
1888
1924
  return [3 /*break*/, 14];
1889
1925
  case 14:
1890
- if (!!directive) return [3 /*break*/, 16];
1926
+ if (!(!directive && !dataQuestion)) return [3 /*break*/, 18];
1891
1927
  recordStep('Response: draft initial answer', { mode: 'full' });
1928
+ _13.label = 15;
1929
+ case 15:
1930
+ _13.trys.push([15, 17, , 18]);
1892
1931
  initialStart = Date.now();
1893
1932
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
1894
- case 15:
1895
- responseText = _9.sent();
1933
+ case 16:
1934
+ responseText = _13.sent();
1896
1935
  accumulateCodexUsage(prompt_1, responseText);
1897
1936
  timingBreakdown.initialResponseMs = Date.now() - initialStart;
1898
1937
  extractedDirective = extractAssistantMongoDirective(responseText);
@@ -1900,26 +1939,32 @@ function executeAiAssistantCodexRun(payload, context) {
1900
1939
  if (directive) {
1901
1940
  directiveSource = 'model';
1902
1941
  lastDirective = directive;
1903
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection) || '');
1942
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.collection) || '');
1904
1943
  recordStep('Directive resolved', {
1905
1944
  source: directiveSource,
1906
1945
  type: directive.type,
1907
- collection: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.collection) || undefined,
1908
- permissionView: normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.permissionView) || undefined
1946
+ collection: normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || undefined,
1947
+ permissionView: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.permissionView) || undefined
1909
1948
  });
1910
1949
  }
1911
- _9.label = 16;
1912
- case 16:
1913
- if (!(!directive && dataQuestion)) return [3 /*break*/, 20];
1950
+ return [3 /*break*/, 18];
1951
+ case 17:
1952
+ error_2 = _13.sent();
1953
+ recordStep('Response: initial draft failed', {
1954
+ message: normalizeOptionalString(error_2 === null || error_2 === void 0 ? void 0 : error_2.message) || 'Unknown error'
1955
+ });
1956
+ return [3 /*break*/, 18];
1957
+ case 18:
1958
+ if (!(!directive && dataQuestion)) return [3 /*break*/, 22];
1914
1959
  recordStep('Directive: forced retry', { mode: 'directive-only' });
1915
1960
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
1916
- _9.label = 17;
1917
- case 17:
1918
- _9.trys.push([17, 19, , 20]);
1961
+ _13.label = 19;
1962
+ case 19:
1963
+ _13.trys.push([19, 21, , 22]);
1919
1964
  forcedStart = Date.now();
1920
1965
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
1921
- case 18:
1922
- directiveText = _9.sent();
1966
+ case 20:
1967
+ directiveText = _13.sent();
1923
1968
  accumulateCodexUsage(directivePrompt, directiveText);
1924
1969
  timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
1925
1970
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -1927,39 +1972,41 @@ function executeAiAssistantCodexRun(payload, context) {
1927
1972
  directive = forcedDirective;
1928
1973
  directiveSource = 'forced';
1929
1974
  lastDirective = forcedDirective;
1930
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.collection) || '');
1975
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.collection) || '');
1931
1976
  recordStep('Directive resolved', {
1932
1977
  source: directiveSource,
1933
1978
  type: directive.type,
1934
- collection: normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.collection) || undefined,
1935
- permissionView: normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.permissionView) || undefined
1979
+ collection: normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || undefined,
1980
+ permissionView: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.permissionView) || undefined
1936
1981
  });
1937
1982
  }
1938
- return [3 /*break*/, 20];
1939
- case 19:
1940
- _d = _9.sent();
1941
- return [3 /*break*/, 20];
1942
- case 20:
1983
+ return [3 /*break*/, 22];
1984
+ case 21:
1985
+ _d = _13.sent();
1986
+ return [3 /*break*/, 22];
1987
+ case 22:
1943
1988
  if (!(directive
1944
1989
  && enforceDatedDirective
1945
1990
  && !isAssistantDeterministicHeuristicDirective(directive)
1946
- && !isAssistantDirectiveDated(directive))) return [3 /*break*/, 24];
1991
+ && !isAssistantDirectiveDated(directive))) return [3 /*break*/, 26];
1947
1992
  recordStep('Directive: dated retry', {
1948
1993
  currentType: directive.type,
1949
1994
  timeGrain: requestedTimeGrain || undefined
1950
1995
  });
1951
1996
  strictDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1952
1997
  enforceDated: true,
1998
+ enforceGrouped: enforceGroupedDirective,
1953
1999
  requestedTimeGrain: requestedTimeGrain,
2000
+ requestedBreakdowns: requestedBreakdownDimensions,
1954
2001
  strict: true
1955
2002
  }), 'aggregate_only');
1956
- _9.label = 21;
1957
- case 21:
1958
- _9.trys.push([21, 23, , 24]);
2003
+ _13.label = 23;
2004
+ case 23:
2005
+ _13.trys.push([23, 25, , 26]);
1959
2006
  strictStart = Date.now();
1960
2007
  return [4 /*yield*/, runCodexInWorkerThread(strictDirectivePrompt, runOptions, codexConfig, streamProgress)];
1961
- case 22:
1962
- strictDirectiveText = _9.sent();
2008
+ case 24:
2009
+ strictDirectiveText = _13.sent();
1963
2010
  accumulateCodexUsage(strictDirectivePrompt, strictDirectiveText);
1964
2011
  timingBreakdown.forcedDirectiveMs += Date.now() - strictStart;
1965
2012
  strictDirective = extractAssistantMongoDirective(strictDirectiveText);
@@ -1970,41 +2017,43 @@ function executeAiAssistantCodexRun(payload, context) {
1970
2017
  directiveSource = 'forced';
1971
2018
  lastDirective = strictDirective;
1972
2019
  datedDirectiveRetryUsed = true;
1973
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.collection) || '');
2020
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.collection) || '');
1974
2021
  recordStep('Directive resolved', {
1975
2022
  source: directiveSource,
1976
2023
  type: directive.type,
1977
- collection: normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.collection) || undefined,
1978
- permissionView: normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.permissionView) || undefined,
2024
+ collection: normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection) || undefined,
2025
+ permissionView: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.permissionView) || undefined,
1979
2026
  reportStyle: strictDirectiveIsDated ? 'dated' : 'aggregate_fallback',
1980
2027
  timeGrain: requestedTimeGrain || undefined
1981
2028
  });
1982
2029
  }
1983
- return [3 /*break*/, 24];
1984
- case 23:
1985
- _e = _9.sent();
1986
- return [3 /*break*/, 24];
1987
- case 24:
2030
+ return [3 /*break*/, 26];
2031
+ case 25:
2032
+ _e = _13.sent();
2033
+ return [3 /*break*/, 26];
2034
+ case 26:
1988
2035
  if (!(directive
1989
2036
  && enforceDatedDirective
1990
2037
  && !isAssistantDeterministicHeuristicDirective(directive)
1991
- && directive.type === 'read')) return [3 /*break*/, 28];
2038
+ && directive.type === 'read')) return [3 /*break*/, 30];
1992
2039
  recordStep('Directive: dated guard retry', {
1993
2040
  currentType: directive.type,
1994
2041
  timeGrain: requestedTimeGrain || undefined
1995
2042
  });
1996
2043
  guardDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
1997
2044
  enforceDated: true,
2045
+ enforceGrouped: enforceGroupedDirective,
1998
2046
  requestedTimeGrain: requestedTimeGrain,
2047
+ requestedBreakdowns: requestedBreakdownDimensions,
1999
2048
  strict: true
2000
2049
  }), 'aggregate_only');
2001
- _9.label = 25;
2002
- case 25:
2003
- _9.trys.push([25, 27, , 28]);
2050
+ _13.label = 27;
2051
+ case 27:
2052
+ _13.trys.push([27, 29, , 30]);
2004
2053
  guardStart = Date.now();
2005
2054
  return [4 /*yield*/, runCodexInWorkerThread(guardDirectivePrompt, runOptions, codexConfig, streamProgress)];
2006
- case 26:
2007
- guardDirectiveText = _9.sent();
2055
+ case 28:
2056
+ guardDirectiveText = _13.sent();
2008
2057
  accumulateCodexUsage(guardDirectivePrompt, guardDirectiveText);
2009
2058
  timingBreakdown.forcedDirectiveMs += Date.now() - guardStart;
2010
2059
  guardDirective = extractAssistantMongoDirective(guardDirectiveText);
@@ -2013,21 +2062,69 @@ function executeAiAssistantCodexRun(payload, context) {
2013
2062
  directiveSource = 'forced';
2014
2063
  lastDirective = guardDirective;
2015
2064
  datedDirectiveRetryUsed = true;
2016
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.collection) || '');
2065
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_3 = directive.payload) === null || _3 === void 0 ? void 0 : _3.collection) || '');
2017
2066
  recordStep('Directive resolved', {
2018
2067
  source: directiveSource,
2019
2068
  type: directive.type,
2020
- collection: normalizeOptionalString((_3 = directive.payload) === null || _3 === void 0 ? void 0 : _3.collection) || undefined,
2021
- permissionView: normalizeOptionalString((_4 = directive.payload) === null || _4 === void 0 ? void 0 : _4.permissionView) || undefined,
2069
+ collection: normalizeOptionalString((_4 = directive.payload) === null || _4 === void 0 ? void 0 : _4.collection) || undefined,
2070
+ permissionView: normalizeOptionalString((_5 = directive.payload) === null || _5 === void 0 ? void 0 : _5.permissionView) || undefined,
2022
2071
  reportStyle: isAssistantDirectiveDated(guardDirective) ? 'dated' : 'aggregate_fallback',
2023
2072
  timeGrain: requestedTimeGrain || undefined
2024
2073
  });
2025
2074
  }
2026
- return [3 /*break*/, 28];
2027
- case 27:
2028
- _f = _9.sent();
2029
- return [3 /*break*/, 28];
2030
- case 28:
2075
+ return [3 /*break*/, 30];
2076
+ case 29:
2077
+ _f = _13.sent();
2078
+ return [3 /*break*/, 30];
2079
+ case 30:
2080
+ if (!(directive
2081
+ && enforceGroupedDirective
2082
+ && !isAssistantDeterministicHeuristicDirective(directive)
2083
+ && !isAssistantDirectiveGrouped(directive))) return [3 /*break*/, 34];
2084
+ recordStep('Directive: grouped guard retry', {
2085
+ currentType: directive.type,
2086
+ breakdownDimensions: requestedBreakdownDimensions.length ? requestedBreakdownDimensions : undefined
2087
+ });
2088
+ groupedDirectivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, buildAssistantDirectiveStyleHint({
2089
+ enforceDated: enforceDatedDirective,
2090
+ enforceGrouped: true,
2091
+ requestedTimeGrain: requestedTimeGrain,
2092
+ requestedBreakdowns: requestedBreakdownDimensions,
2093
+ strict: true
2094
+ }), 'aggregate_only');
2095
+ _13.label = 31;
2096
+ case 31:
2097
+ _13.trys.push([31, 33, , 34]);
2098
+ groupedStart = Date.now();
2099
+ return [4 /*yield*/, runCodexInWorkerThread(groupedDirectivePrompt, runOptions, codexConfig, streamProgress)];
2100
+ case 32:
2101
+ groupedDirectiveText = _13.sent();
2102
+ accumulateCodexUsage(groupedDirectivePrompt, groupedDirectiveText);
2103
+ timingBreakdown.forcedDirectiveMs += Date.now() - groupedStart;
2104
+ groupedDirective = extractAssistantMongoDirective(groupedDirectiveText);
2105
+ if (isAssistantExecutableDirective(groupedDirective) && isAssistantDirectiveGrouped(groupedDirective)) {
2106
+ directive = groupedDirective;
2107
+ directiveSource = 'forced';
2108
+ lastDirective = groupedDirective;
2109
+ datedDirectiveRetryUsed = true;
2110
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_6 = directive.payload) === null || _6 === void 0 ? void 0 : _6.collection) || '');
2111
+ recordStep('Directive resolved', {
2112
+ source: directiveSource,
2113
+ type: directive.type,
2114
+ collection: normalizeOptionalString((_7 = directive.payload) === null || _7 === void 0 ? void 0 : _7.collection) || undefined,
2115
+ permissionView: normalizeOptionalString((_8 = directive.payload) === null || _8 === void 0 ? void 0 : _8.permissionView) || undefined,
2116
+ reportStyle: isAssistantDirectiveDated(groupedDirective)
2117
+ ? 'dated'
2118
+ : 'grouped',
2119
+ breakdownDimensions: requestedBreakdownDimensions.length ? requestedBreakdownDimensions : undefined,
2120
+ timeGrain: requestedTimeGrain || undefined
2121
+ });
2122
+ }
2123
+ return [3 /*break*/, 34];
2124
+ case 33:
2125
+ _g = _13.sent();
2126
+ return [3 /*break*/, 34];
2127
+ case 34:
2031
2128
  if (!directive && dataQuestion) {
2032
2129
  heuristicDirective = buildAssistantHeuristicDirective(message, collectionHints);
2033
2130
  if (isAssistantExecutableDirective(heuristicDirective)) {
@@ -2037,19 +2134,19 @@ function executeAiAssistantCodexRun(payload, context) {
2037
2134
  recordStep('Directive resolved', {
2038
2135
  source: directiveSource,
2039
2136
  type: directive.type,
2040
- collection: normalizeOptionalString((_5 = directive.payload) === null || _5 === void 0 ? void 0 : _5.collection) || undefined,
2041
- permissionView: normalizeOptionalString((_6 = directive.payload) === null || _6 === void 0 ? void 0 : _6.permissionView) || undefined,
2137
+ collection: normalizeOptionalString((_9 = directive.payload) === null || _9 === void 0 ? void 0 : _9.collection) || undefined,
2138
+ permissionView: normalizeOptionalString((_10 = directive.payload) === null || _10 === void 0 ? void 0 : _10.permissionView) || undefined,
2042
2139
  reportStyle: 'heuristic_fallback'
2043
2140
  });
2044
2141
  }
2045
2142
  }
2046
2143
  if (directive) {
2047
- requestedCollection = normalizeOptionalString((_7 = directive.payload) === null || _7 === void 0 ? void 0 : _7.collection);
2144
+ requestedCollection = normalizeOptionalString((_11 = directive.payload) === null || _11 === void 0 ? void 0 : _11.collection);
2048
2145
  collectionOverride = resolveCollectionOverrideWithContext({
2049
2146
  message: message,
2050
2147
  collectionRanking: collectionRanking,
2051
2148
  requestedCollection: requestedCollection,
2052
- permissionView: normalizeOptionalString((_8 = directive.payload) === null || _8 === void 0 ? void 0 : _8.permissionView) || contextRoute,
2149
+ permissionView: normalizeOptionalString((_12 = directive.payload) === null || _12 === void 0 ? void 0 : _12.permissionView) || contextRoute,
2053
2150
  collectionNames: collectionNames
2054
2151
  });
2055
2152
  if (collectionOverride) {
@@ -2066,7 +2163,7 @@ function executeAiAssistantCodexRun(payload, context) {
2066
2163
  if (cleanedResponseText) {
2067
2164
  assistantContent = sanitizeAssistantResponse(cleanedResponseText);
2068
2165
  }
2069
- if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 41];
2166
+ if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 47];
2070
2167
  effectiveDirective = collectionOverride
2071
2168
  ? __assign(__assign({}, directive), { payload: __assign(__assign({}, (directive.payload || {})), { collection: collectionOverride.to }) }) : directive;
2072
2169
  toolRequest = buildAssistantToolRequest(effectiveDirective, input);
@@ -2076,21 +2173,21 @@ function executeAiAssistantCodexRun(payload, context) {
2076
2173
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
2077
2174
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
2078
2175
  });
2079
- _9.label = 29;
2080
- case 29:
2081
- _9.trys.push([29, 39, , 40]);
2176
+ _13.label = 35;
2177
+ case 35:
2178
+ _13.trys.push([35, 45, , 46]);
2082
2179
  toolStart = Date.now();
2083
- if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 31];
2180
+ if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 37];
2084
2181
  return [4 /*yield*/, executeAiAssistantReportBuilderAggregate(toolRequest, context)];
2085
- case 30:
2086
- _g = _9.sent();
2087
- return [3 /*break*/, 33];
2088
- case 31: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
2089
- case 32:
2090
- _g = _9.sent();
2091
- _9.label = 33;
2092
- case 33:
2093
- toolResponse = _g;
2182
+ case 36:
2183
+ _h = _13.sent();
2184
+ return [3 /*break*/, 39];
2185
+ case 37: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
2186
+ case 38:
2187
+ _h = _13.sent();
2188
+ _13.label = 39;
2189
+ case 39:
2190
+ toolResponse = _h;
2094
2191
  timingBreakdown.toolMs = Date.now() - toolStart;
2095
2192
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
2096
2193
  ? toolResponse.debug
@@ -2105,53 +2202,53 @@ function executeAiAssistantCodexRun(payload, context) {
2105
2202
  progressTracker.push('Drafting response');
2106
2203
  skipFollowupCodex = usedDeterministicHeuristicFastPath
2107
2204
  || isAssistantDeterministicHeuristicDirective(effectiveDirective);
2108
- if (!skipFollowupCodex) return [3 /*break*/, 34];
2205
+ if (!skipFollowupCodex) return [3 /*break*/, 40];
2109
2206
  recordStep('Drafting response: deterministic summary', {
2110
2207
  reason: normalizeOptionalString(effectiveDirective.rawLine) || 'deterministic_heuristic'
2111
2208
  });
2112
2209
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
2113
2210
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2114
- return [3 /*break*/, 38];
2115
- case 34:
2211
+ return [3 /*break*/, 44];
2212
+ case 40:
2116
2213
  recordStep('Drafting response');
2117
2214
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
2118
- _9.label = 35;
2119
- case 35:
2120
- _9.trys.push([35, 37, , 38]);
2215
+ _13.label = 41;
2216
+ case 41:
2217
+ _13.trys.push([41, 43, , 44]);
2121
2218
  followupStart = Date.now();
2122
2219
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
2123
- case 36:
2124
- followupText = _9.sent();
2220
+ case 42:
2221
+ followupText = _13.sent();
2125
2222
  accumulateCodexUsage(followupPrompt, followupText);
2126
2223
  timingBreakdown.followupMs = Date.now() - followupStart;
2127
2224
  assistantContent = sanitizeAssistantResponse(followupText);
2128
2225
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2129
- return [3 /*break*/, 38];
2130
- case 37:
2131
- _h = _9.sent();
2226
+ return [3 /*break*/, 44];
2227
+ case 43:
2228
+ _j = _13.sent();
2132
2229
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
2133
- return [3 /*break*/, 38];
2134
- case 38: return [3 /*break*/, 40];
2135
- case 39:
2136
- error_2 = _9.sent();
2137
- assistantContent = buildAssistantToolErrorMessage(error_2);
2138
- toolError = error_2;
2139
- return [3 /*break*/, 40];
2140
- case 40: return [3 /*break*/, 42];
2141
- case 41:
2230
+ return [3 /*break*/, 44];
2231
+ case 44: return [3 /*break*/, 46];
2232
+ case 45:
2233
+ error_3 = _13.sent();
2234
+ assistantContent = buildAssistantToolErrorMessage(error_3);
2235
+ toolError = error_3;
2236
+ return [3 /*break*/, 46];
2237
+ case 46: return [3 /*break*/, 48];
2238
+ case 47:
2142
2239
  progressTracker.push('Drafting response');
2143
2240
  recordStep('Drafting response');
2144
- _9.label = 42;
2145
- case 42: return [3 /*break*/, 45];
2146
- case 43:
2147
- error_3 = _9.sent();
2148
- assistantContent = buildAssistantCodexErrorMessage(error_3);
2149
- recordStep('Error', { message: normalizeOptionalString(error_3 === null || error_3 === void 0 ? void 0 : error_3.message) || 'Unknown error' });
2150
- return [3 /*break*/, 45];
2151
- case 44:
2241
+ _13.label = 48;
2242
+ case 48: return [3 /*break*/, 51];
2243
+ case 49:
2244
+ error_4 = _13.sent();
2245
+ assistantContent = buildAssistantCodexErrorMessage(error_4);
2246
+ recordStep('Error', { message: normalizeOptionalString(error_4 === null || error_4 === void 0 ? void 0 : error_4.message) || 'Unknown error' });
2247
+ return [3 /*break*/, 51];
2248
+ case 50:
2152
2249
  progressTracker.stop();
2153
2250
  return [7 /*endfinally*/];
2154
- case 45:
2251
+ case 51:
2155
2252
  if (!assistantContent) {
2156
2253
  assistantContent = buildAssistantCodexErrorMessage(null);
2157
2254
  }
@@ -2188,7 +2285,9 @@ function executeAiAssistantCodexRun(payload, context) {
2188
2285
  requestTypeSource: requestClassification.source,
2189
2286
  plannerIntentType: requestClassification.plannerIntentType,
2190
2287
  dataQuestion: dataQuestion,
2191
- reportStyleIntent: enforceDatedDirective ? 'dated' : null,
2288
+ reportStyleIntent: enforceDatedDirective
2289
+ ? 'dated'
2290
+ : (enforceGroupedDirective ? 'grouped' : null),
2192
2291
  requestedTimeGrain: requestedTimeGrain,
2193
2292
  datedDirectiveRetryUsed: datedDirectiveRetryUsed,
2194
2293
  datedDirectiveResolved: datedDirectiveResolved,
@@ -2245,14 +2344,14 @@ function executeAiAssistantCodexRun(payload, context) {
2245
2344
  output_tokens: codexUsage.output_tokens,
2246
2345
  total_tokens: codexUsage.total_tokens
2247
2346
  } : null;
2248
- if (!finalUsage) return [3 /*break*/, 50];
2347
+ if (!finalUsage) return [3 /*break*/, 56];
2249
2348
  return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
2250
- case 46:
2251
- usageClientId = _9.sent();
2252
- if (!usageClientId) return [3 /*break*/, 50];
2253
- _9.label = 47;
2254
- case 47:
2255
- _9.trys.push([47, 49, , 50]);
2349
+ case 52:
2350
+ usageClientId = _13.sent();
2351
+ if (!usageClientId) return [3 /*break*/, 56];
2352
+ _13.label = 53;
2353
+ case 53:
2354
+ _13.trys.push([53, 55, , 56]);
2256
2355
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
2257
2356
  id_client: usageClientId,
2258
2357
  model: finalUsage.model,
@@ -2263,16 +2362,16 @@ function executeAiAssistantCodexRun(payload, context) {
2263
2362
  id_request: requestId || undefined,
2264
2363
  id_conversation: conversation._id
2265
2364
  })];
2266
- case 48:
2267
- _9.sent();
2268
- return [3 /*break*/, 50];
2269
- case 49:
2270
- usageError_1 = _9.sent();
2365
+ case 54:
2366
+ _13.sent();
2367
+ return [3 /*break*/, 56];
2368
+ case 55:
2369
+ usageError_1 = _13.sent();
2271
2370
  console.error(new Date(), 'Failed to record codex usage', usageError_1);
2272
- return [3 /*break*/, 50];
2273
- case 50:
2371
+ return [3 /*break*/, 56];
2372
+ case 56:
2274
2373
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
2275
- if (!assistantMessageId) return [3 /*break*/, 52];
2374
+ if (!assistantMessageId) return [3 /*break*/, 58];
2276
2375
  setPayload = {
2277
2376
  content: assistantContent,
2278
2377
  metadata: finalMetadata,
@@ -2282,18 +2381,18 @@ function executeAiAssistantCodexRun(payload, context) {
2282
2381
  setPayload.usage = finalUsage;
2283
2382
  }
2284
2383
  return [4 /*yield*/, updateAssistantMessageWithFallback(assistantMessageId, setPayload)];
2285
- case 51:
2286
- _9.sent();
2287
- _9.label = 52;
2288
- case 52: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2289
- case 53:
2290
- _9.sent();
2291
- if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 55];
2384
+ case 57:
2385
+ _13.sent();
2386
+ _13.label = 58;
2387
+ case 58: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2388
+ case 59:
2389
+ _13.sent();
2390
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 61];
2292
2391
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
2293
- case 54:
2294
- _9.sent();
2295
- _9.label = 55;
2296
- case 55: return [2 /*return*/, finalAssistantDoc];
2392
+ case 60:
2393
+ _13.sent();
2394
+ _13.label = 61;
2395
+ case 61: return [2 /*return*/, finalAssistantDoc];
2297
2396
  }
2298
2397
  });
2299
2398
  }); });
@@ -2324,38 +2423,155 @@ function executeAiAssistantReportBuilderAggregate(payload, context) {
2324
2423
  });
2325
2424
  });
2326
2425
  }
2426
+ function executeAiAssistantReportIssue(payload, context) {
2427
+ return __awaiter(this, void 0, void 0, function () {
2428
+ var input, reason, expected, requestedConversationId, requestedMessageId, conversationId, assistantMessage, messageConversationId, conversation, userPrompt, createdAt, userQuery, userMessage, assistantContent, toolResult, reportMetadata, category, severity, requestId, idClient, _a, idApp, now, doc, insertResult;
2429
+ var _b, _c, _d, _e, _f, _g;
2430
+ return __generator(this, function (_h) {
2431
+ switch (_h.label) {
2432
+ case 0:
2433
+ input = payload || {};
2434
+ reason = normalizeOptionalString(input.reason);
2435
+ expected = normalizeOptionalString(input.expected);
2436
+ if (reason.length < 3) {
2437
+ throw new Error('Issue reason is required.');
2438
+ }
2439
+ requestedConversationId = normalizeOptionalString(input.id_conversation);
2440
+ requestedMessageId = normalizeOptionalString(input.id_message);
2441
+ conversationId = requestedConversationId;
2442
+ assistantMessage = null;
2443
+ if (!requestedMessageId) return [3 /*break*/, 2];
2444
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.findOne({ _id: requestedMessageId })];
2445
+ case 1:
2446
+ assistantMessage = (_h.sent());
2447
+ if (!assistantMessage) {
2448
+ throw new Error('Assistant message not found.');
2449
+ }
2450
+ messageConversationId = normalizeOptionalString(assistantMessage.id_conversation);
2451
+ if (!conversationId) {
2452
+ conversationId = messageConversationId;
2453
+ }
2454
+ else if (messageConversationId && messageConversationId !== conversationId) {
2455
+ throw new Error('Message does not belong to the selected conversation.');
2456
+ }
2457
+ _h.label = 2;
2458
+ case 2:
2459
+ if (!conversationId) {
2460
+ throw new Error('Conversation id is required.');
2461
+ }
2462
+ return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.findOne({ _id: conversationId })];
2463
+ case 3:
2464
+ conversation = _h.sent();
2465
+ if (!conversation) {
2466
+ throw new Error('Conversation not found.');
2467
+ }
2468
+ if (!!assistantMessage) return [3 /*break*/, 5];
2469
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.findOne({ id_conversation: conversationId, role: 'assistant' }, { sort: { createdAt: -1 } })];
2470
+ case 4:
2471
+ assistantMessage = (_h.sent());
2472
+ _h.label = 5;
2473
+ case 5:
2474
+ userPrompt = '';
2475
+ if (!assistantMessage) return [3 /*break*/, 7];
2476
+ createdAt = (assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage.createdAt) ? new Date(assistantMessage.createdAt) : null;
2477
+ userQuery = {
2478
+ id_conversation: conversationId,
2479
+ role: 'user'
2480
+ };
2481
+ if (createdAt && Number.isFinite(createdAt.getTime())) {
2482
+ userQuery.createdAt = { $lte: createdAt };
2483
+ }
2484
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.findOne(userQuery, { sort: { createdAt: -1 } })];
2485
+ case 6:
2486
+ userMessage = _h.sent();
2487
+ if (userMessage === null || userMessage === void 0 ? void 0 : userMessage.content) {
2488
+ userPrompt = normalizeOptionalString(userMessage.content);
2489
+ }
2490
+ _h.label = 7;
2491
+ case 7:
2492
+ assistantContent = normalizeOptionalString(assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage.content);
2493
+ toolResult = (_b = assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage.metadata) === null || _b === void 0 ? void 0 : _b.tool_result;
2494
+ reportMetadata = (input === null || input === void 0 ? void 0 : input.metadata) && typeof input.metadata === 'object' && !Array.isArray(input.metadata)
2495
+ ? __assign({}, input.metadata) : {};
2496
+ category = normalizeOptionalString(input.category);
2497
+ severity = normalizeOptionalString(input.severity);
2498
+ if (category) {
2499
+ reportMetadata.category = category;
2500
+ }
2501
+ if (severity) {
2502
+ reportMetadata.severity = severity;
2503
+ }
2504
+ requestId = normalizeOptionalString(input.request_id)
2505
+ || normalizeOptionalString((_c = assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage.metadata) === null || _c === void 0 ? void 0 : _c.request_id);
2506
+ _a = normalizeOptionalString(input.id_client)
2507
+ || normalizeOptionalString(conversation === null || conversation === void 0 ? void 0 : conversation.id_client);
2508
+ if (_a) return [3 /*break*/, 9];
2509
+ return [4 /*yield*/, resolveClientIdFromConfig(undefined, context === null || context === void 0 ? void 0 : context.id_user)];
2510
+ case 8:
2511
+ _a = (_h.sent());
2512
+ _h.label = 9;
2513
+ case 9:
2514
+ idClient = _a;
2515
+ idApp = normalizeOptionalString(input.id_app)
2516
+ || normalizeOptionalString(conversation === null || conversation === void 0 ? void 0 : conversation.id_app);
2517
+ now = new Date();
2518
+ doc = __assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign(__assign({ id_conversation: conversationId, status: 'open', source: 'user_report', reason: reason }, (expected ? { expected_outcome: expected } : {})), (userPrompt ? { user_prompt: userPrompt } : {})), (assistantContent ? { assistant_content: assistantContent } : {})), (requestId ? { request_id: requestId } : {})), ((toolResult === null || toolResult === void 0 ? void 0 : toolResult.type) ? { tool_type: normalizeOptionalString(toolResult.type) } : {})), (((_d = toolResult === null || toolResult === void 0 ? void 0 : toolResult.output) === null || _d === void 0 ? void 0 : _d.collection) || ((_e = toolResult === null || toolResult === void 0 ? void 0 : toolResult.input) === null || _e === void 0 ? void 0 : _e.collection)
2519
+ ? { tool_collection: normalizeOptionalString(((_f = toolResult === null || toolResult === void 0 ? void 0 : toolResult.output) === null || _f === void 0 ? void 0 : _f.collection) || ((_g = toolResult === null || toolResult === void 0 ? void 0 : toolResult.input) === null || _g === void 0 ? void 0 : _g.collection)) }
2520
+ : {})), (requestedMessageId || (assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage._id) ? { id_message: normalizeOptionalString(requestedMessageId || (assistantMessage === null || assistantMessage === void 0 ? void 0 : assistantMessage._id)) } : {})), (idClient ? { id_client: idClient } : {})), (idApp ? { id_app: idApp } : {})), (normalizeOptionalString(context === null || context === void 0 ? void 0 : context.id_user) ? { id_user: normalizeOptionalString(context.id_user) } : {})), (Object.keys(reportMetadata).length ? { metadata: reportMetadata } : {})), { createdAt: now, updatedAt: now });
2521
+ return [4 /*yield*/, ai_terminal_issue_report_collection_1.AiTerminalIssueReports.insertOne(doc)];
2522
+ case 10:
2523
+ insertResult = _h.sent();
2524
+ return [2 /*return*/, {
2525
+ id_issue_report: insertResult._id,
2526
+ id_conversation: conversationId,
2527
+ id_message: normalizeOptionalString(doc.id_message),
2528
+ status: 'open'
2529
+ }];
2530
+ }
2531
+ });
2532
+ });
2533
+ }
2327
2534
  function executeAiAssistantMongoRead(payload, context) {
2328
2535
  return __awaiter(this, void 0, void 0, function () {
2329
- var input, rawCollection, dbName, db, collectionResolution, collection, bridgeCollection, schemaFields, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, strippedClient, clientScopedQuery, scopedQuery, normalized, findOptions, documents, executedQuery, probeDocs, dateFallback, fallbackQuery, fallbackDocs, expanded, fallbackDocs, nameFallback, fallbackDocs, _c, chemicalLookup, fallbackDocs, queryFields, _d, aliases, rewrittenQuery, fallbackDocs, _e, activeFallback, fallbackDocs, _f, idLookup, fallbackDocs, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, nameFields, dateFields, diagnostics, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, total, sanitizedDocuments, requestedFields, missingFields, _o, projectionAliases, expandedProjection, refreshedDocs, includeIds, fieldAliases, displayDocs, idLookupDisplay, priorityFields, displayMaxRows, display;
2330
- var _p, _q;
2331
- return __generator(this, function (_r) {
2332
- switch (_r.label) {
2536
+ var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, strippedClient, clientScopedQuery, scopedQuery, normalized, findOptions, documents, executedQuery, probeDocs, dateFallback, fallbackQuery, fallbackDocs, expanded, fallbackDocs, nameFallback, fallbackDocs, _c, chemicalLookup, fallbackDocs, queryFields, _d, aliases, rewrittenQuery, fallbackDocs, _e, activeFallback, fallbackDocs, _f, idLookup, fallbackDocs, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, crossCollectionCandidates, crossCollectionCandidates_1, crossCollectionCandidates_1_1, candidateCollection, fallbackPayload, fallbackResult, existingFallbacks, e_1_1, nameFields, dateFields, diagnostics, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, total, sanitizedDocuments, requestedFields, missingFields, _o, projectionAliases, expandedProjection, refreshedDocs, includeIds, fieldAliases, displayDocs, idLookupDisplay, priorityFields, displayMaxRows, display;
2537
+ var e_1, _p;
2538
+ var _q, _r;
2539
+ return __generator(this, function (_s) {
2540
+ switch (_s.label) {
2333
2541
  case 0:
2334
2542
  input = payload || {};
2335
2543
  rawCollection = normalizeOptionalString(input.collection);
2336
2544
  if (!rawCollection) {
2337
2545
  throw new Error('AI assistant report builder bridge: Collection is required.');
2338
2546
  }
2547
+ retryState = input.__assistantRetryState && typeof input.__assistantRetryState === 'object'
2548
+ ? input.__assistantRetryState
2549
+ : {};
2550
+ triedCollections = buildAssistantTriedCollectionSet(retryState.triedCollections);
2551
+ addAssistantCollectionToTriedSet(triedCollections, rawCollection);
2552
+ crossCollectionRetryEnabled = retryState.disableCrossCollectionRetry !== true;
2339
2553
  dbName = resolveAssistantDatabaseName(input.database, input.mongo);
2340
2554
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
2341
2555
  return [4 /*yield*/, resolveAssistantCollectionName(db, dbName, rawCollection)];
2342
2556
  case 1:
2343
- collectionResolution = _r.sent();
2557
+ collectionResolution = _s.sent();
2344
2558
  collection = collectionResolution.name || rawCollection;
2345
2559
  return [4 /*yield*/, resolveAssistantReportBuilderBridgeCollection(collection, db, dbName)];
2346
2560
  case 2:
2347
- bridgeCollection = _r.sent();
2561
+ bridgeCollection = _s.sent();
2348
2562
  if (bridgeCollection.fallbackFrom) {
2349
2563
  collection = bridgeCollection.collection;
2350
2564
  }
2565
+ addAssistantCollectionToTriedSet(triedCollections, collection);
2566
+ retryRootCollection = normalizeOptionalString(retryState.rootCollection) || collection;
2351
2567
  schemaFields = getCollectionSchemaFieldNames(collection);
2352
2568
  return [4 /*yield*/, ensureAssistantReadAccess(context, input.permissionView, collection)];
2353
2569
  case 3:
2354
- _a = _r.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
2570
+ _a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
2355
2571
  if (!isSuperAdmin && AI_ASSISTANT_BLOCKED_COLLECTIONS.has(collection)) {
2356
2572
  throw new Error('AI assistant report builder bridge: Access denied.');
2357
2573
  }
2358
- customerId = normalizeOptionalString((_p = user === null || user === void 0 ? void 0 : user.other) === null || _p === void 0 ? void 0 : _p.id_customer);
2574
+ customerId = normalizeOptionalString((_q = user === null || user === void 0 ? void 0 : user.other) === null || _q === void 0 ? void 0 : _q.id_customer);
2359
2575
  fallbackMeta = {};
2360
2576
  if (bridgeCollection.fallbackFrom) {
2361
2577
  fallbackMeta.reportBuilderBridge = {
@@ -2387,11 +2603,11 @@ function executeAiAssistantMongoRead(payload, context) {
2387
2603
  if (!(!isSuperAdmin && normalizedClient)) return [3 /*break*/, 5];
2388
2604
  return [4 /*yield*/, collectionHasClientIndex(db, dbName, collection)];
2389
2605
  case 4:
2390
- _b = _r.sent();
2606
+ _b = _s.sent();
2391
2607
  return [3 /*break*/, 6];
2392
2608
  case 5:
2393
2609
  _b = false;
2394
- _r.label = 6;
2610
+ _s.label = 6;
2395
2611
  case 6:
2396
2612
  shouldScopeByClient = _b;
2397
2613
  if (!isSuperAdmin && shouldScopeByClient) {
@@ -2411,7 +2627,7 @@ function executeAiAssistantMongoRead(payload, context) {
2411
2627
  findOptions = __assign(__assign({}, normalized.findOptions), { readPreference: AI_ASSISTANT_READ_PREFERENCE });
2412
2628
  return [4 /*yield*/, db.collection(collection).find(scopedQuery, findOptions).toArray()];
2413
2629
  case 7:
2414
- documents = _r.sent();
2630
+ documents = _s.sent();
2415
2631
  executedQuery = scopedQuery;
2416
2632
  probeDocs = null;
2417
2633
  if (!!documents.length) return [3 /*break*/, 9];
@@ -2421,13 +2637,13 @@ function executeAiAssistantMongoRead(payload, context) {
2421
2637
  fallbackMeta.dateField = __assign(__assign({}, dateFallback), { attempted: true, used: false });
2422
2638
  return [4 /*yield*/, db.collection(collection).find(fallbackQuery, findOptions).toArray()];
2423
2639
  case 8:
2424
- fallbackDocs = _r.sent();
2640
+ fallbackDocs = _s.sent();
2425
2641
  if (fallbackDocs.length) {
2426
2642
  documents = fallbackDocs;
2427
2643
  executedQuery = fallbackQuery;
2428
2644
  fallbackMeta.dateField.used = true;
2429
2645
  }
2430
- _r.label = 9;
2646
+ _s.label = 9;
2431
2647
  case 9:
2432
2648
  if (!!documents.length) return [3 /*break*/, 11];
2433
2649
  expanded = expandQueryDateFallbacks(executedQuery, schemaFields);
@@ -2439,13 +2655,13 @@ function executeAiAssistantMongoRead(payload, context) {
2439
2655
  };
2440
2656
  return [4 /*yield*/, db.collection(collection).find(expanded.query, findOptions).toArray()];
2441
2657
  case 10:
2442
- fallbackDocs = _r.sent();
2658
+ fallbackDocs = _s.sent();
2443
2659
  if (fallbackDocs.length) {
2444
2660
  documents = fallbackDocs;
2445
2661
  executedQuery = expanded.query;
2446
2662
  fallbackMeta.dateFieldsExpanded.used = true;
2447
2663
  }
2448
- _r.label = 11;
2664
+ _s.label = 11;
2449
2665
  case 11:
2450
2666
  if (!!documents.length) return [3 /*break*/, 13];
2451
2667
  nameFallback = resolveReadNameMatchFallback(executedQuery);
@@ -2458,13 +2674,13 @@ function executeAiAssistantMongoRead(payload, context) {
2458
2674
  };
2459
2675
  return [4 /*yield*/, db.collection(collection).find(nameFallback.query, findOptions).toArray()];
2460
2676
  case 12:
2461
- fallbackDocs = _r.sent();
2677
+ fallbackDocs = _s.sent();
2462
2678
  if (fallbackDocs.length) {
2463
2679
  documents = fallbackDocs;
2464
2680
  executedQuery = nameFallback.query;
2465
2681
  fallbackMeta.nameMatch.used = true;
2466
2682
  }
2467
- _r.label = 13;
2683
+ _s.label = 13;
2468
2684
  case 13:
2469
2685
  if (!!documents.length) return [3 /*break*/, 18];
2470
2686
  _c = probeDocs;
@@ -2478,8 +2694,8 @@ function executeAiAssistantMongoRead(payload, context) {
2478
2694
  includeClientScope: shouldScopeByClient
2479
2695
  })];
2480
2696
  case 14:
2481
- _c = (_r.sent());
2482
- _r.label = 15;
2697
+ _c = (_s.sent());
2698
+ _s.label = 15;
2483
2699
  case 15:
2484
2700
  probeDocs = _c;
2485
2701
  return [4 /*yield*/, applyChemicalNameLookupFallbackToQuery({
@@ -2492,18 +2708,18 @@ function executeAiAssistantMongoRead(payload, context) {
2492
2708
  probeDocs: probeDocs || undefined
2493
2709
  })];
2494
2710
  case 16:
2495
- chemicalLookup = _r.sent();
2711
+ chemicalLookup = _s.sent();
2496
2712
  if (!chemicalLookup) return [3 /*break*/, 18];
2497
2713
  fallbackMeta.chemicalLookup = __assign(__assign({}, chemicalLookup.meta), { attempted: true, used: false });
2498
2714
  return [4 /*yield*/, db.collection(collection).find(chemicalLookup.query, findOptions).toArray()];
2499
2715
  case 17:
2500
- fallbackDocs = _r.sent();
2716
+ fallbackDocs = _s.sent();
2501
2717
  if (fallbackDocs.length) {
2502
2718
  documents = fallbackDocs;
2503
2719
  executedQuery = chemicalLookup.query;
2504
2720
  fallbackMeta.chemicalLookup.used = true;
2505
2721
  }
2506
- _r.label = 18;
2722
+ _s.label = 18;
2507
2723
  case 18:
2508
2724
  if (!!documents.length) return [3 /*break*/, 22];
2509
2725
  queryFields = extractQueryFieldPaths(executedQuery).filter(function (field) { return !isAssistantIdField(field); });
@@ -2519,8 +2735,8 @@ function executeAiAssistantMongoRead(payload, context) {
2519
2735
  includeClientScope: shouldScopeByClient
2520
2736
  })];
2521
2737
  case 19:
2522
- _d = (_r.sent());
2523
- _r.label = 20;
2738
+ _d = (_s.sent());
2739
+ _s.label = 20;
2524
2740
  case 20:
2525
2741
  probeDocs = _d;
2526
2742
  if (!probeDocs.length) return [3 /*break*/, 22];
@@ -2538,13 +2754,13 @@ function executeAiAssistantMongoRead(payload, context) {
2538
2754
  }, executedQuery);
2539
2755
  return [4 /*yield*/, db.collection(collection).find(rewrittenQuery, findOptions).toArray()];
2540
2756
  case 21:
2541
- fallbackDocs = _r.sent();
2757
+ fallbackDocs = _s.sent();
2542
2758
  if (fallbackDocs.length) {
2543
2759
  documents = fallbackDocs;
2544
2760
  executedQuery = rewrittenQuery;
2545
2761
  fallbackMeta.queryFieldAliases.used = true;
2546
2762
  }
2547
- _r.label = 22;
2763
+ _s.label = 22;
2548
2764
  case 22:
2549
2765
  if (!!documents.length) return [3 /*break*/, 26];
2550
2766
  _e = probeDocs;
@@ -2558,8 +2774,8 @@ function executeAiAssistantMongoRead(payload, context) {
2558
2774
  includeClientScope: shouldScopeByClient
2559
2775
  })];
2560
2776
  case 23:
2561
- _e = (_r.sent());
2562
- _r.label = 24;
2777
+ _e = (_s.sent());
2778
+ _s.label = 24;
2563
2779
  case 24:
2564
2780
  probeDocs = _e;
2565
2781
  activeFallback = resolveReadActiveStatusFallback(executedQuery, probeDocs || []);
@@ -2572,13 +2788,13 @@ function executeAiAssistantMongoRead(payload, context) {
2572
2788
  };
2573
2789
  return [4 /*yield*/, db.collection(collection).find(activeFallback.query, findOptions).toArray()];
2574
2790
  case 25:
2575
- fallbackDocs = _r.sent();
2791
+ fallbackDocs = _s.sent();
2576
2792
  if (fallbackDocs.length) {
2577
2793
  documents = fallbackDocs;
2578
2794
  executedQuery = activeFallback.query;
2579
2795
  fallbackMeta.activeStatus.used = true;
2580
2796
  }
2581
- _r.label = 26;
2797
+ _s.label = 26;
2582
2798
  case 26:
2583
2799
  if (!!documents.length) return [3 /*break*/, 31];
2584
2800
  _f = probeDocs;
@@ -2592,8 +2808,8 @@ function executeAiAssistantMongoRead(payload, context) {
2592
2808
  includeClientScope: shouldScopeByClient
2593
2809
  })];
2594
2810
  case 27:
2595
- _f = (_r.sent());
2596
- _r.label = 28;
2811
+ _f = (_s.sent());
2812
+ _s.label = 28;
2597
2813
  case 28:
2598
2814
  probeDocs = _f;
2599
2815
  return [4 /*yield*/, applyIdLookupFallbackToQuery({
@@ -2606,28 +2822,31 @@ function executeAiAssistantMongoRead(payload, context) {
2606
2822
  probeDocs: probeDocs || undefined
2607
2823
  })];
2608
2824
  case 29:
2609
- idLookup = _r.sent();
2825
+ idLookup = _s.sent();
2610
2826
  if (!idLookup) return [3 /*break*/, 31];
2611
2827
  fallbackMeta.idLookup = __assign(__assign({}, idLookup.meta), { attempted: true, used: false });
2612
2828
  return [4 /*yield*/, db.collection(collection).find(idLookup.query, findOptions).toArray()];
2613
2829
  case 30:
2614
- fallbackDocs = _r.sent();
2830
+ fallbackDocs = _s.sent();
2615
2831
  if (fallbackDocs.length) {
2616
2832
  documents = fallbackDocs;
2617
2833
  executedQuery = idLookup.query;
2618
2834
  fallbackMeta.idLookup.used = true;
2619
2835
  }
2620
- _r.label = 31;
2836
+ _s.label = 31;
2621
2837
  case 31:
2622
2838
  if (!!documents.length) return [3 /*break*/, 34];
2623
2839
  return [4 /*yield*/, resolveBaseCollectionFromReport(db, dbName, collection)];
2624
2840
  case 32:
2625
- baseCollection = _r.sent();
2841
+ baseCollection = _s.sent();
2626
2842
  if (!(baseCollection && baseCollection !== collection)) return [3 /*break*/, 34];
2627
- fallbackPayload = __assign(__assign({}, input), { collection: baseCollection });
2843
+ addAssistantCollectionToTriedSet(triedCollections, baseCollection);
2844
+ fallbackPayload = __assign(__assign({}, input), { collection: baseCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
2845
+ rootCollection: retryRootCollection
2846
+ }) });
2628
2847
  return [4 /*yield*/, executeAiAssistantMongoRead(fallbackPayload, context)];
2629
2848
  case 33:
2630
- fallbackResult = _r.sent();
2849
+ fallbackResult = _s.sent();
2631
2850
  if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
2632
2851
  if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
2633
2852
  existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
@@ -2644,9 +2863,68 @@ function executeAiAssistantMongoRead(payload, context) {
2644
2863
  if (isSuperAdmin) {
2645
2864
  fallbackMeta.reportFallback = { from: collection, to: baseCollection, attempted: true, used: false };
2646
2865
  }
2647
- _r.label = 34;
2866
+ _s.label = 34;
2648
2867
  case 34:
2649
- if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 51];
2868
+ if (!(!documents.length && crossCollectionRetryEnabled)) return [3 /*break*/, 43];
2869
+ return [4 /*yield*/, resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections)];
2870
+ case 35:
2871
+ crossCollectionCandidates = _s.sent();
2872
+ if (!crossCollectionCandidates.length) return [3 /*break*/, 43];
2873
+ fallbackMeta.collectionRetry = {
2874
+ from: collection,
2875
+ root: retryRootCollection,
2876
+ tried: crossCollectionCandidates,
2877
+ attempted: true,
2878
+ used: false
2879
+ };
2880
+ _s.label = 36;
2881
+ case 36:
2882
+ _s.trys.push([36, 41, 42, 43]);
2883
+ crossCollectionCandidates_1 = __values(crossCollectionCandidates), crossCollectionCandidates_1_1 = crossCollectionCandidates_1.next();
2884
+ _s.label = 37;
2885
+ case 37:
2886
+ if (!!crossCollectionCandidates_1_1.done) return [3 /*break*/, 40];
2887
+ candidateCollection = crossCollectionCandidates_1_1.value;
2888
+ addAssistantCollectionToTriedSet(triedCollections, candidateCollection);
2889
+ fallbackPayload = __assign(__assign({}, input), { collection: candidateCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
2890
+ rootCollection: retryRootCollection,
2891
+ disableCrossCollectionRetry: true
2892
+ }) });
2893
+ return [4 /*yield*/, executeAiAssistantMongoRead(fallbackPayload, context)];
2894
+ case 38:
2895
+ fallbackResult = _s.sent();
2896
+ if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
2897
+ if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
2898
+ existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
2899
+ ? fallbackResult.debug.fallbacks
2900
+ : {};
2901
+ fallbackResult.debug.fallbacks = __assign(__assign({}, existingFallbacks), { collectionRetry: {
2902
+ from: collection,
2903
+ to: candidateCollection,
2904
+ root: retryRootCollection,
2905
+ tried: crossCollectionCandidates,
2906
+ used: true
2907
+ } });
2908
+ }
2909
+ return [2 /*return*/, fallbackResult];
2910
+ }
2911
+ _s.label = 39;
2912
+ case 39:
2913
+ crossCollectionCandidates_1_1 = crossCollectionCandidates_1.next();
2914
+ return [3 /*break*/, 37];
2915
+ case 40: return [3 /*break*/, 43];
2916
+ case 41:
2917
+ e_1_1 = _s.sent();
2918
+ e_1 = { error: e_1_1 };
2919
+ return [3 /*break*/, 43];
2920
+ case 42:
2921
+ try {
2922
+ if (crossCollectionCandidates_1_1 && !crossCollectionCandidates_1_1.done && (_p = crossCollectionCandidates_1.return)) _p.call(crossCollectionCandidates_1);
2923
+ }
2924
+ finally { if (e_1) throw e_1.error; }
2925
+ return [7 /*endfinally*/];
2926
+ case 43:
2927
+ if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 60];
2650
2928
  nameFields = collectMatchFieldsByCondition(executedQuery, function (field, condition) { return isRegexMatchCondition(condition)
2651
2929
  || (typeof condition === 'string' && shouldApplyAssistantNameRegex(field)); });
2652
2930
  dateFields = collectMatchFieldsByCondition(executedQuery, function (_field, condition) { return isDateCondition(condition); });
@@ -2654,36 +2932,36 @@ function executeAiAssistantMongoRead(payload, context) {
2654
2932
  nameFields: nameFields.length ? nameFields : undefined,
2655
2933
  dateFields: dateFields.length ? dateFields : undefined
2656
2934
  };
2657
- _r.label = 35;
2658
- case 35:
2659
- _r.trys.push([35, 40, , 41]);
2660
- if (!nameFields.length) return [3 /*break*/, 37];
2935
+ _s.label = 44;
2936
+ case 44:
2937
+ _s.trys.push([44, 49, , 50]);
2938
+ if (!nameFields.length) return [3 /*break*/, 46];
2661
2939
  queryNoName = stripMatchFields(executedQuery, nameFields);
2662
2940
  _g = diagnostics;
2663
2941
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoName, {
2664
2942
  readPreference: AI_ASSISTANT_READ_PREFERENCE
2665
2943
  })];
2666
- case 36:
2667
- _g.recentCount = _r.sent();
2668
- _r.label = 37;
2669
- case 37:
2670
- if (!dateFields.length) return [3 /*break*/, 39];
2944
+ case 45:
2945
+ _g.recentCount = _s.sent();
2946
+ _s.label = 46;
2947
+ case 46:
2948
+ if (!dateFields.length) return [3 /*break*/, 48];
2671
2949
  queryNoDate = stripMatchFields(executedQuery, dateFields);
2672
2950
  _h = diagnostics;
2673
2951
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoDate, {
2674
2952
  readPreference: AI_ASSISTANT_READ_PREFERENCE
2675
2953
  })];
2676
- case 38:
2677
- _h.nameMatchCount = _r.sent();
2678
- _r.label = 39;
2679
- case 39: return [3 /*break*/, 41];
2680
- case 40:
2681
- _j = _r.sent();
2682
- return [3 /*break*/, 41];
2683
- case 41:
2684
- _r.trys.push([41, 44, , 45]);
2954
+ case 47:
2955
+ _h.nameMatchCount = _s.sent();
2956
+ _s.label = 48;
2957
+ case 48: return [3 /*break*/, 50];
2958
+ case 49:
2959
+ _j = _s.sent();
2960
+ return [3 /*break*/, 50];
2961
+ case 50:
2962
+ _s.trys.push([50, 53, , 54]);
2685
2963
  _k = probeDocs;
2686
- if (_k) return [3 /*break*/, 43];
2964
+ if (_k) return [3 /*break*/, 52];
2687
2965
  return [4 /*yield*/, fetchAssistantProbeDocs({
2688
2966
  db: db,
2689
2967
  collection: collection,
@@ -2692,56 +2970,56 @@ function executeAiAssistantMongoRead(payload, context) {
2692
2970
  isSuperAdmin: isSuperAdmin,
2693
2971
  includeClientScope: shouldScopeByClient
2694
2972
  })];
2695
- case 42:
2696
- _k = (_r.sent());
2697
- _r.label = 43;
2698
- case 43:
2973
+ case 51:
2974
+ _k = (_s.sent());
2975
+ _s.label = 52;
2976
+ case 52:
2699
2977
  probeDocs = _k;
2700
2978
  if (probeDocs.length && nameFields.length) {
2701
2979
  diagnostics.chemicalIdDetected = detectChemicalIdFromProbe(probeDocs, nameFields);
2702
2980
  }
2703
- return [3 /*break*/, 45];
2704
- case 44:
2705
- _l = _r.sent();
2706
- return [3 /*break*/, 45];
2707
- case 45:
2708
- _r.trys.push([45, 49, , 50]);
2981
+ return [3 /*break*/, 54];
2982
+ case 53:
2983
+ _l = _s.sent();
2984
+ return [3 /*break*/, 54];
2985
+ case 54:
2986
+ _s.trys.push([54, 58, , 59]);
2709
2987
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
2710
- case 46:
2711
- allCollections = _r.sent();
2988
+ case 55:
2989
+ allCollections = _s.sent();
2712
2990
  base = stripVersionSuffix(collection.startsWith('report-') ? collection.slice('report-'.length) : collection);
2713
2991
  alt = collection.startsWith('report-') ? base : "report-".concat(base);
2714
- if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 48];
2992
+ if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 57];
2715
2993
  return [4 /*yield*/, db.collection(alt).countDocuments({}, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
2716
- case 47:
2717
- altCount = _r.sent();
2994
+ case 56:
2995
+ altCount = _s.sent();
2718
2996
  diagnostics.alternateCollection = alt;
2719
2997
  diagnostics.alternateCollectionCount = altCount;
2720
- _r.label = 48;
2721
- case 48: return [3 /*break*/, 50];
2722
- case 49:
2723
- _m = _r.sent();
2724
- return [3 /*break*/, 50];
2725
- case 50:
2998
+ _s.label = 57;
2999
+ case 57: return [3 /*break*/, 59];
3000
+ case 58:
3001
+ _m = _s.sent();
3002
+ return [3 /*break*/, 59];
3003
+ case 59:
2726
3004
  fallbackMeta.zeroDiagnostics = diagnostics;
2727
- _r.label = 51;
2728
- case 51:
3005
+ _s.label = 60;
3006
+ case 60:
2729
3007
  total = null;
2730
- if (!normalized.includeTotal) return [3 /*break*/, 53];
3008
+ if (!normalized.includeTotal) return [3 /*break*/, 62];
2731
3009
  return [4 /*yield*/, db.collection(collection).countDocuments(executedQuery, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
2732
- case 52:
2733
- total = _r.sent();
2734
- _r.label = 53;
2735
- case 53:
3010
+ case 61:
3011
+ total = _s.sent();
3012
+ _s.label = 62;
3013
+ case 62:
2736
3014
  sanitizedDocuments = isSuperAdmin
2737
3015
  ? documents
2738
3016
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
2739
3017
  requestedFields = resolveProjectionRequestedFields(findOptions.projection);
2740
- if (!(sanitizedDocuments.length && requestedFields.length)) return [3 /*break*/, 57];
3018
+ if (!(sanitizedDocuments.length && requestedFields.length)) return [3 /*break*/, 66];
2741
3019
  missingFields = requestedFields.filter(function (field) { return !hasNonEmptyValue(sanitizedDocuments, field, { treatObjectLikeAsEmpty: true }); });
2742
- if (!missingFields.length) return [3 /*break*/, 57];
3020
+ if (!missingFields.length) return [3 /*break*/, 66];
2743
3021
  _o = probeDocs;
2744
- if (_o) return [3 /*break*/, 55];
3022
+ if (_o) return [3 /*break*/, 64];
2745
3023
  return [4 /*yield*/, fetchAssistantProbeDocs({
2746
3024
  db: db,
2747
3025
  collection: collection,
@@ -2750,26 +3028,26 @@ function executeAiAssistantMongoRead(payload, context) {
2750
3028
  isSuperAdmin: isSuperAdmin,
2751
3029
  includeClientScope: shouldScopeByClient
2752
3030
  })];
2753
- case 54:
2754
- _o = (_r.sent());
2755
- _r.label = 55;
2756
- case 55:
3031
+ case 63:
3032
+ _o = (_s.sent());
3033
+ _s.label = 64;
3034
+ case 64:
2757
3035
  probeDocs = _o;
2758
- if (!probeDocs.length) return [3 /*break*/, 57];
3036
+ if (!probeDocs.length) return [3 /*break*/, 66];
2759
3037
  projectionAliases = resolveFieldAliases(probeDocs, missingFields, schemaFields);
2760
- if (!Object.keys(projectionAliases).length) return [3 /*break*/, 57];
3038
+ if (!Object.keys(projectionAliases).length) return [3 /*break*/, 66];
2761
3039
  fallbackMeta.projectionAliases = {
2762
3040
  aliases: projectionAliases,
2763
3041
  attempted: true,
2764
3042
  used: false
2765
3043
  };
2766
3044
  expandedProjection = expandProjectionWithAliases(findOptions.projection, projectionAliases);
2767
- if (!(expandedProjection && expandedProjection !== findOptions.projection)) return [3 /*break*/, 57];
3045
+ if (!(expandedProjection && expandedProjection !== findOptions.projection)) return [3 /*break*/, 66];
2768
3046
  findOptions = __assign(__assign({}, findOptions), { projection: expandedProjection });
2769
3047
  normalized.findOptions.projection = expandedProjection;
2770
3048
  return [4 /*yield*/, db.collection(collection).find(executedQuery, findOptions).toArray()];
2771
- case 56:
2772
- refreshedDocs = _r.sent();
3049
+ case 65:
3050
+ refreshedDocs = _s.sent();
2773
3051
  if (refreshedDocs.length) {
2774
3052
  documents = refreshedDocs;
2775
3053
  sanitizedDocuments = isSuperAdmin
@@ -2777,9 +3055,9 @@ function executeAiAssistantMongoRead(payload, context) {
2777
3055
  : refreshedDocs.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
2778
3056
  fallbackMeta.projectionAliases.used = true;
2779
3057
  }
2780
- _r.label = 57;
2781
- case 57:
2782
- includeIds = ((_q = input.options) === null || _q === void 0 ? void 0 : _q.includeIds) === true;
3058
+ _s.label = 66;
3059
+ case 66:
3060
+ includeIds = ((_r = input.options) === null || _r === void 0 ? void 0 : _r.includeIds) === true;
2783
3061
  fieldAliases = resolveFieldAliases(sanitizedDocuments, requestedFields, schemaFields);
2784
3062
  displayDocs = Object.keys(fieldAliases).length
2785
3063
  ? applyFieldAliasesForDisplay(sanitizedDocuments, fieldAliases)
@@ -2793,8 +3071,8 @@ function executeAiAssistantMongoRead(payload, context) {
2793
3071
  idCustomer: customerId,
2794
3072
  isSuperAdmin: isSuperAdmin
2795
3073
  })];
2796
- case 58:
2797
- idLookupDisplay = _r.sent();
3074
+ case 67:
3075
+ idLookupDisplay = _s.sent();
2798
3076
  if (idLookupDisplay === null || idLookupDisplay === void 0 ? void 0 : idLookupDisplay.docs) {
2799
3077
  displayDocs = idLookupDisplay.docs;
2800
3078
  }
@@ -2839,37 +3117,46 @@ function executeAiAssistantMongoRead(payload, context) {
2839
3117
  }
2840
3118
  function executeAiAssistantMongoAggregate(payload, context) {
2841
3119
  return __awaiter(this, void 0, void 0, function () {
2842
- var input, rawCollection, dbName, db, collectionResolution, collection, bridgeCollection, schemaFields, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
3120
+ var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, crossCollectionCandidates, crossCollectionCandidates_2, crossCollectionCandidates_2_1, candidateCollection, fallbackPayload, fallbackResult, existingFallbacks, e_2_1, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
3121
+ var e_2, _o;
2843
3122
  var _this = this;
2844
- var _o, _p;
2845
- return __generator(this, function (_q) {
2846
- switch (_q.label) {
3123
+ var _p, _q;
3124
+ return __generator(this, function (_r) {
3125
+ switch (_r.label) {
2847
3126
  case 0:
2848
3127
  input = payload || {};
2849
3128
  rawCollection = normalizeOptionalString(input.collection);
2850
3129
  if (!rawCollection) {
2851
3130
  throw new Error('AI assistant report builder bridge: Collection is required.');
2852
3131
  }
3132
+ retryState = input.__assistantRetryState && typeof input.__assistantRetryState === 'object'
3133
+ ? input.__assistantRetryState
3134
+ : {};
3135
+ triedCollections = buildAssistantTriedCollectionSet(retryState.triedCollections);
3136
+ addAssistantCollectionToTriedSet(triedCollections, rawCollection);
3137
+ crossCollectionRetryEnabled = retryState.disableCrossCollectionRetry !== true;
2853
3138
  dbName = resolveAssistantDatabaseName(input.database, input.mongo);
2854
3139
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
2855
3140
  return [4 /*yield*/, resolveAssistantCollectionName(db, dbName, rawCollection)];
2856
3141
  case 1:
2857
- collectionResolution = _q.sent();
3142
+ collectionResolution = _r.sent();
2858
3143
  collection = collectionResolution.name || rawCollection;
2859
3144
  return [4 /*yield*/, resolveAssistantReportBuilderBridgeCollection(collection, db, dbName)];
2860
3145
  case 2:
2861
- bridgeCollection = _q.sent();
3146
+ bridgeCollection = _r.sent();
2862
3147
  if (bridgeCollection.fallbackFrom) {
2863
3148
  collection = bridgeCollection.collection;
2864
3149
  }
3150
+ addAssistantCollectionToTriedSet(triedCollections, collection);
3151
+ retryRootCollection = normalizeOptionalString(retryState.rootCollection) || collection;
2865
3152
  schemaFields = getCollectionSchemaFieldNames(collection);
2866
3153
  return [4 /*yield*/, ensureAssistantReadAccess(context, input.permissionView, collection)];
2867
3154
  case 3:
2868
- _a = _q.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
3155
+ _a = _r.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
2869
3156
  if (!isSuperAdmin && AI_ASSISTANT_BLOCKED_COLLECTIONS.has(collection)) {
2870
3157
  throw new Error('AI assistant report builder bridge: Access denied.');
2871
3158
  }
2872
- customerId = normalizeOptionalString((_o = user === null || user === void 0 ? void 0 : user.other) === null || _o === void 0 ? void 0 : _o.id_customer);
3159
+ customerId = normalizeOptionalString((_p = user === null || user === void 0 ? void 0 : user.other) === null || _p === void 0 ? void 0 : _p.id_customer);
2873
3160
  fallbackMeta = {};
2874
3161
  if (bridgeCollection.fallbackFrom) {
2875
3162
  fallbackMeta.reportBuilderBridge = {
@@ -2901,11 +3188,11 @@ function executeAiAssistantMongoAggregate(payload, context) {
2901
3188
  if (!(!isSuperAdmin && normalizedClient)) return [3 /*break*/, 5];
2902
3189
  return [4 /*yield*/, collectionHasClientIndex(db, dbName, collection)];
2903
3190
  case 4:
2904
- _b = _q.sent();
3191
+ _b = _r.sent();
2905
3192
  return [3 /*break*/, 6];
2906
3193
  case 5:
2907
3194
  _b = false;
2908
- _q.label = 6;
3195
+ _r.label = 6;
2909
3196
  case 6:
2910
3197
  shouldScopeByClient = _b;
2911
3198
  clientScopedQuery = shouldScopeByClient
@@ -2933,7 +3220,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
2933
3220
  }
2934
3221
  aggregateOptions = __assign(__assign({}, normalizedOptions.aggregateOptions), { readPreference: AI_ASSISTANT_READ_PREFERENCE });
2935
3222
  runAggregateWithRepair = function (pipeline, stage) { return __awaiter(_this, void 0, void 0, function () {
2936
- var docs, error_4, repaired, docs;
3223
+ var docs, error_5, repaired, docs;
2937
3224
  return __generator(this, function (_a) {
2938
3225
  switch (_a.label) {
2939
3226
  case 0:
@@ -2945,13 +3232,13 @@ function executeAiAssistantMongoAggregate(payload, context) {
2945
3232
  docs = _a.sent();
2946
3233
  return [2 /*return*/, { documents: docs, pipeline: pipeline }];
2947
3234
  case 2:
2948
- error_4 = _a.sent();
2949
- if (!isAssistantDateArithmeticArgumentError(error_4)) {
2950
- throw error_4;
3235
+ error_5 = _a.sent();
3236
+ if (!isAssistantDateArithmeticArgumentError(error_5)) {
3237
+ throw error_5;
2951
3238
  }
2952
3239
  repaired = repairAssistantDateArithmeticInPipeline(pipeline);
2953
3240
  if (!repaired.changed || containsForbiddenMongoOperators(repaired.pipeline)) {
2954
- throw error_4;
3241
+ throw error_5;
2955
3242
  }
2956
3243
  return [4 /*yield*/, db.collection(collection)
2957
3244
  .aggregate(repaired.pipeline, aggregateOptions)
@@ -2971,7 +3258,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
2971
3258
  }); };
2972
3259
  return [4 /*yield*/, runAggregateWithRepair(executedPipeline, 'initial')];
2973
3260
  case 7:
2974
- initialAggregate = _q.sent();
3261
+ initialAggregate = _r.sent();
2975
3262
  documents = initialAggregate.documents;
2976
3263
  executedPipeline = initialAggregate.pipeline;
2977
3264
  dateField = findAggregateDateField(executedPipeline);
@@ -2984,14 +3271,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
2984
3271
  if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 9];
2985
3272
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'date_field_fallback')];
2986
3273
  case 8:
2987
- fallbackAggregate = _q.sent();
3274
+ fallbackAggregate = _r.sent();
2988
3275
  fallbackDocs = fallbackAggregate.documents;
2989
3276
  if (fallbackDocs.length) {
2990
3277
  documents = fallbackDocs;
2991
3278
  executedPipeline = fallbackAggregate.pipeline;
2992
3279
  fallbackMeta.dateField.used = true;
2993
3280
  }
2994
- _q.label = 9;
3281
+ _r.label = 9;
2995
3282
  case 9:
2996
3283
  if (!(!documents.length && dateField !== 'createdAt')) return [3 /*break*/, 11];
2997
3284
  createdFallback = { from: dateField, to: 'createdAt', attempted: true, used: false };
@@ -3000,14 +3287,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3000
3287
  if (!!containsForbiddenMongoOperators(createdPipeline)) return [3 /*break*/, 11];
3001
3288
  return [4 /*yield*/, runAggregateWithRepair(createdPipeline, 'date_field_created_at')];
3002
3289
  case 10:
3003
- createdAggregate = _q.sent();
3290
+ createdAggregate = _r.sent();
3004
3291
  createdDocs = createdAggregate.documents;
3005
3292
  if (createdDocs.length) {
3006
3293
  documents = createdDocs;
3007
3294
  executedPipeline = createdAggregate.pipeline;
3008
3295
  fallbackMeta.dateFieldCreatedAt.used = true;
3009
3296
  }
3010
- _q.label = 11;
3297
+ _r.label = 11;
3011
3298
  case 11:
3012
3299
  if (!!documents.length) return [3 /*break*/, 13];
3013
3300
  expanded = expandAggregateDateMatchFallback(executedPipeline, schemaFields);
@@ -3020,14 +3307,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3020
3307
  if (!!containsForbiddenMongoOperators(expanded.pipeline)) return [3 /*break*/, 13];
3021
3308
  return [4 /*yield*/, runAggregateWithRepair(expanded.pipeline, 'date_fields_expanded')];
3022
3309
  case 12:
3023
- expandedAggregate = _q.sent();
3310
+ expandedAggregate = _r.sent();
3024
3311
  expandedDocs = expandedAggregate.documents;
3025
3312
  if (expandedDocs.length) {
3026
3313
  documents = expandedDocs;
3027
3314
  executedPipeline = expandedAggregate.pipeline;
3028
3315
  fallbackMeta.dateFieldsExpanded.used = true;
3029
3316
  }
3030
- _q.label = 13;
3317
+ _r.label = 13;
3031
3318
  case 13:
3032
3319
  if (!!documents.length) return [3 /*break*/, 17];
3033
3320
  completionFallback = resolveAggregateCompletionFallback(executedPipeline);
@@ -3044,14 +3331,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3044
3331
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 15];
3045
3332
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'completion_add_fields')];
3046
3333
  case 14:
3047
- fallbackAggregate = _q.sent();
3334
+ fallbackAggregate = _r.sent();
3048
3335
  fallbackDocs = fallbackAggregate.documents;
3049
3336
  if (fallbackDocs.length) {
3050
3337
  documents = fallbackDocs;
3051
3338
  executedPipeline = fallbackAggregate.pipeline;
3052
3339
  fallbackMeta.completion.used = true;
3053
3340
  }
3054
- _q.label = 15;
3341
+ _r.label = 15;
3055
3342
  case 15:
3056
3343
  if (!!documents.length) return [3 /*break*/, 17];
3057
3344
  completionExprFallback = resolveAggregateCompletionExprFallback(executedPipeline);
@@ -3068,23 +3355,23 @@ function executeAiAssistantMongoAggregate(payload, context) {
3068
3355
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 17];
3069
3356
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'completion_expr')];
3070
3357
  case 16:
3071
- fallbackAggregate = _q.sent();
3358
+ fallbackAggregate = _r.sent();
3072
3359
  fallbackDocs = fallbackAggregate.documents;
3073
3360
  if (fallbackDocs.length) {
3074
3361
  documents = fallbackDocs;
3075
3362
  executedPipeline = fallbackAggregate.pipeline;
3076
3363
  fallbackMeta.completion.used = true;
3077
3364
  }
3078
- _q.label = 17;
3365
+ _r.label = 17;
3079
3366
  case 17:
3080
3367
  if (!(documents.length <= 1)) return [3 /*break*/, 26];
3081
3368
  unwindFallback = resolveAggregateUnwindFallback(executedPipeline);
3082
3369
  if (!unwindFallback) return [3 /*break*/, 26];
3083
3370
  fallbackMeta.unwind = { path: unwindFallback.path, attempted: true, used: false };
3084
3371
  shouldUnwind = false;
3085
- _q.label = 18;
3372
+ _r.label = 18;
3086
3373
  case 18:
3087
- _q.trys.push([18, 21, , 22]);
3374
+ _r.trys.push([18, 21, , 22]);
3088
3375
  _c = probeDocs;
3089
3376
  if (_c) return [3 /*break*/, 20];
3090
3377
  return [4 /*yield*/, fetchAssistantProbeDocs({
@@ -3096,14 +3383,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3096
3383
  includeClientScope: shouldScopeByClient
3097
3384
  })];
3098
3385
  case 19:
3099
- _c = (_q.sent());
3100
- _q.label = 20;
3386
+ _c = (_r.sent());
3387
+ _r.label = 20;
3101
3388
  case 20:
3102
3389
  probeDocs = _c;
3103
3390
  shouldUnwind = probeDocs.length ? hasArrayValueAtPath(probeDocs, unwindFallback.path) : false;
3104
3391
  return [3 /*break*/, 22];
3105
3392
  case 21:
3106
- _d = _q.sent();
3393
+ _d = _r.sent();
3107
3394
  shouldUnwind = false;
3108
3395
  return [3 /*break*/, 22];
3109
3396
  case 22:
@@ -3112,18 +3399,18 @@ function executeAiAssistantMongoAggregate(payload, context) {
3112
3399
  if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 24];
3113
3400
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'unwind')];
3114
3401
  case 23:
3115
- fallbackAggregate = _q.sent();
3402
+ fallbackAggregate = _r.sent();
3116
3403
  fallbackDocs = fallbackAggregate.documents;
3117
3404
  if (fallbackDocs.length > documents.length) {
3118
3405
  documents = fallbackDocs;
3119
3406
  executedPipeline = fallbackAggregate.pipeline;
3120
3407
  fallbackMeta.unwind.used = true;
3121
3408
  }
3122
- _q.label = 24;
3409
+ _r.label = 24;
3123
3410
  case 24: return [3 /*break*/, 26];
3124
3411
  case 25:
3125
3412
  fallbackMeta.unwind.skipped = 'not_array';
3126
- _q.label = 26;
3413
+ _r.label = 26;
3127
3414
  case 26:
3128
3415
  if (!!documents.length) return [3 /*break*/, 28];
3129
3416
  nameFallback = resolveAggregateNameMatchFallback(executedPipeline);
@@ -3138,14 +3425,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3138
3425
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 28];
3139
3426
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'name_match')];
3140
3427
  case 27:
3141
- fallbackAggregate = _q.sent();
3428
+ fallbackAggregate = _r.sent();
3142
3429
  fallbackDocs = fallbackAggregate.documents;
3143
3430
  if (fallbackDocs.length) {
3144
3431
  documents = fallbackDocs;
3145
3432
  executedPipeline = fallbackAggregate.pipeline;
3146
3433
  fallbackMeta.nameMatch.used = true;
3147
3434
  }
3148
- _q.label = 28;
3435
+ _r.label = 28;
3149
3436
  case 28:
3150
3437
  if (!!documents.length) return [3 /*break*/, 34];
3151
3438
  _e = probeDocs;
@@ -3159,14 +3446,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3159
3446
  includeClientScope: shouldScopeByClient
3160
3447
  })];
3161
3448
  case 29:
3162
- _e = (_q.sent());
3163
- _q.label = 30;
3449
+ _e = (_r.sent());
3450
+ _r.label = 30;
3164
3451
  case 30:
3165
3452
  probeDocs = _e;
3166
3453
  _loop_1 = function (i) {
3167
3454
  var stage, chemicalLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3168
- return __generator(this, function (_r) {
3169
- switch (_r.label) {
3455
+ return __generator(this, function (_s) {
3456
+ switch (_s.label) {
3170
3457
  case 0:
3171
3458
  stage = executedPipeline[i];
3172
3459
  if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
@@ -3182,7 +3469,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3182
3469
  probeDocs: probeDocs || undefined
3183
3470
  })];
3184
3471
  case 1:
3185
- chemicalLookup = _r.sent();
3472
+ chemicalLookup = _s.sent();
3186
3473
  if (!chemicalLookup) {
3187
3474
  return [2 /*return*/, "continue"];
3188
3475
  }
@@ -3191,7 +3478,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3191
3478
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 3];
3192
3479
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'chemical_lookup')];
3193
3480
  case 2:
3194
- fallbackAggregate = _r.sent();
3481
+ fallbackAggregate = _s.sent();
3195
3482
  fallbackDocs = fallbackAggregate.documents;
3196
3483
  if (fallbackDocs.length) {
3197
3484
  documents = fallbackDocs;
@@ -3199,21 +3486,21 @@ function executeAiAssistantMongoAggregate(payload, context) {
3199
3486
  fallbackMeta.chemicalLookup.used = true;
3200
3487
  return [2 /*return*/, "break"];
3201
3488
  }
3202
- _r.label = 3;
3489
+ _s.label = 3;
3203
3490
  case 3: return [2 /*return*/];
3204
3491
  }
3205
3492
  });
3206
3493
  };
3207
3494
  i = 0;
3208
- _q.label = 31;
3495
+ _r.label = 31;
3209
3496
  case 31:
3210
3497
  if (!(i < (executedPipeline || []).length)) return [3 /*break*/, 34];
3211
3498
  return [5 /*yield**/, _loop_1(i)];
3212
3499
  case 32:
3213
- state_1 = _q.sent();
3500
+ state_1 = _r.sent();
3214
3501
  if (state_1 === "break")
3215
3502
  return [3 /*break*/, 34];
3216
- _q.label = 33;
3503
+ _r.label = 33;
3217
3504
  case 33:
3218
3505
  i += 1;
3219
3506
  return [3 /*break*/, 31];
@@ -3239,8 +3526,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
3239
3526
  includeClientScope: shouldScopeByClient
3240
3527
  })];
3241
3528
  case 35:
3242
- _f = (_q.sent());
3243
- _q.label = 36;
3529
+ _f = (_r.sent());
3530
+ _r.label = 36;
3244
3531
  case 36:
3245
3532
  probeDocs = _f;
3246
3533
  if (!probeDocs.length) return [3 /*break*/, 38];
@@ -3259,27 +3546,27 @@ function executeAiAssistantMongoAggregate(payload, context) {
3259
3546
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 38];
3260
3547
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'query_field_aliases')];
3261
3548
  case 37:
3262
- fallbackAggregate = _q.sent();
3549
+ fallbackAggregate = _r.sent();
3263
3550
  fallbackDocs = fallbackAggregate.documents;
3264
3551
  if (fallbackDocs.length) {
3265
3552
  documents = fallbackDocs;
3266
3553
  executedPipeline = fallbackAggregate.pipeline;
3267
3554
  fallbackMeta.queryFieldAliases.used = true;
3268
3555
  }
3269
- _q.label = 38;
3556
+ _r.label = 38;
3270
3557
  case 38:
3271
3558
  if (!!documents.length) return [3 /*break*/, 42];
3272
3559
  _loop_2 = function (i) {
3273
- var stage, _s, idLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3274
- return __generator(this, function (_t) {
3275
- switch (_t.label) {
3560
+ var stage, _t, idLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3561
+ return __generator(this, function (_u) {
3562
+ switch (_u.label) {
3276
3563
  case 0:
3277
3564
  stage = executedPipeline[i];
3278
3565
  if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
3279
3566
  return [2 /*return*/, "continue"];
3280
3567
  }
3281
- _s = probeDocs;
3282
- if (_s) return [3 /*break*/, 2];
3568
+ _t = probeDocs;
3569
+ if (_t) return [3 /*break*/, 2];
3283
3570
  return [4 /*yield*/, fetchAssistantProbeDocs({
3284
3571
  db: db,
3285
3572
  collection: collection,
@@ -3289,10 +3576,10 @@ function executeAiAssistantMongoAggregate(payload, context) {
3289
3576
  includeClientScope: shouldScopeByClient
3290
3577
  })];
3291
3578
  case 1:
3292
- _s = (_t.sent());
3293
- _t.label = 2;
3579
+ _t = (_u.sent());
3580
+ _u.label = 2;
3294
3581
  case 2:
3295
- probeDocs = _s;
3582
+ probeDocs = _t;
3296
3583
  return [4 /*yield*/, applyIdLookupFallbackToQuery({
3297
3584
  query: stage.$match,
3298
3585
  db: db,
@@ -3303,7 +3590,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3303
3590
  probeDocs: probeDocs || undefined
3304
3591
  })];
3305
3592
  case 3:
3306
- idLookup = _t.sent();
3593
+ idLookup = _u.sent();
3307
3594
  if (!idLookup) {
3308
3595
  return [2 /*return*/, "continue"];
3309
3596
  }
@@ -3312,7 +3599,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3312
3599
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 5];
3313
3600
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'id_lookup')];
3314
3601
  case 4:
3315
- fallbackAggregate = _t.sent();
3602
+ fallbackAggregate = _u.sent();
3316
3603
  fallbackDocs = fallbackAggregate.documents;
3317
3604
  if (fallbackDocs.length) {
3318
3605
  documents = fallbackDocs;
@@ -3320,21 +3607,21 @@ function executeAiAssistantMongoAggregate(payload, context) {
3320
3607
  fallbackMeta.idLookup.used = true;
3321
3608
  return [2 /*return*/, "break"];
3322
3609
  }
3323
- _t.label = 5;
3610
+ _u.label = 5;
3324
3611
  case 5: return [2 /*return*/];
3325
3612
  }
3326
3613
  });
3327
3614
  };
3328
3615
  i = 0;
3329
- _q.label = 39;
3616
+ _r.label = 39;
3330
3617
  case 39:
3331
3618
  if (!(i < (executedPipeline || []).length)) return [3 /*break*/, 42];
3332
3619
  return [5 /*yield**/, _loop_2(i)];
3333
3620
  case 40:
3334
- state_2 = _q.sent();
3621
+ state_2 = _r.sent();
3335
3622
  if (state_2 === "break")
3336
3623
  return [3 /*break*/, 42];
3337
- _q.label = 41;
3624
+ _r.label = 41;
3338
3625
  case 41:
3339
3626
  i += 1;
3340
3627
  return [3 /*break*/, 39];
@@ -3342,12 +3629,15 @@ function executeAiAssistantMongoAggregate(payload, context) {
3342
3629
  if (!!documents.length) return [3 /*break*/, 45];
3343
3630
  return [4 /*yield*/, resolveBaseCollectionFromReport(db, dbName, collection)];
3344
3631
  case 43:
3345
- baseCollection = _q.sent();
3632
+ baseCollection = _r.sent();
3346
3633
  if (!(baseCollection && baseCollection !== collection)) return [3 /*break*/, 45];
3347
- fallbackPayload = __assign(__assign({}, input), { collection: baseCollection });
3634
+ addAssistantCollectionToTriedSet(triedCollections, baseCollection);
3635
+ fallbackPayload = __assign(__assign({}, input), { collection: baseCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
3636
+ rootCollection: retryRootCollection
3637
+ }) });
3348
3638
  return [4 /*yield*/, executeAiAssistantMongoAggregate(fallbackPayload, context)];
3349
3639
  case 44:
3350
- fallbackResult = _q.sent();
3640
+ fallbackResult = _r.sent();
3351
3641
  if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
3352
3642
  if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
3353
3643
  existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
@@ -3364,48 +3654,107 @@ function executeAiAssistantMongoAggregate(payload, context) {
3364
3654
  if (isSuperAdmin) {
3365
3655
  fallbackMeta.reportFallback = { from: collection, to: baseCollection, attempted: true, used: false };
3366
3656
  }
3367
- _q.label = 45;
3657
+ _r.label = 45;
3368
3658
  case 45:
3369
- if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 62];
3659
+ if (!(!documents.length && crossCollectionRetryEnabled)) return [3 /*break*/, 54];
3660
+ return [4 /*yield*/, resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections)];
3661
+ case 46:
3662
+ crossCollectionCandidates = _r.sent();
3663
+ if (!crossCollectionCandidates.length) return [3 /*break*/, 54];
3664
+ fallbackMeta.collectionRetry = {
3665
+ from: collection,
3666
+ root: retryRootCollection,
3667
+ tried: crossCollectionCandidates,
3668
+ attempted: true,
3669
+ used: false
3670
+ };
3671
+ _r.label = 47;
3672
+ case 47:
3673
+ _r.trys.push([47, 52, 53, 54]);
3674
+ crossCollectionCandidates_2 = __values(crossCollectionCandidates), crossCollectionCandidates_2_1 = crossCollectionCandidates_2.next();
3675
+ _r.label = 48;
3676
+ case 48:
3677
+ if (!!crossCollectionCandidates_2_1.done) return [3 /*break*/, 51];
3678
+ candidateCollection = crossCollectionCandidates_2_1.value;
3679
+ addAssistantCollectionToTriedSet(triedCollections, candidateCollection);
3680
+ fallbackPayload = __assign(__assign({}, input), { collection: candidateCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
3681
+ rootCollection: retryRootCollection,
3682
+ disableCrossCollectionRetry: true
3683
+ }) });
3684
+ return [4 /*yield*/, executeAiAssistantMongoAggregate(fallbackPayload, context)];
3685
+ case 49:
3686
+ fallbackResult = _r.sent();
3687
+ if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
3688
+ if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
3689
+ existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
3690
+ ? fallbackResult.debug.fallbacks
3691
+ : {};
3692
+ fallbackResult.debug.fallbacks = __assign(__assign({}, existingFallbacks), { collectionRetry: {
3693
+ from: collection,
3694
+ to: candidateCollection,
3695
+ root: retryRootCollection,
3696
+ tried: crossCollectionCandidates,
3697
+ used: true
3698
+ } });
3699
+ }
3700
+ return [2 /*return*/, fallbackResult];
3701
+ }
3702
+ _r.label = 50;
3703
+ case 50:
3704
+ crossCollectionCandidates_2_1 = crossCollectionCandidates_2.next();
3705
+ return [3 /*break*/, 48];
3706
+ case 51: return [3 /*break*/, 54];
3707
+ case 52:
3708
+ e_2_1 = _r.sent();
3709
+ e_2 = { error: e_2_1 };
3710
+ return [3 /*break*/, 54];
3711
+ case 53:
3712
+ try {
3713
+ if (crossCollectionCandidates_2_1 && !crossCollectionCandidates_2_1.done && (_o = crossCollectionCandidates_2.return)) _o.call(crossCollectionCandidates_2);
3714
+ }
3715
+ finally { if (e_2) throw e_2.error; }
3716
+ return [7 /*endfinally*/];
3717
+ case 54:
3718
+ if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 71];
3370
3719
  matchStages = (executedPipeline || []).filter(function (stage) { return stage && typeof stage === 'object' && stage.$match && typeof stage.$match === 'object'; });
3371
3720
  diagnostics = {};
3372
- if (!matchStages.length) return [3 /*break*/, 62];
3721
+ if (!matchStages.length) return [3 /*break*/, 71];
3373
3722
  combinedMatch = matchStages.reduce(function (acc, stage) { return ({ $and: __spreadArray(__spreadArray([], __read((acc.$and || [])), false), [stage.$match], false) }); }, { $and: [] });
3374
3723
  nameFields = collectMatchFieldsByCondition(combinedMatch, function (field, condition) { return isRegexMatchCondition(condition)
3375
3724
  || (typeof condition === 'string' && shouldApplyAssistantNameRegex(field)); });
3376
3725
  dateFields = collectMatchFieldsByCondition(combinedMatch, function (_field, condition) { return isDateCondition(condition); });
3377
3726
  diagnostics.nameFields = nameFields.length ? nameFields : undefined;
3378
3727
  diagnostics.dateFields = dateFields.length ? dateFields : undefined;
3379
- _q.label = 46;
3380
- case 46:
3381
- _q.trys.push([46, 51, , 52]);
3382
- if (!nameFields.length) return [3 /*break*/, 48];
3728
+ _r.label = 55;
3729
+ case 55:
3730
+ _r.trys.push([55, 60, , 61]);
3731
+ if (!nameFields.length) return [3 /*break*/, 57];
3383
3732
  queryNoName = stripMatchFields(combinedMatch, nameFields);
3384
3733
  _g = diagnostics;
3385
3734
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoName, {
3386
3735
  readPreference: AI_ASSISTANT_READ_PREFERENCE
3387
3736
  })];
3388
- case 47:
3389
- _g.recentCount = _q.sent();
3390
- _q.label = 48;
3391
- case 48:
3392
- if (!dateFields.length) return [3 /*break*/, 50];
3737
+ case 56:
3738
+ _g.recentCount = _r.sent();
3739
+ _r.label = 57;
3740
+ case 57:
3741
+ if (!dateFields.length) return [3 /*break*/, 59];
3393
3742
  queryNoDate = stripMatchFields(combinedMatch, dateFields);
3394
3743
  _h = diagnostics;
3395
3744
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoDate, {
3396
3745
  readPreference: AI_ASSISTANT_READ_PREFERENCE
3397
3746
  })];
3398
- case 49:
3399
- _h.nameMatchCount = _q.sent();
3400
- _q.label = 50;
3401
- case 50: return [3 /*break*/, 52];
3402
- case 51:
3403
- _j = _q.sent();
3404
- return [3 /*break*/, 52];
3405
- case 52:
3406
- _q.trys.push([52, 55, , 56]);
3747
+ case 58:
3748
+ _h.nameMatchCount = _r.sent();
3749
+ _r.label = 59;
3750
+ case 59: return [3 /*break*/, 61];
3751
+ case 60:
3752
+ _j = _r.sent();
3753
+ return [3 /*break*/, 61];
3754
+ case 61:
3755
+ _r.trys.push([61, 64, , 65]);
3407
3756
  _k = probeDocs;
3408
- if (_k) return [3 /*break*/, 54];
3757
+ if (_k) return [3 /*break*/, 63];
3409
3758
  return [4 /*yield*/, fetchAssistantProbeDocs({
3410
3759
  db: db,
3411
3760
  collection: collection,
@@ -3414,52 +3763,52 @@ function executeAiAssistantMongoAggregate(payload, context) {
3414
3763
  isSuperAdmin: isSuperAdmin,
3415
3764
  includeClientScope: shouldScopeByClient
3416
3765
  })];
3417
- case 53:
3418
- _k = (_q.sent());
3419
- _q.label = 54;
3420
- case 54:
3766
+ case 62:
3767
+ _k = (_r.sent());
3768
+ _r.label = 63;
3769
+ case 63:
3421
3770
  probeDocs = _k;
3422
3771
  if (probeDocs.length && nameFields.length) {
3423
3772
  diagnostics.chemicalIdDetected = detectChemicalIdFromProbe(probeDocs, nameFields);
3424
3773
  }
3425
- return [3 /*break*/, 56];
3426
- case 55:
3427
- _l = _q.sent();
3428
- return [3 /*break*/, 56];
3429
- case 56:
3430
- _q.trys.push([56, 60, , 61]);
3774
+ return [3 /*break*/, 65];
3775
+ case 64:
3776
+ _l = _r.sent();
3777
+ return [3 /*break*/, 65];
3778
+ case 65:
3779
+ _r.trys.push([65, 69, , 70]);
3431
3780
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
3432
- case 57:
3433
- allCollections = _q.sent();
3781
+ case 66:
3782
+ allCollections = _r.sent();
3434
3783
  base = stripVersionSuffix(collection.startsWith('report-') ? collection.slice('report-'.length) : collection);
3435
3784
  alt = collection.startsWith('report-') ? base : "report-".concat(base);
3436
- if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 59];
3785
+ if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 68];
3437
3786
  return [4 /*yield*/, db.collection(alt).countDocuments({}, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
3438
- case 58:
3439
- altCount = _q.sent();
3787
+ case 67:
3788
+ altCount = _r.sent();
3440
3789
  diagnostics.alternateCollection = alt;
3441
3790
  diagnostics.alternateCollectionCount = altCount;
3442
- _q.label = 59;
3443
- case 59: return [3 /*break*/, 61];
3444
- case 60:
3445
- _m = _q.sent();
3446
- return [3 /*break*/, 61];
3447
- case 61:
3791
+ _r.label = 68;
3792
+ case 68: return [3 /*break*/, 70];
3793
+ case 69:
3794
+ _m = _r.sent();
3795
+ return [3 /*break*/, 70];
3796
+ case 70:
3448
3797
  fallbackMeta.zeroDiagnostics = diagnostics;
3449
- _q.label = 62;
3450
- case 62: return [4 /*yield*/, verifyAssistantAggregateReliability({
3798
+ _r.label = 71;
3799
+ case 71: return [4 /*yield*/, verifyAssistantAggregateReliability({
3451
3800
  db: db,
3452
3801
  collection: collection,
3453
3802
  pipeline: executedPipeline,
3454
3803
  documents: documents,
3455
3804
  aggregateOptions: aggregateOptions
3456
3805
  })];
3457
- case 63:
3458
- verification = _q.sent();
3806
+ case 72:
3807
+ verification = _r.sent();
3459
3808
  sanitizedDocuments = isSuperAdmin
3460
3809
  ? documents
3461
3810
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
3462
- includeIds = ((_p = input.options) === null || _p === void 0 ? void 0 : _p.includeIds) === true;
3811
+ includeIds = ((_q = input.options) === null || _q === void 0 ? void 0 : _q.includeIds) === true;
3463
3812
  displayDocs = sanitizedDocuments.map(function (doc) { return flattenForTable(doc, {
3464
3813
  includeGroupFromId: true,
3465
3814
  includeIds: true
@@ -3473,8 +3822,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
3473
3822
  idCustomer: customerId,
3474
3823
  isSuperAdmin: isSuperAdmin
3475
3824
  })];
3476
- case 64:
3477
- idLookupDisplay = _q.sent();
3825
+ case 73:
3826
+ idLookupDisplay = _r.sent();
3478
3827
  if (idLookupDisplay === null || idLookupDisplay === void 0 ? void 0 : idLookupDisplay.docs) {
3479
3828
  displayDocs = idLookupDisplay.docs;
3480
3829
  }
@@ -4208,7 +4557,8 @@ function resolveAssistantRevenueByTimeRequest(text, scope) {
4208
4557
  if (!/\b(revenue|invoice)\b/.test(normalized)) {
4209
4558
  return null;
4210
4559
  }
4211
- var byCustomer = /\bby\s+each\s+customer\b/.test(normalized) || /\bby\s+customer\b/.test(normalized);
4560
+ var byCustomer = /\b(?:by|per)\s+(?:each\s+)?(?:customer|client|account)s?\b/.test(normalized)
4561
+ || /\bfor\s+each\s+(?:customer|client|account)\b/.test(normalized);
4212
4562
  if (scope === 'overall' && byCustomer) {
4213
4563
  return null;
4214
4564
  }
@@ -4216,19 +4566,19 @@ function resolveAssistantRevenueByTimeRequest(text, scope) {
4216
4566
  return null;
4217
4567
  }
4218
4568
  var grain = null;
4219
- if (/\bby\s+day\b|\bdaily\b/.test(normalized)) {
4569
+ if (/\b(?:by|per)\s+day\b|\bdaily\b/.test(normalized)) {
4220
4570
  grain = 'day';
4221
4571
  }
4222
- else if (/\bby\s+week\b|\bweekly\b/.test(normalized)) {
4572
+ else if (/\b(?:by|per)\s+week\b|\bweekly\b/.test(normalized)) {
4223
4573
  grain = 'week';
4224
4574
  }
4225
- else if (/\bby\s+month\b|\bmonthly\b/.test(normalized)) {
4575
+ else if (/\b(?:by|per)\s+month\b|\bmonthly\b/.test(normalized)) {
4226
4576
  grain = 'month';
4227
4577
  }
4228
- else if (/\bby\s+quarter\b|\bquarterly\b/.test(normalized)) {
4578
+ else if (/\b(?:by|per)\s+quarter\b|\bquarterly\b/.test(normalized)) {
4229
4579
  grain = 'quarter';
4230
4580
  }
4231
- else if (/\bby\s+year\b|\byearly\b|\bannually\b/.test(normalized)) {
4581
+ else if (/\b(?:by|per)\s+year\b|\byearly\b|\bannually\b/.test(normalized)) {
4232
4582
  grain = 'year';
4233
4583
  }
4234
4584
  if (!grain) {
@@ -4427,10 +4777,21 @@ function isAssistantInvoiceTopCustomersHeuristicDirective(directive) {
4427
4777
  var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4428
4778
  return rawLine.includes('heuristic_agg(invoice-top-customers)');
4429
4779
  }
4780
+ function isAssistantOperationalHeuristicDirective(directive) {
4781
+ var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4782
+ return rawLine.includes('heuristic_agg(work-order-status)')
4783
+ || rawLine.includes('heuristic_agg(work-order-completed-per-day)')
4784
+ || rawLine.includes('heuristic_agg(work-order-top-customers)')
4785
+ || rawLine.includes('heuristic_agg(blend-last10-summary)')
4786
+ || rawLine.includes('heuristic_agg(blend-throughput-by-day)')
4787
+ || rawLine.includes('heuristic_agg(deliveries-per-driver-last-month)')
4788
+ || rawLine.includes('heuristic_agg(last-deliveries)');
4789
+ }
4430
4790
  function isAssistantDeterministicHeuristicDirective(directive) {
4431
4791
  return isAssistantRevenueByTimeHeuristicDirective(directive)
4432
4792
  || isAssistantActiveClientsHeuristicDirective(directive)
4433
4793
  || isAssistantInvoiceTopCustomersHeuristicDirective(directive)
4794
+ || isAssistantOperationalHeuristicDirective(directive)
4434
4795
  || isAssistantBlendRedUltraLiftHeuristicDirective(directive);
4435
4796
  }
4436
4797
  function buildAssistantHeuristicDirective(message, collectionHints) {
@@ -4508,12 +4869,14 @@ function buildAssistantHeuristicDirective(message, collectionHints) {
4508
4869
  rawLine: "HEURISTIC_AGG(invoice-revenue-time-".concat(revenueByTime.grain, ")")
4509
4870
  };
4510
4871
  }
4511
- if (/(last\s+20).*(work[\s-]*orders?).*(group(ed)?\s+by\s+status)/.test(text)) {
4872
+ if (/\b(last|latest|recent)\s+20\b/.test(text)
4873
+ && /\bwork[\s-]*orders?\b/.test(text)
4874
+ && /\b(group(ed)?\s+by|by|per)\s+status\b/.test(text)) {
4512
4875
  return {
4513
4876
  type: 'aggregate',
4514
4877
  payload: {
4515
4878
  collection: 'work-order-dynamics',
4516
- permissionView: '/work-order/list',
4879
+ permissionView: '/work-order-dynamic/list',
4517
4880
  pipeline: [
4518
4881
  {
4519
4882
  $addFields: {
@@ -4550,6 +4913,205 @@ function buildAssistantHeuristicDirective(message, collectionHints) {
4550
4913
  rawLine: 'HEURISTIC_AGG(work-order-status)'
4551
4914
  };
4552
4915
  }
4916
+ if (/\bwork[\s-]*orders?\b/.test(text)
4917
+ && /\b(completed|complete)\b/.test(text)
4918
+ && /\b(per|by)\s+day\b/.test(text)
4919
+ && /\b(last|past)\s+30\s+days?\b/.test(text)) {
4920
+ return {
4921
+ type: 'aggregate',
4922
+ payload: {
4923
+ collection: 'work-order-dynamics',
4924
+ permissionView: '/work-order-dynamic/list',
4925
+ pipeline: [
4926
+ {
4927
+ $match: {
4928
+ date_completed: {
4929
+ $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 30 } },
4930
+ $lt: '$$NOW'
4931
+ }
4932
+ }
4933
+ },
4934
+ {
4935
+ $group: {
4936
+ _id: {
4937
+ $dateToString: {
4938
+ format: '%Y-%m-%d',
4939
+ date: '$date_completed',
4940
+ timezone: 'UTC'
4941
+ }
4942
+ },
4943
+ completed_work_orders: { $sum: 1 }
4944
+ }
4945
+ },
4946
+ { $sort: { _id: 1 } },
4947
+ {
4948
+ $project: {
4949
+ _id: 0,
4950
+ day_utc: '$_id',
4951
+ completed_work_orders: 1
4952
+ }
4953
+ }
4954
+ ]
4955
+ },
4956
+ cleaned: '',
4957
+ rawLine: 'HEURISTIC_AGG(work-order-completed-per-day)'
4958
+ };
4959
+ }
4960
+ if (/\btop\s+10\b/.test(text)
4961
+ && /\bcustomers?\b/.test(text)
4962
+ && /\bwork[\s-]*orders?\b/.test(text)
4963
+ && /\b(last|past)\s+6\s+months?\b/.test(text)) {
4964
+ return {
4965
+ type: 'aggregate',
4966
+ payload: {
4967
+ collection: 'work-order-dynamics',
4968
+ permissionView: '/work-order-dynamic/list',
4969
+ pipeline: [
4970
+ {
4971
+ $match: {
4972
+ date_created: {
4973
+ $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'month', amount: 6 } },
4974
+ $lt: '$$NOW'
4975
+ }
4976
+ }
4977
+ },
4978
+ {
4979
+ $group: {
4980
+ _id: { $ifNull: ['$customer', 'Unknown'] },
4981
+ work_order_count: { $sum: 1 }
4982
+ }
4983
+ },
4984
+ { $sort: { work_order_count: -1, _id: 1 } },
4985
+ { $limit: 10 },
4986
+ {
4987
+ $project: {
4988
+ _id: 0,
4989
+ customer: '$_id',
4990
+ work_order_count: 1
4991
+ }
4992
+ }
4993
+ ]
4994
+ },
4995
+ cleaned: '',
4996
+ rawLine: 'HEURISTIC_AGG(work-order-top-customers)'
4997
+ };
4998
+ }
4999
+ if (/\bblend(?:ing)?\b/.test(text)
5000
+ && /\b(last\s+10)\b/.test(text)
5001
+ && /\b(summarize|summary)\b/.test(text)
5002
+ && /\btickets?\b/.test(text)) {
5003
+ return {
5004
+ type: 'aggregate',
5005
+ payload: {
5006
+ collection: 'chemical-blends',
5007
+ permissionView: '/report-builder/list',
5008
+ pipeline: [
5009
+ { $sort: { date: -1, createdAt: -1, _id: -1 } },
5010
+ { $limit: 10 },
5011
+ {
5012
+ $project: {
5013
+ _id: 0,
5014
+ product: buildAssistantTrimmedStringExpr({ $ifNull: ['$blend_name', '$chemical'] }),
5015
+ total_volume: { $ifNull: ['$chemical_recipe_quantity', 0] },
5016
+ volume_unit: buildAssistantTrimmedStringExpr({
5017
+ $cond: [{ $eq: ['$blend_in_pounds', true] }, 'lb', 'gal']
5018
+ }),
5019
+ created_date: { $ifNull: ['$date', '$createdAt'] },
5020
+ batch_number: buildAssistantTrimmedStringExpr('$batch_number')
5021
+ }
5022
+ }
5023
+ ]
5024
+ },
5025
+ cleaned: '',
5026
+ rawLine: 'HEURISTIC_AGG(blend-last10-summary)'
5027
+ };
5028
+ }
5029
+ if (/\bblend(?:ing)?\b/.test(text)
5030
+ && /\bthroughput\b/.test(text)
5031
+ && /\b(per|by)\s+day\b/.test(text)
5032
+ && /\b(last|past)\s+2\s+weeks?\b/.test(text)) {
5033
+ return {
5034
+ type: 'aggregate',
5035
+ payload: {
5036
+ collection: 'chemical-blends',
5037
+ permissionView: '/report-builder/list',
5038
+ pipeline: [
5039
+ {
5040
+ $match: {
5041
+ date: {
5042
+ $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 14 } },
5043
+ $lt: '$$NOW'
5044
+ }
5045
+ }
5046
+ },
5047
+ {
5048
+ $group: {
5049
+ _id: {
5050
+ $dateToString: {
5051
+ format: '%Y-%m-%d',
5052
+ date: '$date',
5053
+ timezone: 'UTC'
5054
+ }
5055
+ },
5056
+ blend_count: { $sum: 1 },
5057
+ total_volume: { $sum: { $ifNull: ['$chemical_recipe_quantity', 0] } }
5058
+ }
5059
+ },
5060
+ { $sort: { _id: 1 } },
5061
+ {
5062
+ $project: {
5063
+ _id: 0,
5064
+ day_utc: '$_id',
5065
+ blend_count: 1,
5066
+ total_volume: 1
5067
+ }
5068
+ }
5069
+ ]
5070
+ },
5071
+ cleaned: '',
5072
+ rawLine: 'HEURISTIC_AGG(blend-throughput-by-day)'
5073
+ };
5074
+ }
5075
+ if (/\bdeliver(?:y|ies)\b/.test(text)
5076
+ && /\bdrivers?\b/.test(text)
5077
+ && /\blast\s+month\b/.test(text)) {
5078
+ var thisMonthStart = { $dateTrunc: { date: '$$NOW', unit: 'month' } };
5079
+ return {
5080
+ type: 'aggregate',
5081
+ payload: {
5082
+ collection: 'work-order-dynamics',
5083
+ permissionView: '/work-order-dynamic/list',
5084
+ pipeline: [
5085
+ {
5086
+ $match: {
5087
+ date_completed: {
5088
+ $gte: { $dateSubtract: { startDate: thisMonthStart, unit: 'month', amount: 1 } },
5089
+ $lt: thisMonthStart
5090
+ },
5091
+ status: { $in: ['Completed', 'Closed'] }
5092
+ }
5093
+ },
5094
+ { $unwind: { path: '$drivers', preserveNullAndEmptyArrays: true } },
5095
+ {
5096
+ $group: {
5097
+ _id: { $ifNull: ['$drivers.user', 'Unassigned'] },
5098
+ delivery_count: { $sum: 1 }
5099
+ }
5100
+ },
5101
+ { $sort: { delivery_count: -1, _id: 1 } },
5102
+ {
5103
+ $project: {
5104
+ _id: 0,
5105
+ driver: '$_id',
5106
+ delivery_count: 1
5107
+ }
5108
+ }
5109
+ ]
5110
+ },
5111
+ cleaned: '',
5112
+ rawLine: 'HEURISTIC_AGG(deliveries-per-driver-last-month)'
5113
+ };
5114
+ }
4553
5115
  if (/(which\s+blends?|blends?\s+used).*(red\s+ultra\s+lift|chemical\s+red\s+ultra\s+lift)/.test(text)
4554
5116
  && /(last|past)\s+30\s+days/.test(text)) {
4555
5117
  return {
@@ -4701,7 +5263,7 @@ function buildAssistantHeuristicDirective(message, collectionHints) {
4701
5263
  type: 'aggregate',
4702
5264
  payload: {
4703
5265
  collection: 'work-order-dynamics',
4704
- permissionView: '/work-order/list',
5266
+ permissionView: '/work-order-dynamic/list',
4705
5267
  pipeline: [
4706
5268
  {
4707
5269
  $match: {
@@ -4784,6 +5346,9 @@ function resolveDefaultAssistantPermissionView(collection) {
4784
5346
  if (base.startsWith('employee')) {
4785
5347
  return '/employee/list';
4786
5348
  }
5349
+ if (base.startsWith('support-ticket') || base.startsWith('supportticket')) {
5350
+ return '/support-ticket/list';
5351
+ }
4787
5352
  return '/report-builder';
4788
5353
  }
4789
5354
  function normalizeAssistantPermissionView(permissionView, collection) {
@@ -4864,7 +5429,7 @@ function ensureAssistantDisplayColumns(display, requestedColumns) {
4864
5429
  return __assign(__assign({}, display), { columns: columns, rows: rows });
4865
5430
  }
4866
5431
  function resolveAssistantPipelineTimeGrain(pipeline) {
4867
- var e_1, _a;
5432
+ var e_3, _a;
4868
5433
  if (!Array.isArray(pipeline) || !pipeline.length) {
4869
5434
  return null;
4870
5435
  }
@@ -4926,12 +5491,12 @@ function resolveAssistantPipelineTimeGrain(pipeline) {
4926
5491
  }
4927
5492
  }
4928
5493
  }
4929
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5494
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
4930
5495
  finally {
4931
5496
  try {
4932
5497
  if (priority_1_1 && !priority_1_1.done && (_a = priority_1.return)) _a.call(priority_1);
4933
5498
  }
4934
- finally { if (e_1) throw e_1.error; }
5499
+ finally { if (e_3) throw e_3.error; }
4935
5500
  }
4936
5501
  return null;
4937
5502
  }
@@ -5634,7 +6199,7 @@ function applyAssistantDatedReportWindow(value, toolResult) {
5634
6199
  return "".concat(line, "\n\n").concat(content).trim();
5635
6200
  }
5636
6201
  function resolveAssistantDatedReportWindow(toolResult) {
5637
- var e_2, _a;
6202
+ var e_4, _a;
5638
6203
  var _b, _c, _d, _e, _f, _g, _h, _j;
5639
6204
  var verificationWindow = (_d = (_c = (_b = toolResult === null || toolResult === void 0 ? void 0 : toolResult.output) === null || _b === void 0 ? void 0 : _b.verification) === null || _c === void 0 ? void 0 : _c.metrics) === null || _d === void 0 ? void 0 : _d.window;
5640
6205
  var verificationStart = normalizeOptionalString(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.startDate);
@@ -5700,17 +6265,17 @@ function resolveAssistantDatedReportWindow(toolResult) {
5700
6265
  };
5701
6266
  }
5702
6267
  }
5703
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
6268
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
5704
6269
  finally {
5705
6270
  try {
5706
6271
  if (pipelineCandidates_1_1 && !pipelineCandidates_1_1.done && (_a = pipelineCandidates_1.return)) _a.call(pipelineCandidates_1);
5707
6272
  }
5708
- finally { if (e_2) throw e_2.error; }
6273
+ finally { if (e_4) throw e_4.error; }
5709
6274
  }
5710
6275
  return null;
5711
6276
  }
5712
6277
  function buildAssistantDebugPayload(params) {
5713
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4;
6278
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6;
5714
6279
  var notes = [];
5715
6280
  notes.push("Request classification: ".concat(params.requestType, " (").concat(params.requestTypeSource, ")."));
5716
6281
  if (params.dataQuestion) {
@@ -5728,6 +6293,12 @@ function buildAssistantDebugPayload(params) {
5728
6293
  notes.push('Directive did not include explicit time-based grouping.');
5729
6294
  }
5730
6295
  }
6296
+ if (params.reportStyleIntent === 'grouped') {
6297
+ notes.push('Report style intent: grouped.');
6298
+ if (params.datedDirectiveRetryUsed) {
6299
+ notes.push('Retried directive generation to enforce grouped aggregation.');
6300
+ }
6301
+ }
5731
6302
  if (params.directiveSource === 'forced') {
5732
6303
  notes.push('Assistant response omitted a REPORT_BUILDER_* directive; ran a directive-only pass.');
5733
6304
  }
@@ -5834,14 +6405,22 @@ function buildAssistantDebugPayload(params) {
5834
6405
  var to = fallbackInfo.reportFallback.to || 'base';
5835
6406
  notes.push("Report fallback: ".concat(from, " -> ").concat(to, "."));
5836
6407
  }
5837
- if ((_w = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idLookup) === null || _w === void 0 ? void 0 : _w.used) {
6408
+ if ((_w = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.collectionRetry) === null || _w === void 0 ? void 0 : _w.used) {
6409
+ var from = fallbackInfo.collectionRetry.from || 'unknown';
6410
+ var to = fallbackInfo.collectionRetry.to || 'unknown';
6411
+ notes.push("Cross-collection retry: ".concat(from, " -> ").concat(to, "."));
6412
+ }
6413
+ else if (((_x = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.collectionRetry) === null || _x === void 0 ? void 0 : _x.attempted) && Array.isArray(fallbackInfo.collectionRetry.tried) && fallbackInfo.collectionRetry.tried.length) {
6414
+ notes.push("Cross-collection retry attempted: ".concat(fallbackInfo.collectionRetry.tried.join(', '), "."));
6415
+ }
6416
+ if ((_y = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idLookup) === null || _y === void 0 ? void 0 : _y.used) {
5838
6417
  var field = fallbackInfo.idLookup.field || 'id';
5839
6418
  var strategy = fallbackInfo.idLookup.strategy || 'lookup';
5840
6419
  var collection = fallbackInfo.idLookup.collection ? " in ".concat(fallbackInfo.idLookup.collection) : '';
5841
6420
  var detail = fallbackInfo.idLookup.nameField ? " via ".concat(fallbackInfo.idLookup.nameField) : '';
5842
6421
  notes.push("Resolved ".concat(field, " by ").concat(strategy).concat(collection).concat(detail, "."));
5843
6422
  }
5844
- if ((_x = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idDisplayLookup) === null || _x === void 0 ? void 0 : _x.used) {
6423
+ if ((_z = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idDisplayLookup) === null || _z === void 0 ? void 0 : _z.used) {
5845
6424
  var lookups = Array.isArray(fallbackInfo.idDisplayLookup.lookups)
5846
6425
  ? fallbackInfo.idDisplayLookup.lookups
5847
6426
  : [];
@@ -5852,7 +6431,7 @@ function buildAssistantDebugPayload(params) {
5852
6431
  notes.push(summary ? "Resolved id lookups for display: ".concat(summary, ".") : 'Resolved id lookups for display.');
5853
6432
  }
5854
6433
  if (params.toolError) {
5855
- var errorMessage = ((_y = params.toolError) === null || _y === void 0 ? void 0 : _y.message) || String(params.toolError || '');
6434
+ var errorMessage = ((_0 = params.toolError) === null || _0 === void 0 ? void 0 : _0.message) || String(params.toolError || '');
5856
6435
  if (errorMessage) {
5857
6436
  notes.push("Tool error: ".concat(errorMessage));
5858
6437
  }
@@ -5880,13 +6459,13 @@ function buildAssistantDebugPayload(params) {
5880
6459
  collectionResolved: resolvedCollection || undefined,
5881
6460
  collectionMatched: matchedCollection,
5882
6461
  collectionCandidates: candidateCollections.length ? candidateCollections : undefined,
5883
- collectionScore: typeof ((_z = params.toolResponseDebug) === null || _z === void 0 ? void 0 : _z.collectionScore) === 'number'
6462
+ collectionScore: typeof ((_1 = params.toolResponseDebug) === null || _1 === void 0 ? void 0 : _1.collectionScore) === 'number'
5884
6463
  ? params.toolResponseDebug.collectionScore
5885
6464
  : undefined,
5886
- query: ((_0 = params.toolResponseDebug) === null || _0 === void 0 ? void 0 : _0.query) || undefined,
5887
- pipeline: ((_1 = params.toolResponseDebug) === null || _1 === void 0 ? void 0 : _1.executedPipeline) || ((_2 = params.toolResponseDebug) === null || _2 === void 0 ? void 0 : _2.originalPipeline) || undefined,
5888
- options: ((_3 = params.toolResponseDebug) === null || _3 === void 0 ? void 0 : _3.options) || undefined,
5889
- fallbacks: ((_4 = params.toolResponseDebug) === null || _4 === void 0 ? void 0 : _4.fallbacks) || undefined,
6465
+ query: ((_2 = params.toolResponseDebug) === null || _2 === void 0 ? void 0 : _2.query) || undefined,
6466
+ pipeline: ((_3 = params.toolResponseDebug) === null || _3 === void 0 ? void 0 : _3.executedPipeline) || ((_4 = params.toolResponseDebug) === null || _4 === void 0 ? void 0 : _4.originalPipeline) || undefined,
6467
+ options: ((_5 = params.toolResponseDebug) === null || _5 === void 0 ? void 0 : _5.options) || undefined,
6468
+ fallbacks: ((_6 = params.toolResponseDebug) === null || _6 === void 0 ? void 0 : _6.fallbacks) || undefined,
5890
6469
  notes: notes
5891
6470
  };
5892
6471
  if (params.trace && typeof params.trace === 'object') {
@@ -6267,7 +6846,7 @@ function getValueAtPath(obj, path) {
6267
6846
  return walk(obj, 0);
6268
6847
  }
6269
6848
  function hasArrayValueAtPath(docs, path) {
6270
- var e_3, _a;
6849
+ var e_5, _a;
6271
6850
  if (!Array.isArray(docs) || !docs.length || !path) {
6272
6851
  return false;
6273
6852
  }
@@ -6280,17 +6859,17 @@ function hasArrayValueAtPath(docs, path) {
6280
6859
  }
6281
6860
  }
6282
6861
  }
6283
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
6862
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
6284
6863
  finally {
6285
6864
  try {
6286
6865
  if (docs_1_1 && !docs_1_1.done && (_a = docs_1.return)) _a.call(docs_1);
6287
6866
  }
6288
- finally { if (e_3) throw e_3.error; }
6867
+ finally { if (e_5) throw e_5.error; }
6289
6868
  }
6290
6869
  return false;
6291
6870
  }
6292
6871
  function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
6293
- var e_4, _a, e_5, _b;
6872
+ var e_6, _a, e_7, _b;
6294
6873
  if (!Array.isArray(docs) || !fieldPath) {
6295
6874
  return 'unknown';
6296
6875
  }
@@ -6303,7 +6882,7 @@ function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
6303
6882
  : doc === null || doc === void 0 ? void 0 : doc[fieldPath];
6304
6883
  var queue = Array.isArray(value) ? value : [value];
6305
6884
  try {
6306
- for (var queue_1 = (e_5 = void 0, __values(queue)), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {
6885
+ for (var queue_1 = (e_7 = void 0, __values(queue)), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {
6307
6886
  var entry = queue_1_1.value;
6308
6887
  if (entry === null || entry === undefined) {
6309
6888
  continue;
@@ -6316,21 +6895,21 @@ function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
6316
6895
  }
6317
6896
  }
6318
6897
  }
6319
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
6898
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
6320
6899
  finally {
6321
6900
  try {
6322
6901
  if (queue_1_1 && !queue_1_1.done && (_b = queue_1.return)) _b.call(queue_1);
6323
6902
  }
6324
- finally { if (e_5) throw e_5.error; }
6903
+ finally { if (e_7) throw e_7.error; }
6325
6904
  }
6326
6905
  }
6327
6906
  }
6328
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
6907
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
6329
6908
  finally {
6330
6909
  try {
6331
6910
  if (docs_2_1 && !docs_2_1.done && (_a = docs_2.return)) _a.call(docs_2);
6332
6911
  }
6333
- finally { if (e_4) throw e_4.error; }
6912
+ finally { if (e_6) throw e_6.error; }
6334
6913
  }
6335
6914
  return sawString ? 'string' : 'unknown';
6336
6915
  }
@@ -6425,7 +7004,7 @@ function normalizeLookupKeyValue(value) {
6425
7004
  return '';
6426
7005
  }
6427
7006
  function collectTopLevelIdFieldValues(docs, options) {
6428
- var e_6, _a, e_7, _b;
7007
+ var e_8, _a, e_9, _b;
6429
7008
  if (!Array.isArray(docs) || !docs.length) {
6430
7009
  return [];
6431
7010
  }
@@ -6473,26 +7052,26 @@ function collectTopLevelIdFieldValues(docs, options) {
6473
7052
  });
6474
7053
  };
6475
7054
  try {
6476
- for (var keys_1 = (e_7 = void 0, __values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
7055
+ for (var keys_1 = (e_9 = void 0, __values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
6477
7056
  var key = keys_1_1.value;
6478
7057
  _loop_3(key);
6479
7058
  }
6480
7059
  }
6481
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
7060
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
6482
7061
  finally {
6483
7062
  try {
6484
7063
  if (keys_1_1 && !keys_1_1.done && (_b = keys_1.return)) _b.call(keys_1);
6485
7064
  }
6486
- finally { if (e_7) throw e_7.error; }
7065
+ finally { if (e_9) throw e_9.error; }
6487
7066
  }
6488
7067
  }
6489
7068
  }
6490
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
7069
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
6491
7070
  finally {
6492
7071
  try {
6493
7072
  if (docs_3_1 && !docs_3_1.done && (_a = docs_3.return)) _a.call(docs_3);
6494
7073
  }
6495
- finally { if (e_6) throw e_6.error; }
7074
+ finally { if (e_8) throw e_8.error; }
6496
7075
  }
6497
7076
  return Array.from(fieldMap.entries()).map(function (_a) {
6498
7077
  var _b = __read(_a, 2), field = _b[0], values = _b[1];
@@ -6503,7 +7082,7 @@ function collectTopLevelIdFieldValues(docs, options) {
6503
7082
  });
6504
7083
  }
6505
7084
  function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
6506
- var e_8, _a, e_9, _b;
7085
+ var e_10, _a, e_11, _b;
6507
7086
  var normalizedBase = normalizeOptionalString(baseToken);
6508
7087
  if (!normalizedBase) {
6509
7088
  return null;
@@ -6521,12 +7100,12 @@ function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
6521
7100
  }
6522
7101
  }
6523
7102
  }
6524
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
7103
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
6525
7104
  finally {
6526
7105
  try {
6527
7106
  if (schemaCandidates_1_1 && !schemaCandidates_1_1.done && (_a = schemaCandidates_1.return)) _a.call(schemaCandidates_1);
6528
7107
  }
6529
- finally { if (e_8) throw e_8.error; }
7108
+ finally { if (e_10) throw e_10.error; }
6530
7109
  }
6531
7110
  return schemaCandidates[0];
6532
7111
  }
@@ -6539,12 +7118,12 @@ function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
6539
7118
  }
6540
7119
  }
6541
7120
  }
6542
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
7121
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
6543
7122
  finally {
6544
7123
  try {
6545
7124
  if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return)) _b.call(candidates_1);
6546
7125
  }
6547
- finally { if (e_9) throw e_9.error; }
7126
+ finally { if (e_11) throw e_11.error; }
6548
7127
  }
6549
7128
  return candidates.length ? candidates[0] : null;
6550
7129
  }
@@ -6557,8 +7136,8 @@ function resolveLookupMappingsForField(field, mappings) {
6557
7136
  }
6558
7137
  function applyIdLookupDisplayEnrichment(params) {
6559
7138
  return __awaiter(this, void 0, void 0, function () {
6560
- var docs, collection, db, dbName, idClient, idCustomer, isSuperAdmin, idFields, lookupMappings, allCollections, collectionProbeCache, collectionSchemaCache, lookupMeta, enrichedDocs, _loop_4, idFields_1, idFields_1_1, fieldEntry, e_10_1;
6561
- var e_10, _a;
7139
+ var docs, collection, db, dbName, idClient, idCustomer, isSuperAdmin, idFields, lookupMappings, allCollections, collectionProbeCache, collectionSchemaCache, lookupMeta, enrichedDocs, _loop_4, idFields_1, idFields_1_1, fieldEntry, e_12_1;
7140
+ var e_12, _a;
6562
7141
  return __generator(this, function (_b) {
6563
7142
  switch (_b.label) {
6564
7143
  case 0:
@@ -6582,8 +7161,8 @@ function applyIdLookupDisplayEnrichment(params) {
6582
7161
  lookupMeta = [];
6583
7162
  enrichedDocs = docs.map(function (doc) { return (__assign({}, doc)); });
6584
7163
  _loop_4 = function (fieldEntry) {
6585
- var values, baseToken, mappingMatches, candidateCollections, filteredCandidates, _loop_5, filteredCandidates_1, filteredCandidates_1_1, candidate, state_3, e_11_1;
6586
- var e_11, _c;
7164
+ var values, baseToken, mappingMatches, candidateCollections, filteredCandidates, _loop_5, filteredCandidates_1, filteredCandidates_1_1, candidate, state_3, e_13_1;
7165
+ var e_13, _c;
6587
7166
  return __generator(this, function (_d) {
6588
7167
  switch (_d.label) {
6589
7168
  case 0:
@@ -6732,7 +7311,7 @@ function applyIdLookupDisplayEnrichment(params) {
6732
7311
  _d.label = 1;
6733
7312
  case 1:
6734
7313
  _d.trys.push([1, 6, 7, 8]);
6735
- filteredCandidates_1 = (e_11 = void 0, __values(filteredCandidates)), filteredCandidates_1_1 = filteredCandidates_1.next();
7314
+ filteredCandidates_1 = (e_13 = void 0, __values(filteredCandidates)), filteredCandidates_1_1 = filteredCandidates_1.next();
6736
7315
  _d.label = 2;
6737
7316
  case 2:
6738
7317
  if (!!filteredCandidates_1_1.done) return [3 /*break*/, 5];
@@ -6748,14 +7327,14 @@ function applyIdLookupDisplayEnrichment(params) {
6748
7327
  return [3 /*break*/, 2];
6749
7328
  case 5: return [3 /*break*/, 8];
6750
7329
  case 6:
6751
- e_11_1 = _d.sent();
6752
- e_11 = { error: e_11_1 };
7330
+ e_13_1 = _d.sent();
7331
+ e_13 = { error: e_13_1 };
6753
7332
  return [3 /*break*/, 8];
6754
7333
  case 7:
6755
7334
  try {
6756
7335
  if (filteredCandidates_1_1 && !filteredCandidates_1_1.done && (_c = filteredCandidates_1.return)) _c.call(filteredCandidates_1);
6757
7336
  }
6758
- finally { if (e_11) throw e_11.error; }
7337
+ finally { if (e_13) throw e_13.error; }
6759
7338
  return [7 /*endfinally*/];
6760
7339
  case 8: return [2 /*return*/];
6761
7340
  }
@@ -6778,14 +7357,14 @@ function applyIdLookupDisplayEnrichment(params) {
6778
7357
  return [3 /*break*/, 3];
6779
7358
  case 6: return [3 /*break*/, 9];
6780
7359
  case 7:
6781
- e_10_1 = _b.sent();
6782
- e_10 = { error: e_10_1 };
7360
+ e_12_1 = _b.sent();
7361
+ e_12 = { error: e_12_1 };
6783
7362
  return [3 /*break*/, 9];
6784
7363
  case 8:
6785
7364
  try {
6786
7365
  if (idFields_1_1 && !idFields_1_1.done && (_a = idFields_1.return)) _a.call(idFields_1);
6787
7366
  }
6788
- finally { if (e_10) throw e_10.error; }
7367
+ finally { if (e_12) throw e_12.error; }
6789
7368
  return [7 /*endfinally*/];
6790
7369
  case 9:
6791
7370
  if (!lookupMeta.length) {
@@ -6804,7 +7383,7 @@ function applyIdLookupDisplayEnrichment(params) {
6804
7383
  });
6805
7384
  }
6806
7385
  function hasNonEmptyValue(docs, fieldPath, options) {
6807
- var e_12, _a;
7386
+ var e_14, _a;
6808
7387
  if (!Array.isArray(docs) || !fieldPath) {
6809
7388
  return false;
6810
7389
  }
@@ -6821,12 +7400,12 @@ function hasNonEmptyValue(docs, fieldPath, options) {
6821
7400
  }
6822
7401
  }
6823
7402
  }
6824
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
7403
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
6825
7404
  finally {
6826
7405
  try {
6827
7406
  if (docs_4_1 && !docs_4_1.done && (_a = docs_4.return)) _a.call(docs_4);
6828
7407
  }
6829
- finally { if (e_12) throw e_12.error; }
7408
+ finally { if (e_14) throw e_14.error; }
6830
7409
  }
6831
7410
  return false;
6832
7411
  }
@@ -8851,7 +9430,7 @@ function flattenAssistantExprClauses(expr) {
8851
9430
  return [expr];
8852
9431
  }
8853
9432
  function detectAssistantMonthWindowInExpr(expr, allowedDateFields) {
8854
- var e_13, _a;
9433
+ var e_15, _a;
8855
9434
  var clauses = flattenAssistantExprClauses(expr);
8856
9435
  if (!clauses.length) {
8857
9436
  return null;
@@ -8925,12 +9504,12 @@ function detectAssistantMonthWindowInExpr(expr, allowedDateFields) {
8925
9504
  return state_4.value;
8926
9505
  }
8927
9506
  }
8928
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
9507
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
8929
9508
  finally {
8930
9509
  try {
8931
9510
  if (lowerClauses_1_1 && !lowerClauses_1_1.done && (_a = lowerClauses_1.return)) _a.call(lowerClauses_1);
8932
9511
  }
8933
- finally { if (e_13) throw e_13.error; }
9512
+ finally { if (e_15) throw e_15.error; }
8934
9513
  }
8935
9514
  return null;
8936
9515
  }
@@ -8993,7 +9572,7 @@ function resolveAssistantMonthlyGroupDateFields(pipeline) {
8993
9572
  return fields;
8994
9573
  }
8995
9574
  function detectAssistantMonthWindowFromPipeline(pipeline) {
8996
- var e_14, _a;
9575
+ var e_16, _a;
8997
9576
  var _b;
8998
9577
  var monthlyFields = resolveAssistantMonthlyGroupDateFields(pipeline);
8999
9578
  var scanMatch = function (match) {
@@ -9021,12 +9600,12 @@ function detectAssistantMonthWindowFromPipeline(pipeline) {
9021
9600
  }
9022
9601
  }
9023
9602
  }
9024
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
9603
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
9025
9604
  finally {
9026
9605
  try {
9027
9606
  if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
9028
9607
  }
9029
- finally { if (e_14) throw e_14.error; }
9608
+ finally { if (e_16) throw e_16.error; }
9030
9609
  }
9031
9610
  return null;
9032
9611
  }
@@ -9229,7 +9808,7 @@ function matchContainsField(value, field) {
9229
9808
  });
9230
9809
  }
9231
9810
  function resolveAggregateCompletionFallback(pipeline) {
9232
- var e_15, _a;
9811
+ var e_17, _a;
9233
9812
  if (!Array.isArray(pipeline)) {
9234
9813
  return null;
9235
9814
  }
@@ -9242,7 +9821,7 @@ function resolveAggregateCompletionFallback(pipeline) {
9242
9821
  }
9243
9822
  var addFields = stage.$addFields;
9244
9823
  try {
9245
- for (var _b = (e_15 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
9824
+ for (var _b = (e_17 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
9246
9825
  var key = _c.value;
9247
9826
  if (!isCompletionFieldName(key)) {
9248
9827
  continue;
@@ -9256,12 +9835,12 @@ function resolveAggregateCompletionFallback(pipeline) {
9256
9835
  }
9257
9836
  }
9258
9837
  }
9259
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
9838
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
9260
9839
  finally {
9261
9840
  try {
9262
9841
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9263
9842
  }
9264
- finally { if (e_15) throw e_15.error; }
9843
+ finally { if (e_17) throw e_17.error; }
9265
9844
  }
9266
9845
  if (candidateField) {
9267
9846
  break;
@@ -9417,7 +9996,7 @@ function buildCompletionFallbackSources(field) {
9417
9996
  ]);
9418
9997
  }
9419
9998
  function resolveAggregateCompletionExprFallback(pipeline) {
9420
- var e_16, _a;
9999
+ var e_18, _a;
9421
10000
  if (!Array.isArray(pipeline)) {
9422
10001
  return null;
9423
10002
  }
@@ -9437,7 +10016,7 @@ function resolveAggregateCompletionExprFallback(pipeline) {
9437
10016
  }
9438
10017
  if (!candidateField) {
9439
10018
  try {
9440
- for (var _b = (e_16 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
10019
+ for (var _b = (e_18 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
9441
10020
  var key = _c.value;
9442
10021
  if (key.startsWith('$')) {
9443
10022
  continue;
@@ -9452,12 +10031,12 @@ function resolveAggregateCompletionExprFallback(pipeline) {
9452
10031
  }
9453
10032
  }
9454
10033
  }
9455
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
10034
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
9456
10035
  finally {
9457
10036
  try {
9458
10037
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
9459
10038
  }
9460
- finally { if (e_16) throw e_16.error; }
10039
+ finally { if (e_18) throw e_18.error; }
9461
10040
  }
9462
10041
  }
9463
10042
  if (!candidateField) {
@@ -9597,7 +10176,7 @@ function hasAssistantDateGroupingOperator(value) {
9597
10176
  return Object.keys(value).some(function (key) { return hasAssistantDateGroupingOperator(value[key]); });
9598
10177
  }
9599
10178
  function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths) {
9600
- var e_17, _a, e_18, _b;
10179
+ var e_19, _a, e_20, _b;
9601
10180
  if (!Array.isArray(pipeline) || groupIndex <= 0 || !groupPaths.length) {
9602
10181
  return false;
9603
10182
  }
@@ -9623,14 +10202,14 @@ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths)
9623
10202
  continue;
9624
10203
  }
9625
10204
  try {
9626
- for (var stageKeys_1 = (e_17 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
10205
+ for (var stageKeys_1 = (e_19 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
9627
10206
  var stageKey = stageKeys_1_1.value;
9628
10207
  var payload = stage[stageKey];
9629
10208
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
9630
10209
  continue;
9631
10210
  }
9632
10211
  try {
9633
- for (var groupFields_1 = (e_18 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
10212
+ for (var groupFields_1 = (e_20 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
9634
10213
  var groupField = groupFields_1_1.value;
9635
10214
  if (!Object.prototype.hasOwnProperty.call(payload, groupField)) {
9636
10215
  continue;
@@ -9640,21 +10219,21 @@ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths)
9640
10219
  }
9641
10220
  }
9642
10221
  }
9643
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
10222
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
9644
10223
  finally {
9645
10224
  try {
9646
10225
  if (groupFields_1_1 && !groupFields_1_1.done && (_b = groupFields_1.return)) _b.call(groupFields_1);
9647
10226
  }
9648
- finally { if (e_18) throw e_18.error; }
10227
+ finally { if (e_20) throw e_20.error; }
9649
10228
  }
9650
10229
  }
9651
10230
  }
9652
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
10231
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
9653
10232
  finally {
9654
10233
  try {
9655
10234
  if (stageKeys_1_1 && !stageKeys_1_1.done && (_a = stageKeys_1.return)) _a.call(stageKeys_1);
9656
10235
  }
9657
- finally { if (e_17) throw e_17.error; }
10236
+ finally { if (e_19) throw e_19.error; }
9658
10237
  }
9659
10238
  }
9660
10239
  return false;
@@ -9681,6 +10260,12 @@ function isAssistantTimeGroupedAggregatePipeline(pipeline) {
9681
10260
  }
9682
10261
  return isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths);
9683
10262
  }
10263
+ function isAssistantGroupedAggregatePipeline(pipeline) {
10264
+ if (!Array.isArray(pipeline) || !pipeline.length) {
10265
+ return false;
10266
+ }
10267
+ return findAggregateGroupIndex(pipeline) !== -1;
10268
+ }
9684
10269
  function isAssistantDirectiveDated(directive) {
9685
10270
  var _a;
9686
10271
  if (!directive || directive.type !== 'aggregate') {
@@ -9689,6 +10274,14 @@ function isAssistantDirectiveDated(directive) {
9689
10274
  var pipeline = Array.isArray((_a = directive.payload) === null || _a === void 0 ? void 0 : _a.pipeline) ? directive.payload.pipeline : [];
9690
10275
  return isAssistantTimeGroupedAggregatePipeline(pipeline);
9691
10276
  }
10277
+ function isAssistantDirectiveGrouped(directive) {
10278
+ var _a;
10279
+ if (!directive || directive.type !== 'aggregate') {
10280
+ return false;
10281
+ }
10282
+ var pipeline = Array.isArray((_a = directive.payload) === null || _a === void 0 ? void 0 : _a.pipeline) ? directive.payload.pipeline : [];
10283
+ return isAssistantGroupedAggregatePipeline(pipeline);
10284
+ }
9692
10285
  function findCommonPathPrefix(paths) {
9693
10286
  var _a;
9694
10287
  if (!paths.length) {
@@ -9747,7 +10340,7 @@ function isRegexMatchCondition(value) {
9747
10340
  return false;
9748
10341
  }
9749
10342
  function findRegexMatchInMatchObject(match, prefix) {
9750
- var e_19, _a, e_20, _b;
10343
+ var e_21, _a, e_22, _b;
9751
10344
  if (prefix === void 0) { prefix = ''; }
9752
10345
  if (Array.isArray(match)) {
9753
10346
  try {
@@ -9759,12 +10352,12 @@ function findRegexMatchInMatchObject(match, prefix) {
9759
10352
  }
9760
10353
  }
9761
10354
  }
9762
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
10355
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
9763
10356
  finally {
9764
10357
  try {
9765
10358
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
9766
10359
  }
9767
- finally { if (e_19) throw e_19.error; }
10360
+ finally { if (e_21) throw e_21.error; }
9768
10361
  }
9769
10362
  return null;
9770
10363
  }
@@ -9795,12 +10388,12 @@ function findRegexMatchInMatchObject(match, prefix) {
9795
10388
  }
9796
10389
  }
9797
10390
  }
9798
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
10391
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
9799
10392
  finally {
9800
10393
  try {
9801
10394
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
9802
10395
  }
9803
- finally { if (e_20) throw e_20.error; }
10396
+ finally { if (e_22) throw e_22.error; }
9804
10397
  }
9805
10398
  return null;
9806
10399
  }
@@ -10024,7 +10617,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
10024
10617
  return results;
10025
10618
  }
10026
10619
  function findMatchConditionForField(match, targetField, prefix) {
10027
- var e_21, _a, e_22, _b;
10620
+ var e_23, _a, e_24, _b;
10028
10621
  if (prefix === void 0) { prefix = ''; }
10029
10622
  if (!match || typeof match !== 'object') {
10030
10623
  return undefined;
@@ -10039,12 +10632,12 @@ function findMatchConditionForField(match, targetField, prefix) {
10039
10632
  }
10040
10633
  }
10041
10634
  }
10042
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
10635
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
10043
10636
  finally {
10044
10637
  try {
10045
10638
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
10046
10639
  }
10047
- finally { if (e_21) throw e_21.error; }
10640
+ finally { if (e_23) throw e_23.error; }
10048
10641
  }
10049
10642
  return undefined;
10050
10643
  }
@@ -10071,12 +10664,12 @@ function findMatchConditionForField(match, targetField, prefix) {
10071
10664
  }
10072
10665
  }
10073
10666
  }
10074
- catch (e_22_1) { e_22 = { error: e_22_1 }; }
10667
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
10075
10668
  finally {
10076
10669
  try {
10077
10670
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
10078
10671
  }
10079
- finally { if (e_22) throw e_22.error; }
10672
+ finally { if (e_24) throw e_24.error; }
10080
10673
  }
10081
10674
  return undefined;
10082
10675
  }
@@ -10180,7 +10773,7 @@ function detectIdLikeValue(value) {
10180
10773
  return false;
10181
10774
  }
10182
10775
  function detectChemicalIdFromProbe(probeDocs, fields) {
10183
- var e_23, _a, e_24, _b;
10776
+ var e_25, _a, e_26, _b;
10184
10777
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
10185
10778
  return false;
10186
10779
  }
@@ -10192,7 +10785,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
10192
10785
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
10193
10786
  var doc = probeDocs_1_1.value;
10194
10787
  try {
10195
- for (var targets_1 = (e_24 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
10788
+ for (var targets_1 = (e_26 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
10196
10789
  var field = targets_1_1.value;
10197
10790
  var value = getValueAtPath(doc, field);
10198
10791
  if (Array.isArray(value)) {
@@ -10205,21 +10798,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
10205
10798
  }
10206
10799
  }
10207
10800
  }
10208
- catch (e_24_1) { e_24 = { error: e_24_1 }; }
10801
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
10209
10802
  finally {
10210
10803
  try {
10211
10804
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
10212
10805
  }
10213
- finally { if (e_24) throw e_24.error; }
10806
+ finally { if (e_26) throw e_26.error; }
10214
10807
  }
10215
10808
  }
10216
10809
  }
10217
- catch (e_23_1) { e_23 = { error: e_23_1 }; }
10810
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
10218
10811
  finally {
10219
10812
  try {
10220
10813
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
10221
10814
  }
10222
- finally { if (e_23) throw e_23.error; }
10815
+ finally { if (e_25) throw e_25.error; }
10223
10816
  }
10224
10817
  return false;
10225
10818
  }
@@ -10440,8 +11033,8 @@ function buildChemicalIdFieldCandidates(field) {
10440
11033
  }
10441
11034
  function applyChemicalNameLookupFallbackToQuery(params) {
10442
11035
  return __awaiter(this, void 0, void 0, function () {
10443
- 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_25_1;
10444
- var e_25, _a;
11036
+ 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_27_1;
11037
+ var e_27, _a;
10445
11038
  var _b;
10446
11039
  return __generator(this, function (_c) {
10447
11040
  switch (_c.label) {
@@ -10554,14 +11147,14 @@ function applyChemicalNameLookupFallbackToQuery(params) {
10554
11147
  return [3 /*break*/, 3];
10555
11148
  case 6: return [3 /*break*/, 9];
10556
11149
  case 7:
10557
- e_25_1 = _c.sent();
10558
- e_25 = { error: e_25_1 };
11150
+ e_27_1 = _c.sent();
11151
+ e_27 = { error: e_27_1 };
10559
11152
  return [3 /*break*/, 9];
10560
11153
  case 8:
10561
11154
  try {
10562
11155
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
10563
11156
  }
10564
- finally { if (e_25) throw e_25.error; }
11157
+ finally { if (e_27) throw e_27.error; }
10565
11158
  return [7 /*endfinally*/];
10566
11159
  case 9: return [2 /*return*/, null];
10567
11160
  }
@@ -10655,8 +11248,8 @@ function lookupIdsForNameMatch(params) {
10655
11248
  }
10656
11249
  function applyIdLookupFallbackToQuery(params) {
10657
11250
  return __awaiter(this, void 0, void 0, function () {
10658
- 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_26_1, e_27_1;
10659
- var e_27, _c, e_26, _d;
11251
+ 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_28_1, e_29_1;
11252
+ var e_29, _c, e_28, _d;
10660
11253
  var _e;
10661
11254
  return __generator(this, function (_f) {
10662
11255
  switch (_f.label) {
@@ -10726,7 +11319,7 @@ function applyIdLookupFallbackToQuery(params) {
10726
11319
  _f.label = 5;
10727
11320
  case 5:
10728
11321
  _f.trys.push([5, 14, 15, 16]);
10729
- candidates_3 = (e_26 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
11322
+ candidates_3 = (e_28 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
10730
11323
  _f.label = 6;
10731
11324
  case 6:
10732
11325
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -10793,28 +11386,28 @@ function applyIdLookupFallbackToQuery(params) {
10793
11386
  return [3 /*break*/, 6];
10794
11387
  case 13: return [3 /*break*/, 16];
10795
11388
  case 14:
10796
- e_26_1 = _f.sent();
10797
- e_26 = { error: e_26_1 };
11389
+ e_28_1 = _f.sent();
11390
+ e_28 = { error: e_28_1 };
10798
11391
  return [3 /*break*/, 16];
10799
11392
  case 15:
10800
11393
  try {
10801
11394
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
10802
11395
  }
10803
- finally { if (e_26) throw e_26.error; }
11396
+ finally { if (e_28) throw e_28.error; }
10804
11397
  return [7 /*endfinally*/];
10805
11398
  case 16:
10806
11399
  conditions_1_1 = conditions_1.next();
10807
11400
  return [3 /*break*/, 4];
10808
11401
  case 17: return [3 /*break*/, 20];
10809
11402
  case 18:
10810
- e_27_1 = _f.sent();
10811
- e_27 = { error: e_27_1 };
11403
+ e_29_1 = _f.sent();
11404
+ e_29 = { error: e_29_1 };
10812
11405
  return [3 /*break*/, 20];
10813
11406
  case 19:
10814
11407
  try {
10815
11408
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
10816
11409
  }
10817
- finally { if (e_27) throw e_27.error; }
11410
+ finally { if (e_29) throw e_29.error; }
10818
11411
  return [7 /*endfinally*/];
10819
11412
  case 20: return [2 /*return*/, null];
10820
11413
  }
@@ -11412,6 +12005,9 @@ function resolveAssistantDefaultCollectionHints(message) {
11412
12005
  push('customers');
11413
12006
  push('clients');
11414
12007
  }
12008
+ if (/\bsupport[\s-]*tickets?\b/.test(text) || /\btickets?\b/.test(text)) {
12009
+ push('support-tickets');
12010
+ }
11415
12011
  return hints;
11416
12012
  }
11417
12013
  function buildCollectionRankingDebugFromTokens(tokens, collectionNames, max) {
@@ -11717,6 +12313,10 @@ var AI_ASSISTANT_BRIDGE_COLLECTION_ALIASES = {
11717
12313
  reportchemicalblends: 'chemical-blends',
11718
12314
  blend: 'chemical-blends',
11719
12315
  blends: 'chemical-blends',
12316
+ supportticket: 'support-tickets',
12317
+ supporttickets: 'support-tickets',
12318
+ ticket: 'support-tickets',
12319
+ tickets: 'support-tickets',
11720
12320
  invoice: 'invoices',
11721
12321
  client: 'customers',
11722
12322
  clients: 'customers',
@@ -11728,8 +12328,154 @@ var AI_ASSISTANT_DIRECT_COLLECTION_FALLBACK_ALLOWLIST = new Set([
11728
12328
  'chemical-blends',
11729
12329
  'report-chemical-blends',
11730
12330
  'jobs',
11731
- 'customers'
12331
+ 'customers',
12332
+ 'support-tickets'
11732
12333
  ]);
12334
+ var AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS = [
12335
+ 'work-order-dynamics',
12336
+ 'maintenance-orders',
12337
+ 'orders',
12338
+ 'repair-orders',
12339
+ 'reoccurring-orders'
12340
+ ];
12341
+ var AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS = [
12342
+ 'customers',
12343
+ 'clients',
12344
+ 'api-customers',
12345
+ 'ibp-customers',
12346
+ 'qb-customers'
12347
+ ];
12348
+ var AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS = [
12349
+ 'support-tickets',
12350
+ 'supporttickets',
12351
+ 'support-ticket'
12352
+ ];
12353
+ var AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS = [
12354
+ 'invoices',
12355
+ 'billings',
12356
+ 'sales-taxes'
12357
+ ];
12358
+ function normalizeAssistantCollectionFamilyName(value) {
12359
+ var normalized = normalizeOptionalString(value).toLowerCase();
12360
+ if (!normalized) {
12361
+ return '';
12362
+ }
12363
+ var withoutReport = normalized.startsWith('report-') ? normalized.slice('report-'.length) : normalized;
12364
+ return stripVersionSuffix(withoutReport);
12365
+ }
12366
+ function addAssistantCollectionToTriedSet(tried, collection) {
12367
+ var normalized = normalizeOptionalString(collection);
12368
+ if (normalized) {
12369
+ tried.add(normalized);
12370
+ }
12371
+ var family = normalizeAssistantCollectionFamilyName(collection);
12372
+ if (family) {
12373
+ tried.add(family);
12374
+ }
12375
+ }
12376
+ function buildAssistantTriedCollectionSet(triedCollections) {
12377
+ var tried = new Set();
12378
+ var values = Array.isArray(triedCollections) ? triedCollections : [];
12379
+ values.forEach(function (value) {
12380
+ if (typeof value !== 'string') {
12381
+ return;
12382
+ }
12383
+ addAssistantCollectionToTriedSet(tried, value);
12384
+ });
12385
+ return tried;
12386
+ }
12387
+ function hasAssistantCollectionBeenTried(tried, collection) {
12388
+ var normalized = normalizeOptionalString(collection);
12389
+ var family = normalizeAssistantCollectionFamilyName(collection);
12390
+ return !!((normalized && tried.has(normalized)) || (family && tried.has(family)));
12391
+ }
12392
+ function buildAssistantRetryState(baseState, triedCollections, options) {
12393
+ var next = {
12394
+ triedCollections: Array.from(triedCollections)
12395
+ };
12396
+ var rootCollection = normalizeOptionalString((options === null || options === void 0 ? void 0 : options.rootCollection) || (baseState === null || baseState === void 0 ? void 0 : baseState.rootCollection));
12397
+ if (rootCollection) {
12398
+ next.rootCollection = rootCollection;
12399
+ }
12400
+ if ((options === null || options === void 0 ? void 0 : options.disableCrossCollectionRetry) === true || (baseState === null || baseState === void 0 ? void 0 : baseState.disableCrossCollectionRetry) === true) {
12401
+ next.disableCrossCollectionRetry = true;
12402
+ }
12403
+ return next;
12404
+ }
12405
+ function resolveAssistantCrossCollectionFallbackCandidates(collection) {
12406
+ var normalized = normalizeAssistantCollectionFamilyName(collection);
12407
+ if (!normalized) {
12408
+ return [];
12409
+ }
12410
+ var candidates = [];
12411
+ if (AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('order')) {
12412
+ candidates = AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS;
12413
+ }
12414
+ else if (AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('customer') || normalized.includes('client')) {
12415
+ candidates = AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS;
12416
+ }
12417
+ else if (AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('ticket') || normalized.includes('support')) {
12418
+ candidates = AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS;
12419
+ }
12420
+ else if (AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('invoice') || normalized.includes('billing')) {
12421
+ candidates = AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS;
12422
+ }
12423
+ var deduped = [];
12424
+ candidates.forEach(function (candidate) {
12425
+ if (!candidate || deduped.includes(candidate)) {
12426
+ return;
12427
+ }
12428
+ deduped.push(candidate);
12429
+ });
12430
+ return deduped;
12431
+ }
12432
+ function resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections) {
12433
+ return __awaiter(this, void 0, void 0, function () {
12434
+ var candidates, collectionNames, namesByFamily, currentFamily, available;
12435
+ return __generator(this, function (_a) {
12436
+ switch (_a.label) {
12437
+ case 0:
12438
+ candidates = resolveAssistantCrossCollectionFallbackCandidates(collection);
12439
+ if (!candidates.length) {
12440
+ return [2 /*return*/, []];
12441
+ }
12442
+ return [4 /*yield*/, listAssistantCollections(db, dbName)];
12443
+ case 1:
12444
+ collectionNames = _a.sent();
12445
+ namesByFamily = new Map();
12446
+ collectionNames.forEach(function (name) {
12447
+ var family = normalizeAssistantCollectionFamilyName(name);
12448
+ if (!family) {
12449
+ return;
12450
+ }
12451
+ var existing = namesByFamily.get(family) || [];
12452
+ existing.push(name);
12453
+ namesByFamily.set(family, existing);
12454
+ });
12455
+ currentFamily = normalizeAssistantCollectionFamilyName(collection);
12456
+ available = [];
12457
+ candidates.forEach(function (candidate) {
12458
+ var family = normalizeAssistantCollectionFamilyName(candidate);
12459
+ if (!family || family === currentFamily || hasAssistantCollectionBeenTried(triedCollections, candidate)) {
12460
+ return;
12461
+ }
12462
+ var familyNames = namesByFamily.get(family) || [];
12463
+ if (!familyNames.length) {
12464
+ return;
12465
+ }
12466
+ var preferred = familyNames.find(function (name) { return !name.startsWith('report-') && !isVersionCollectionName(name); })
12467
+ || familyNames.find(function (name) { return !name.startsWith('report-'); })
12468
+ || familyNames[0];
12469
+ if (!preferred || hasAssistantCollectionBeenTried(triedCollections, preferred) || available.includes(preferred)) {
12470
+ return;
12471
+ }
12472
+ available.push(preferred);
12473
+ });
12474
+ return [2 /*return*/, available];
12475
+ }
12476
+ });
12477
+ });
12478
+ }
11733
12479
  function resolveAssistantBridgeCollectionAlias(value) {
11734
12480
  var key = normalizeCollectionKey(value);
11735
12481
  return AI_ASSISTANT_BRIDGE_COLLECTION_ALIASES[key] || '';
@@ -11744,7 +12490,7 @@ function isAssistantDirectCollectionFallbackAllowed(collection) {
11744
12490
  function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
11745
12491
  return __awaiter(this, arguments, void 0, function (collection, db, dbName) {
11746
12492
  var normalized, alias, manager, fallback, candidates, pushCandidate, base, reportCandidate, candidates_4, candidates_4_1, candidate, model, resolved, resolvedName, model, _a, candidates_5, candidates_5_1, candidate;
11747
- var e_28, _b, e_29, _c;
12493
+ var e_30, _b, e_31, _c;
11748
12494
  var _d;
11749
12495
  if (dbName === void 0) { dbName = ''; }
11750
12496
  return __generator(this, function (_e) {
@@ -11792,12 +12538,12 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
11792
12538
  }
11793
12539
  }
11794
12540
  }
11795
- catch (e_28_1) { e_28 = { error: e_28_1 }; }
12541
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
11796
12542
  finally {
11797
12543
  try {
11798
12544
  if (candidates_4_1 && !candidates_4_1.done && (_b = candidates_4.return)) _b.call(candidates_4);
11799
12545
  }
11800
- finally { if (e_28) throw e_28.error; }
12546
+ finally { if (e_30) throw e_30.error; }
11801
12547
  }
11802
12548
  if (!(db && dbName)) return [3 /*break*/, 4];
11803
12549
  _e.label = 1;
@@ -11827,12 +12573,12 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
11827
12573
  }
11828
12574
  }
11829
12575
  }
11830
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
12576
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
11831
12577
  finally {
11832
12578
  try {
11833
12579
  if (candidates_5_1 && !candidates_5_1.done && (_c = candidates_5.return)) _c.call(candidates_5);
11834
12580
  }
11835
- finally { if (e_29) throw e_29.error; }
12581
+ finally { if (e_31) throw e_31.error; }
11836
12582
  }
11837
12583
  throw new Error('AI assistant report builder bridge: Collection is not configured for report builder.');
11838
12584
  }
@@ -11840,7 +12586,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
11840
12586
  });
11841
12587
  }
11842
12588
  function findQueryDateField(query) {
11843
- var e_30, _a, e_31, _b;
12589
+ var e_32, _a, e_33, _b;
11844
12590
  if (!query || typeof query !== 'object') {
11845
12591
  return null;
11846
12592
  }
@@ -11854,12 +12600,12 @@ function findQueryDateField(query) {
11854
12600
  }
11855
12601
  }
11856
12602
  }
11857
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
12603
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
11858
12604
  finally {
11859
12605
  try {
11860
12606
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
11861
12607
  }
11862
- finally { if (e_30) throw e_30.error; }
12608
+ finally { if (e_32) throw e_32.error; }
11863
12609
  }
11864
12610
  return null;
11865
12611
  }
@@ -11878,12 +12624,12 @@ function findQueryDateField(query) {
11878
12624
  }
11879
12625
  }
11880
12626
  }
11881
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
12627
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
11882
12628
  finally {
11883
12629
  try {
11884
12630
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
11885
12631
  }
11886
- finally { if (e_31) throw e_31.error; }
12632
+ finally { if (e_33) throw e_33.error; }
11887
12633
  }
11888
12634
  return null;
11889
12635
  }
@@ -12132,7 +12878,7 @@ function resolveQueryDateFieldFallback(query) {
12132
12878
  return { from: dateField, to: fallback };
12133
12879
  }
12134
12880
  function containsForbiddenMongoOperators(value) {
12135
- var e_32, _a;
12881
+ var e_34, _a;
12136
12882
  if (!value || typeof value !== 'object') {
12137
12883
  return false;
12138
12884
  }
@@ -12151,12 +12897,12 @@ function containsForbiddenMongoOperators(value) {
12151
12897
  }
12152
12898
  }
12153
12899
  }
12154
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
12900
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
12155
12901
  finally {
12156
12902
  try {
12157
12903
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
12158
12904
  }
12159
- finally { if (e_32) throw e_32.error; }
12905
+ finally { if (e_34) throw e_34.error; }
12160
12906
  }
12161
12907
  return false;
12162
12908
  }
@@ -12599,8 +13345,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
12599
13345
  }
12600
13346
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
12601
13347
  return __awaiter(this, void 0, void 0, function () {
12602
- var _a, _b, _c, _d, message, payload, status_1, e_33_1;
12603
- var _e, e_33, _f, _g;
13348
+ var _a, _b, _c, _d, message, payload, status_1, e_35_1;
13349
+ var _e, e_35, _f, _g;
12604
13350
  return __generator(this, function (_h) {
12605
13351
  switch (_h.label) {
12606
13352
  case 0:
@@ -12627,8 +13373,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
12627
13373
  return [3 /*break*/, 1];
12628
13374
  case 4: return [3 /*break*/, 11];
12629
13375
  case 5:
12630
- e_33_1 = _h.sent();
12631
- e_33 = { error: e_33_1 };
13376
+ e_35_1 = _h.sent();
13377
+ e_35 = { error: e_35_1 };
12632
13378
  return [3 /*break*/, 11];
12633
13379
  case 6:
12634
13380
  _h.trys.push([6, , 9, 10]);
@@ -12639,7 +13385,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
12639
13385
  _h.label = 8;
12640
13386
  case 8: return [3 /*break*/, 10];
12641
13387
  case 9:
12642
- if (e_33) throw e_33.error;
13388
+ if (e_35) throw e_35.error;
12643
13389
  return [7 /*endfinally*/];
12644
13390
  case 10: return [7 /*endfinally*/];
12645
13391
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -12649,7 +13395,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
12649
13395
  }
12650
13396
  function runCodexInWorkerThread(prompt, runOptions, config, streamStatusHandler) {
12651
13397
  return __awaiter(this, void 0, void 0, function () {
12652
- var streamedOptions, codexClient, workerPath, codexClient, error_5, codexClient;
13398
+ var streamedOptions, codexClient, workerPath, codexClient, error_6, codexClient;
12653
13399
  return __generator(this, function (_a) {
12654
13400
  switch (_a.label) {
12655
13401
  case 0:
@@ -12670,11 +13416,11 @@ function runCodexInWorkerThread(prompt, runOptions, config, streamStatusHandler)
12670
13416
  return [4 /*yield*/, runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config, streamStatusHandler)];
12671
13417
  case 6: return [2 /*return*/, _a.sent()];
12672
13418
  case 7:
12673
- error_5 = _a.sent();
12674
- if (!(error_5 instanceof CodexWorkerBootstrapError)) {
12675
- throw error_5;
13419
+ error_6 = _a.sent();
13420
+ if (!(error_6 instanceof CodexWorkerBootstrapError)) {
13421
+ throw error_6;
12676
13422
  }
12677
- console.error('Codex worker bootstrap failed, falling back to in-process run.', error_5);
13423
+ console.error('Codex worker bootstrap failed, falling back to in-process run.', error_6);
12678
13424
  codexClient = getAssistantCodexClient(config);
12679
13425
  return [4 /*yield*/, codexClient.run(prompt, streamedOptions)];
12680
13426
  case 8: return [2 /*return*/, _a.sent()];
@@ -12712,7 +13458,7 @@ function runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config,
12712
13458
  timeoutMs = ((sanitizedOptions === null || sanitizedOptions === void 0 ? void 0 : sanitizedOptions.timeoutMs) || resolveCodexTimeoutMs()) + 15000;
12713
13459
  timeoutController = new AbortController();
12714
13460
  timeoutPromise = (function () { return __awaiter(_this, void 0, void 0, function () {
12715
- var error_6;
13461
+ var error_7;
12716
13462
  return __generator(this, function (_a) {
12717
13463
  switch (_a.label) {
12718
13464
  case 0:
@@ -12722,11 +13468,11 @@ function runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config,
12722
13468
  _a.sent();
12723
13469
  return [2 /*return*/, { type: 'timeout' }];
12724
13470
  case 2:
12725
- error_6 = _a.sent();
12726
- if ((error_6 === null || error_6 === void 0 ? void 0 : error_6.name) === 'AbortError') {
13471
+ error_7 = _a.sent();
13472
+ if ((error_7 === null || error_7 === void 0 ? void 0 : error_7.name) === 'AbortError') {
12727
13473
  return [2 /*return*/, { type: 'aborted' }];
12728
13474
  }
12729
- throw error_6;
13475
+ throw error_7;
12730
13476
  case 3: return [2 /*return*/];
12731
13477
  }
12732
13478
  });
@@ -13067,6 +13813,8 @@ var AI_ASSISTANT_DATA_REQUEST_PATTERNS = [
13067
13813
  /\bmissing\b/,
13068
13814
  /\bgroup(ed)? by\b/,
13069
13815
  /\bbreakdown\b/,
13816
+ /\bbreak\s+up\b/,
13817
+ /\b(by|per)\s+(user|customer|client|status|driver|assignee|owner|location|type|priority)\b/,
13070
13818
  /\bby day\b/,
13071
13819
  /\bby week\b/,
13072
13820
  /\bby month\b/,
@@ -13119,7 +13867,9 @@ var AI_ASSISTANT_STRONG_DATA_PATTERNS = [
13119
13867
  /\baverage\b/,
13120
13868
  /\bavg\b/,
13121
13869
  /\bbreakdown\b/,
13870
+ /\bbreak\s+up\b/,
13122
13871
  /\bgroup(ed)? by\b/,
13872
+ /\b(by|per)\s+(user|customer|client|status|driver|assignee|owner|location|type|priority)\b/,
13123
13873
  /\bby day\b/,
13124
13874
  /\bby week\b/,
13125
13875
  /\bby month\b/,
@@ -13349,6 +14099,143 @@ function hasAssistantDatedLanguage(message) {
13349
14099
  ];
13350
14100
  return patterns.some(function (pattern) { return pattern.test(text); });
13351
14101
  }
14102
+ var AI_ASSISTANT_BREAKDOWN_DIMENSION_STOPWORDS = new Set([
14103
+ 'of',
14104
+ 'in',
14105
+ 'for',
14106
+ 'with',
14107
+ 'to',
14108
+ 'from',
14109
+ 'over',
14110
+ 'across',
14111
+ 'within',
14112
+ 'between',
14113
+ 'into',
14114
+ 'onto',
14115
+ 'through',
14116
+ 'during',
14117
+ 'and',
14118
+ 'or',
14119
+ 'that',
14120
+ 'which',
14121
+ 'who',
14122
+ 'what',
14123
+ 'when',
14124
+ 'where',
14125
+ 'while',
14126
+ 'than',
14127
+ 'then',
14128
+ 'as',
14129
+ 'is',
14130
+ 'are',
14131
+ 'was',
14132
+ 'were',
14133
+ 'be',
14134
+ 'been',
14135
+ 'being',
14136
+ 'last',
14137
+ 'past',
14138
+ 'previous',
14139
+ 'recent',
14140
+ 'current',
14141
+ 'next',
14142
+ 'this',
14143
+ 'these',
14144
+ 'those',
14145
+ 'now',
14146
+ 'today',
14147
+ 'tomorrow',
14148
+ 'yesterday',
14149
+ 'me',
14150
+ 'my',
14151
+ 'our',
14152
+ 'your',
14153
+ 'their',
14154
+ 'by'
14155
+ ]);
14156
+ function normalizeAssistantBreakdownDimension(value) {
14157
+ var e_36, _a;
14158
+ var normalized = normalizeOptionalString(value)
14159
+ .toLowerCase()
14160
+ .replace(/[^a-z0-9_\s-]+/g, ' ')
14161
+ .replace(/\s+/g, ' ')
14162
+ .trim();
14163
+ if (!normalized) {
14164
+ return '';
14165
+ }
14166
+ var tokens = normalized
14167
+ .split(/\s+/g)
14168
+ .filter(Boolean)
14169
+ .filter(function (token) { return !['the', 'a', 'an', 'each'].includes(token); });
14170
+ if (!tokens.length) {
14171
+ return '';
14172
+ }
14173
+ var kept = [];
14174
+ try {
14175
+ for (var tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next(); !tokens_1_1.done; tokens_1_1 = tokens_1.next()) {
14176
+ var token = tokens_1_1.value;
14177
+ if (AI_ASSISTANT_BREAKDOWN_DIMENSION_STOPWORDS.has(token)) {
14178
+ break;
14179
+ }
14180
+ if (/^\d+$/.test(token)) {
14181
+ break;
14182
+ }
14183
+ kept.push(token);
14184
+ if (kept.length >= 3) {
14185
+ break;
14186
+ }
14187
+ }
14188
+ }
14189
+ catch (e_36_1) { e_36 = { error: e_36_1 }; }
14190
+ finally {
14191
+ try {
14192
+ if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
14193
+ }
14194
+ finally { if (e_36) throw e_36.error; }
14195
+ }
14196
+ if (!kept.length) {
14197
+ return '';
14198
+ }
14199
+ return kept.join(' ').trim();
14200
+ }
14201
+ function extractAssistantRequestedBreakdownDimensions(message) {
14202
+ var text = normalizeOptionalString(message).toLowerCase();
14203
+ if (!text) {
14204
+ return [];
14205
+ }
14206
+ var results = [];
14207
+ var seen = new Set();
14208
+ var add = function (value) {
14209
+ var normalized = normalizeAssistantBreakdownDimension(value);
14210
+ if (!normalized || seen.has(normalized)) {
14211
+ return;
14212
+ }
14213
+ seen.add(normalized);
14214
+ results.push(normalized);
14215
+ };
14216
+ var patterns = [
14217
+ /\bgroup(?:ed)?\s+by\s+([a-z0-9_-]+(?:\s+[a-z0-9_-]+){0,2})(?=\s+(?:by|per|for|of|in|with|and|or)\b|[,.!?;]|$)/gi,
14218
+ /\bbreak(?:\s+up|\s*down)?\b[\s\S]{0,80}?\bby\s+([a-z0-9_-]+(?:\s+[a-z0-9_-]+){0,2})(?=\s+(?:by|per|for|of|in|with|and|or)\b|[,.!?;]|$)/gi,
14219
+ /\b(?:by|per)\s+(?:each\s+)?([a-z0-9_-]+(?:\s+[a-z0-9_-]+){0,2})(?=\s+(?:by|per|for|of|in|with|and|or)\b|[,.!?;]|$)/gi,
14220
+ /\bfor\s+each\s+([a-z0-9_-]+(?:\s+[a-z0-9_-]+){0,2})(?=\s+(?:by|per|for|of|in|with|and|or)\b|[,.!?;]|$)/gi
14221
+ ];
14222
+ patterns.forEach(function (pattern) {
14223
+ var match = pattern.exec(text);
14224
+ while (match) {
14225
+ add(String(match[1] || ''));
14226
+ match = pattern.exec(text);
14227
+ }
14228
+ });
14229
+ return results;
14230
+ }
14231
+ function hasAssistantGroupingMetricCue(message) {
14232
+ var text = normalizeOptionalString(message).toLowerCase();
14233
+ if (!text) {
14234
+ return false;
14235
+ }
14236
+ return /\b(total|count|number|sum|avg|average|hours?|revenue|sales|billing|volume|throughput|breakdown|rank|ranking|top|how\s+many)\b/.test(text)
14237
+ || /\b(last|recent)\s+\d+\b/.test(text);
14238
+ }
13352
14239
  function hasAssistantGroupedLanguage(message) {
13353
14240
  var text = normalizeOptionalString(message).toLowerCase();
13354
14241
  if (!text) {
@@ -13356,17 +14243,29 @@ function hasAssistantGroupedLanguage(message) {
13356
14243
  }
13357
14244
  var patterns = [
13358
14245
  /\bbreakdown\b/i,
14246
+ /\bbreak\s+up\b/i,
13359
14247
  /\bgroup(?:ed)?\s+by\b/i,
13360
- /\bby\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
13361
- /\bper\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
14248
+ /\bby\s+(day|week|month|quarter|year)\b/i,
14249
+ /\bper\s+(day|week|month|quarter|year)\b/i,
13362
14250
  /\bover\s+time\b/i,
13363
14251
  /\btime\s*series\b/i,
13364
14252
  /\btrend(?:ing|s)?\b/i,
13365
14253
  /\bmonth\s+over\s+month\b/i,
13366
14254
  /\bquarter\s+over\s+quarter\b/i,
13367
- /\byear\s+over\s+year\b/i
14255
+ /\byear\s+over\s+year\b/i,
14256
+ /\btop\s+\d+\b[\s\S]{0,60}\bby\b/i
13368
14257
  ];
13369
- return patterns.some(function (pattern) { return pattern.test(text); });
14258
+ if (patterns.some(function (pattern) { return pattern.test(text); })) {
14259
+ return true;
14260
+ }
14261
+ var dimensions = extractAssistantRequestedBreakdownDimensions(text);
14262
+ if (!dimensions.length) {
14263
+ return false;
14264
+ }
14265
+ if (dimensions.length >= 2) {
14266
+ return true;
14267
+ }
14268
+ return hasAssistantGroupingMetricCue(text);
13370
14269
  }
13371
14270
  function shouldPreferAssistantListDirective(message, plannerOutput, requestClassification) {
13372
14271
  var _a, _b, _c, _d, _e;
@@ -13406,6 +14305,17 @@ function shouldEnforceAssistantDatedDirective(message, plannerOutput, requestCla
13406
14305
  }
13407
14306
  return hasAssistantDatedLanguage(message);
13408
14307
  }
14308
+ function shouldEnforceAssistantGroupedDirective(message, plannerOutput, requestClassification) {
14309
+ var _a, _b;
14310
+ if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
14311
+ return false;
14312
+ }
14313
+ 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();
14314
+ if (plannerGroupBy && plannerGroupBy !== 'none' && plannerGroupBy !== 'null') {
14315
+ return true;
14316
+ }
14317
+ return hasAssistantGroupedLanguage(message);
14318
+ }
13409
14319
  function buildAssistantDirectiveStyleHint(params) {
13410
14320
  if (params.preferList && !params.enforceDated) {
13411
14321
  return [
@@ -13415,6 +14325,17 @@ function buildAssistantDirectiveStyleHint(params) {
13415
14325
  '- 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.'
13416
14326
  ].join('\n');
13417
14327
  }
14328
+ var breakdowns = (Array.isArray(params.requestedBreakdowns) ? params.requestedBreakdowns : [])
14329
+ .map(function (value) { return normalizeOptionalString(value); })
14330
+ .filter(Boolean);
14331
+ if (!params.enforceDated && params.enforceGrouped) {
14332
+ return [
14333
+ 'Report style intent: Grouped.',
14334
+ '- Return REPORT_BUILDER_AGG (not REPORT_BUILDER_READ).',
14335
+ breakdowns.length ? "- Requested breakdown dimensions: ".concat(breakdowns.join(', '), ".") : '- Requested breakdown dimensions must be preserved exactly.',
14336
+ params.strict ? '- STRICT: do not return a flat list when grouped dimensions are requested.' : ''
14337
+ ].filter(Boolean).join('\n');
14338
+ }
13418
14339
  if (!params.enforceDated) {
13419
14340
  return '';
13420
14341
  }
@@ -13423,6 +14344,7 @@ function buildAssistantDirectiveStyleHint(params) {
13423
14344
  'Report style intent: Dated.',
13424
14345
  "Requested time grain: ".concat(grainLabel, "."),
13425
14346
  '- Return REPORT_BUILDER_AGG (not REPORT_BUILDER_READ).',
14347
+ breakdowns.length ? "- Requested breakdown dimensions: ".concat(breakdowns.join(', '), ".") : '- Preserve all explicitly requested breakdown dimensions.',
13426
14348
  '- Ensure the pipeline groups by the requested time grain and requested breakdown dimensions.',
13427
14349
  '- For "last/past N" windows, use full completed calendar-period bounds in UTC unless the user asks for period-to-date.',
13428
14350
  params.strict ? '- STRICT: if unsure, still prefer REPORT_BUILDER_AGG.' : ''
@@ -13456,7 +14378,7 @@ function resolveAssistantPlannerEnabled() {
13456
14378
  return raw === undefined ? true : raw === true;
13457
14379
  }
13458
14380
  function resolveAssistantPlannerKnownRoutes() {
13459
- var e_34, _a;
14381
+ var e_37, _a;
13460
14382
  var _b;
13461
14383
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
13462
14384
  var unique = new Set();
@@ -13469,12 +14391,12 @@ function resolveAssistantPlannerKnownRoutes() {
13469
14391
  }
13470
14392
  }
13471
14393
  }
13472
- catch (e_34_1) { e_34 = { error: e_34_1 }; }
14394
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
13473
14395
  finally {
13474
14396
  try {
13475
14397
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
13476
14398
  }
13477
- finally { if (e_34) throw e_34.error; }
14399
+ finally { if (e_37) throw e_37.error; }
13478
14400
  }
13479
14401
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
13480
14402
  }
@@ -13717,7 +14639,7 @@ function normalizeRouteMatchKey(value) {
13717
14639
  return normalizeRouteKey(value).toLowerCase();
13718
14640
  }
13719
14641
  function buildClientRouteIndex() {
13720
- var e_35, _a;
14642
+ var e_38, _a;
13721
14643
  var _b;
13722
14644
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
13723
14645
  var set = new Set();
@@ -13736,12 +14658,12 @@ function buildClientRouteIndex() {
13736
14658
  }
13737
14659
  }
13738
14660
  }
13739
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
14661
+ catch (e_38_1) { e_38 = { error: e_38_1 }; }
13740
14662
  finally {
13741
14663
  try {
13742
14664
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
13743
14665
  }
13744
- finally { if (e_35) throw e_35.error; }
14666
+ finally { if (e_38) throw e_38.error; }
13745
14667
  }
13746
14668
  return { set: set, map: map, size: routes.length };
13747
14669
  }
@@ -14756,7 +15678,7 @@ function sanitizeAssistantResponse(value) {
14756
15678
  return normalizeAssistantRoutes(normalizedCurrency);
14757
15679
  }
14758
15680
  function evaluateAssistantGuardrails(message) {
14759
- var e_36, _a;
15681
+ var e_39, _a;
14760
15682
  var normalized = String(message || '').toLowerCase();
14761
15683
  var patterns = [
14762
15684
  {
@@ -14802,12 +15724,12 @@ function evaluateAssistantGuardrails(message) {
14802
15724
  }
14803
15725
  }
14804
15726
  }
14805
- catch (e_36_1) { e_36 = { error: e_36_1 }; }
15727
+ catch (e_39_1) { e_39 = { error: e_39_1 }; }
14806
15728
  finally {
14807
15729
  try {
14808
15730
  if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
14809
15731
  }
14810
- finally { if (e_36) throw e_36.error; }
15732
+ finally { if (e_39) throw e_39.error; }
14811
15733
  }
14812
15734
  return null;
14813
15735
  }
@@ -14922,7 +15844,7 @@ function tokenizeArithmeticExpression(expression) {
14922
15844
  return tokens;
14923
15845
  }
14924
15846
  function evaluateArithmeticExpression(expression) {
14925
- var e_37, _a, e_38, _b;
15847
+ var e_40, _a, e_41, _b;
14926
15848
  var tokens = tokenizeArithmeticExpression(expression);
14927
15849
  if (!tokens || !tokens.length) {
14928
15850
  return null;
@@ -14946,8 +15868,8 @@ function evaluateArithmeticExpression(expression) {
14946
15868
  ops.push(op);
14947
15869
  };
14948
15870
  try {
14949
- for (var tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next(); !tokens_1_1.done; tokens_1_1 = tokens_1.next()) {
14950
- var token = tokens_1_1.value;
15871
+ for (var tokens_2 = __values(tokens), tokens_2_1 = tokens_2.next(); !tokens_2_1.done; tokens_2_1 = tokens_2.next()) {
15872
+ var token = tokens_2_1.value;
14951
15873
  if (token === '(') {
14952
15874
  ops.push(token);
14953
15875
  prevToken = token;
@@ -14979,12 +15901,12 @@ function evaluateArithmeticExpression(expression) {
14979
15901
  prevToken = token;
14980
15902
  }
14981
15903
  }
14982
- catch (e_37_1) { e_37 = { error: e_37_1 }; }
15904
+ catch (e_40_1) { e_40 = { error: e_40_1 }; }
14983
15905
  finally {
14984
15906
  try {
14985
- if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
15907
+ if (tokens_2_1 && !tokens_2_1.done && (_a = tokens_2.return)) _a.call(tokens_2);
14986
15908
  }
14987
- finally { if (e_37) throw e_37.error; }
15909
+ finally { if (e_40) throw e_40.error; }
14988
15910
  }
14989
15911
  while (ops.length) {
14990
15912
  var op = ops.pop();
@@ -15024,12 +15946,12 @@ function evaluateArithmeticExpression(expression) {
15024
15946
  stack.push(Number(token));
15025
15947
  }
15026
15948
  }
15027
- catch (e_38_1) { e_38 = { error: e_38_1 }; }
15949
+ catch (e_41_1) { e_41 = { error: e_41_1 }; }
15028
15950
  finally {
15029
15951
  try {
15030
15952
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
15031
15953
  }
15032
- finally { if (e_38) throw e_38.error; }
15954
+ finally { if (e_41) throw e_41.error; }
15033
15955
  }
15034
15956
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
15035
15957
  return null;
@@ -15213,8 +16135,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
15213
16135
  }
15214
16136
  function readAttachmentContents(attachments) {
15215
16137
  return __awaiter(this, void 0, void 0, function () {
15216
- var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_39_1;
15217
- var e_39, _b;
16138
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_42_1;
16139
+ var e_42, _b;
15218
16140
  return __generator(this, function (_c) {
15219
16141
  switch (_c.label) {
15220
16142
  case 0:
@@ -15293,14 +16215,14 @@ function readAttachmentContents(attachments) {
15293
16215
  return [3 /*break*/, 2];
15294
16216
  case 10: return [3 /*break*/, 13];
15295
16217
  case 11:
15296
- e_39_1 = _c.sent();
15297
- e_39 = { error: e_39_1 };
16218
+ e_42_1 = _c.sent();
16219
+ e_42 = { error: e_42_1 };
15298
16220
  return [3 /*break*/, 13];
15299
16221
  case 12:
15300
16222
  try {
15301
16223
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
15302
16224
  }
15303
- finally { if (e_39) throw e_39.error; }
16225
+ finally { if (e_42) throw e_42.error; }
15304
16226
  return [7 /*endfinally*/];
15305
16227
  case 13: return [2 /*return*/, {
15306
16228
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -15455,7 +16377,7 @@ function resolveAssistantDatabaseNameForSystemCollections() {
15455
16377
  }
15456
16378
  function updateAssistantMessageWithFallback(messageId, setPayload) {
15457
16379
  return __awaiter(this, void 0, void 0, function () {
15458
- var error_7, dbName, _a;
16380
+ var error_8, dbName, _a;
15459
16381
  return __generator(this, function (_b) {
15460
16382
  switch (_b.label) {
15461
16383
  case 0:
@@ -15470,9 +16392,9 @@ function updateAssistantMessageWithFallback(messageId, setPayload) {
15470
16392
  _b.sent();
15471
16393
  return [2 /*return*/];
15472
16394
  case 3:
15473
- error_7 = _b.sent();
15474
- if (!isAssistantTransactionCommittedError(error_7)) {
15475
- throw error_7;
16395
+ error_8 = _b.sent();
16396
+ if (!isAssistantTransactionCommittedError(error_8)) {
16397
+ throw error_8;
15476
16398
  }
15477
16399
  dbName = resolveAssistantDatabaseNameForSystemCollections();
15478
16400
  _b.label = 4;
@@ -15502,7 +16424,7 @@ function updateAssistantMessageWithFallback(messageId, setPayload) {
15502
16424
  }
15503
16425
  function touchConversation(idConversation, timestamp, lastMessageId) {
15504
16426
  return __awaiter(this, void 0, void 0, function () {
15505
- var update, error_8, dbName;
16427
+ var update, error_9, dbName;
15506
16428
  return __generator(this, function (_a) {
15507
16429
  switch (_a.label) {
15508
16430
  case 0:
@@ -15521,9 +16443,9 @@ function touchConversation(idConversation, timestamp, lastMessageId) {
15521
16443
  _a.sent();
15522
16444
  return [2 /*return*/];
15523
16445
  case 3:
15524
- error_8 = _a.sent();
15525
- if (!isAssistantTransactionCommittedError(error_8)) {
15526
- throw error_8;
16446
+ error_9 = _a.sent();
16447
+ if (!isAssistantTransactionCommittedError(error_9)) {
16448
+ throw error_9;
15527
16449
  }
15528
16450
  dbName = resolveAssistantDatabaseNameForSystemCollections();
15529
16451
  return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMongoConnection()
@@ -15624,7 +16546,7 @@ function estimateUsage(messages, responseText, model) {
15624
16546
  };
15625
16547
  }
15626
16548
  function evaluateGuardrails(message) {
15627
- var e_40, _a;
16549
+ var e_43, _a;
15628
16550
  var normalized = String(message || '').toLowerCase();
15629
16551
  var patterns = [
15630
16552
  { 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.' },
@@ -15646,12 +16568,12 @@ function evaluateGuardrails(message) {
15646
16568
  }
15647
16569
  }
15648
16570
  }
15649
- catch (e_40_1) { e_40 = { error: e_40_1 }; }
16571
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
15650
16572
  finally {
15651
16573
  try {
15652
16574
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
15653
16575
  }
15654
- finally { if (e_40) throw e_40.error; }
16576
+ finally { if (e_43) throw e_43.error; }
15655
16577
  }
15656
16578
  return null;
15657
16579
  }