@resolveio/server-lib 22.1.27 → 22.1.29

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.
@@ -1614,6 +1614,15 @@ function executeAiAssistantCodexRun(payload, context) {
1614
1614
  user = _d.sent();
1615
1615
  isSuperAdmin = !!((_a = user === null || user === void 0 ? void 0 : user.roles) === null || _a === void 0 ? void 0 : _a.super_admin);
1616
1616
  canViewDebug = isAssistantDebugUser(user);
1617
+ if (shouldLogAssistantFinalizeDebug()) {
1618
+ console.log(new Date(), '[AI-Dashboard][AI-Assistant] debug-visibility', {
1619
+ requestId: requestId || null,
1620
+ id_user: (context === null || context === void 0 ? void 0 : context.id_user) || null,
1621
+ username: normalizeOptionalString(user === null || user === void 0 ? void 0 : user.username) || null,
1622
+ isSuperAdmin: isSuperAdmin,
1623
+ canViewDebug: canViewDebug
1624
+ });
1625
+ }
1617
1626
  hasInvoiceAccess = userHasInvoiceAccess(user);
1618
1627
  customerId = normalizeOptionalString((_b = user === null || user === void 0 ? void 0 : user.other) === null || _b === void 0 ? void 0 : _b.id_customer);
1619
1628
  return [4 /*yield*/, ensureConversation(input, 'codex', context === null || context === void 0 ? void 0 : context.id_user)];
@@ -1754,10 +1763,10 @@ function executeAiAssistantCodexRun(payload, context) {
1754
1763
  insertResult = _d.sent();
1755
1764
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1756
1765
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1757
- 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, methodHints, publicationHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerUsed, plannerSkipReason, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, surfaceHints, _a, allowedRoutes, rankedAllowedRoutes, routeHints, rankedCollectionHints, rankedCollections, hintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, plannerRunOptions, 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, allowCollectionOverride, cleanedResponseText, deniedModuleByIntent, permissionLabel, 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;
1758
- 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;
1759
- return __generator(this, function (_13) {
1760
- switch (_13.label) {
1766
+ 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, methodHints, publicationHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerUsed, plannerSkipReason, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, surfaceHints, _a, allowedRoutes, rankedAllowedRoutes, routeHints, rankedCollectionHints, rankedCollections, hintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, plannerRunOptions, 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, allowCollectionOverride, cleanedResponseText, deniedModuleByIntent, permissionLabel, 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, finalizeError_1, failedAt, fallbackContent, failureMetadata, persistError_1, _k;
1767
+ var _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, _13;
1768
+ return __generator(this, function (_14) {
1769
+ switch (_14.label) {
1761
1770
  case 0:
1762
1771
  runStart = Date.now();
1763
1772
  if (aiWorkerDebug) {
@@ -1837,8 +1846,8 @@ function executeAiAssistantCodexRun(payload, context) {
1837
1846
  codexUsage.output_tokens += outputTokens;
1838
1847
  codexUsage.total_tokens += inputTokens + outputTokens;
1839
1848
  };
1840
- contextRoute = normalizeOptionalString((_k = input === null || input === void 0 ? void 0 : input.context) === null || _k === void 0 ? void 0 : _k.route);
1841
- contextMode = normalizeOptionalString((_l = input === null || input === void 0 ? void 0 : input.context) === null || _l === void 0 ? void 0 : _l.mode);
1849
+ contextRoute = normalizeOptionalString((_l = input === null || input === void 0 ? void 0 : input.context) === null || _l === void 0 ? void 0 : _l.route);
1850
+ contextMode = normalizeOptionalString((_m = input === null || input === void 0 ? void 0 : input.context) === null || _m === void 0 ? void 0 : _m.mode);
1842
1851
  recordStep('Queued', { requestId: requestId || undefined });
1843
1852
  if (changeHistoryFastPathBypassedReason) {
1844
1853
  recordStep('Planning: change-history fast path unavailable', {
@@ -1850,9 +1859,9 @@ function executeAiAssistantCodexRun(payload, context) {
1850
1859
  source: requestClassification.source,
1851
1860
  dataQuestion: dataQuestion
1852
1861
  });
1853
- _13.label = 1;
1862
+ _14.label = 1;
1854
1863
  case 1:
1855
- _13.trys.push([1, 53, 54, 55]);
1864
+ _14.trys.push([1, 53, 54, 55]);
1856
1865
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1857
1866
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1858
1867
  hintText = termExpansion.expanded || hintSeed;
@@ -1873,19 +1882,19 @@ function executeAiAssistantCodexRun(payload, context) {
1873
1882
  recordStep('Planning: term expansion', {
1874
1883
  termMatches: termExpansion.matches.length ? termExpansion.matches : undefined
1875
1884
  });
1876
- _13.label = 2;
1885
+ _14.label = 2;
1877
1886
  case 2:
1878
- _13.trys.push([2, 5, , 6]);
1887
+ _14.trys.push([2, 5, , 6]);
1879
1888
  dbName = resolveAssistantDatabaseName(undefined, input.mongo);
1880
1889
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
1881
1890
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
1882
1891
  case 3:
1883
- collectionNames = _13.sent();
1892
+ collectionNames = _14.sent();
1884
1893
  collectionHints = resolveCollectionHintsFromTokens(expandedTokens, collectionNames, 5);
1885
1894
  collectionRanking = buildCollectionRankingDebugFromTokens(expandedTokens, collectionNames, 8);
1886
1895
  return [4 /*yield*/, resolveAssistantSurfaceHints(hintSeed, contextRoute, collectionNames)];
1887
1896
  case 4:
1888
- surfaceHints = _13.sent();
1897
+ surfaceHints = _14.sent();
1889
1898
  methodHints = surfaceHints.methodHints;
1890
1899
  publicationHints = surfaceHints.publicationHints;
1891
1900
  if (surfaceHints.collectionHints.length) {
@@ -1893,7 +1902,7 @@ function executeAiAssistantCodexRun(payload, context) {
1893
1902
  }
1894
1903
  return [3 /*break*/, 6];
1895
1904
  case 5:
1896
- _a = _13.sent();
1905
+ _a = _14.sent();
1897
1906
  collectionHints = [];
1898
1907
  collectionRanking = collectionRanking || ((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens)
1899
1908
  ? buildCollectionRankingDebugFromTokens(collectionTokenization.expandedTokens || [], [], 0)
@@ -1956,14 +1965,14 @@ function executeAiAssistantCodexRun(payload, context) {
1956
1965
  if (hasDeterministicHeuristicFastPath) {
1957
1966
  recordStep('Planning: heuristic directive fast path', {
1958
1967
  type: heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.type,
1959
- collection: normalizeOptionalString((_m = heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.payload) === null || _m === void 0 ? void 0 : _m.collection) || undefined,
1968
+ collection: normalizeOptionalString((_o = heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.payload) === null || _o === void 0 ? void 0 : _o.collection) || undefined,
1960
1969
  heuristic: normalizeOptionalString(heuristicDirectivePrecomputed === null || heuristicDirectivePrecomputed === void 0 ? void 0 : heuristicDirectivePrecomputed.rawLine) || undefined
1961
1970
  });
1962
1971
  }
1963
1972
  prompt_1 = buildAssistantCodexPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext);
1964
1973
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
1965
1974
  case 7:
1966
- workspaceRoot = _13.sent();
1975
+ workspaceRoot = _14.sent();
1967
1976
  codexConfig = resolveCodexSettings({
1968
1977
  model: codexModel,
1969
1978
  fallbackModels: codexFallbackModels
@@ -2010,20 +2019,20 @@ function executeAiAssistantCodexRun(payload, context) {
2010
2019
  publicationHints: publicationHints,
2011
2020
  inputClientId: input.id_client
2012
2021
  });
2013
- _13.label = 8;
2022
+ _14.label = 8;
2014
2023
  case 8:
2015
- _13.trys.push([8, 10, , 11]);
2024
+ _14.trys.push([8, 10, , 11]);
2016
2025
  plannerStart = Date.now();
2017
2026
  return [4 /*yield*/, runCodexInWorkerThread(plannerPrompt, plannerRunOptions, codexConfig, streamProgress)];
2018
2027
  case 9:
2019
- plannerRaw = _13.sent();
2028
+ plannerRaw = _14.sent();
2020
2029
  accumulateCodexUsage(plannerPrompt, plannerRaw);
2021
2030
  timingBreakdown.plannerMs = Date.now() - plannerStart;
2022
2031
  plannerOutput = parseJsonObject(plannerRaw);
2023
2032
  recordStep('Planning: planner result', { parsed: !!plannerOutput });
2024
2033
  return [3 /*break*/, 11];
2025
2034
  case 10:
2026
- _b = _13.sent();
2035
+ _b = _14.sent();
2027
2036
  recordStep('Planning: planner result', { parsed: false });
2028
2037
  return [3 /*break*/, 11];
2029
2038
  case 11: return [3 /*break*/, 13];
@@ -2040,7 +2049,7 @@ function executeAiAssistantCodexRun(payload, context) {
2040
2049
  }
2041
2050
  recordStep('Planning: planner skipped', { reason: plannerSkipReason });
2042
2051
  }
2043
- _13.label = 13;
2052
+ _14.label = 13;
2044
2053
  case 13:
2045
2054
  requestClassification = classifyAssistantRequestType(message, plannerOutput || undefined);
2046
2055
  dataQuestion = requestClassification.dataQuestion;
@@ -2082,12 +2091,12 @@ function executeAiAssistantCodexRun(payload, context) {
2082
2091
  directiveSource = 'forced';
2083
2092
  lastDirective = heuristicDirectiveFastPath;
2084
2093
  usedDeterministicHeuristicFastPath = true;
2085
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_o = directive.payload) === null || _o === void 0 ? void 0 : _o.collection) || '');
2094
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || '');
2086
2095
  recordStep('Directive resolved', {
2087
2096
  source: directiveSource,
2088
2097
  type: directive.type,
2089
- collection: normalizeOptionalString((_p = directive.payload) === null || _p === void 0 ? void 0 : _p.collection) || undefined,
2090
- permissionView: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.permissionView) || undefined,
2098
+ collection: normalizeOptionalString((_q = directive.payload) === null || _q === void 0 ? void 0 : _q.collection) || undefined,
2099
+ permissionView: normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.permissionView) || undefined,
2091
2100
  reportStyle: 'heuristic_fast_path',
2092
2101
  timeGrain: requestedTimeGrain || undefined
2093
2102
  });
@@ -2095,13 +2104,13 @@ function executeAiAssistantCodexRun(payload, context) {
2095
2104
  if (!(dataQuestion && !directive)) return [3 /*break*/, 17];
2096
2105
  recordStep('Directive: determine tool', { type: 'data-question' });
2097
2106
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
2098
- _13.label = 14;
2107
+ _14.label = 14;
2099
2108
  case 14:
2100
- _13.trys.push([14, 16, , 17]);
2109
+ _14.trys.push([14, 16, , 17]);
2101
2110
  directiveStart = Date.now();
2102
2111
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
2103
2112
  case 15:
2104
- directiveText = _13.sent();
2113
+ directiveText = _14.sent();
2105
2114
  accumulateCodexUsage(directivePrompt, directiveText);
2106
2115
  timingBreakdown.directiveMs = Date.now() - directiveStart;
2107
2116
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -2109,28 +2118,28 @@ function executeAiAssistantCodexRun(payload, context) {
2109
2118
  directive = forcedDirective;
2110
2119
  directiveSource = 'model';
2111
2120
  lastDirective = forcedDirective;
2112
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_r = directive.payload) === null || _r === void 0 ? void 0 : _r.collection) || '');
2121
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || '');
2113
2122
  recordStep('Directive resolved', {
2114
2123
  source: directiveSource,
2115
2124
  type: directive.type,
2116
- collection: normalizeOptionalString((_s = directive.payload) === null || _s === void 0 ? void 0 : _s.collection) || undefined,
2117
- permissionView: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.permissionView) || undefined
2125
+ collection: normalizeOptionalString((_t = directive.payload) === null || _t === void 0 ? void 0 : _t.collection) || undefined,
2126
+ permissionView: normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.permissionView) || undefined
2118
2127
  });
2119
2128
  }
2120
2129
  return [3 /*break*/, 17];
2121
2130
  case 16:
2122
- _c = _13.sent();
2131
+ _c = _14.sent();
2123
2132
  return [3 /*break*/, 17];
2124
2133
  case 17:
2125
2134
  if (!(!directive && !dataQuestion)) return [3 /*break*/, 21];
2126
2135
  recordStep('Response: draft initial answer', { mode: 'full' });
2127
- _13.label = 18;
2136
+ _14.label = 18;
2128
2137
  case 18:
2129
- _13.trys.push([18, 20, , 21]);
2138
+ _14.trys.push([18, 20, , 21]);
2130
2139
  initialStart = Date.now();
2131
2140
  return [4 /*yield*/, runCodexInWorkerThread(prompt_1, runOptions, codexConfig, streamProgress)];
2132
2141
  case 19:
2133
- responseText = _13.sent();
2142
+ responseText = _14.sent();
2134
2143
  accumulateCodexUsage(prompt_1, responseText);
2135
2144
  timingBreakdown.initialResponseMs = Date.now() - initialStart;
2136
2145
  extractedDirective = extractAssistantMongoDirective(responseText);
@@ -2138,17 +2147,17 @@ function executeAiAssistantCodexRun(payload, context) {
2138
2147
  if (directive) {
2139
2148
  directiveSource = 'model';
2140
2149
  lastDirective = directive;
2141
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_u = directive.payload) === null || _u === void 0 ? void 0 : _u.collection) || '');
2150
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || '');
2142
2151
  recordStep('Directive resolved', {
2143
2152
  source: directiveSource,
2144
2153
  type: directive.type,
2145
- collection: normalizeOptionalString((_v = directive.payload) === null || _v === void 0 ? void 0 : _v.collection) || undefined,
2146
- permissionView: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.permissionView) || undefined
2154
+ collection: normalizeOptionalString((_w = directive.payload) === null || _w === void 0 ? void 0 : _w.collection) || undefined,
2155
+ permissionView: normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.permissionView) || undefined
2147
2156
  });
2148
2157
  }
2149
2158
  return [3 /*break*/, 21];
2150
2159
  case 20:
2151
- error_2 = _13.sent();
2160
+ error_2 = _14.sent();
2152
2161
  recordStep('Response: initial draft failed', {
2153
2162
  message: normalizeOptionalString(error_2 === null || error_2 === void 0 ? void 0 : error_2.message) || 'Unknown error'
2154
2163
  });
@@ -2157,13 +2166,13 @@ function executeAiAssistantCodexRun(payload, context) {
2157
2166
  if (!(!directive && dataQuestion)) return [3 /*break*/, 25];
2158
2167
  recordStep('Directive: forced retry', { mode: 'directive-only' });
2159
2168
  directivePrompt = buildAssistantCodexDirectivePrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, directiveStyleHint, directivePromptMode);
2160
- _13.label = 22;
2169
+ _14.label = 22;
2161
2170
  case 22:
2162
- _13.trys.push([22, 24, , 25]);
2171
+ _14.trys.push([22, 24, , 25]);
2163
2172
  forcedStart = Date.now();
2164
2173
  return [4 /*yield*/, runCodexInWorkerThread(directivePrompt, runOptions, codexConfig, streamProgress)];
2165
2174
  case 23:
2166
- directiveText = _13.sent();
2175
+ directiveText = _14.sent();
2167
2176
  accumulateCodexUsage(directivePrompt, directiveText);
2168
2177
  timingBreakdown.forcedDirectiveMs = Date.now() - forcedStart;
2169
2178
  forcedDirective = extractAssistantMongoDirective(directiveText);
@@ -2171,17 +2180,17 @@ function executeAiAssistantCodexRun(payload, context) {
2171
2180
  directive = forcedDirective;
2172
2181
  directiveSource = 'forced';
2173
2182
  lastDirective = forcedDirective;
2174
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_x = directive.payload) === null || _x === void 0 ? void 0 : _x.collection) || '');
2183
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || '');
2175
2184
  recordStep('Directive resolved', {
2176
2185
  source: directiveSource,
2177
2186
  type: directive.type,
2178
- collection: normalizeOptionalString((_y = directive.payload) === null || _y === void 0 ? void 0 : _y.collection) || undefined,
2179
- permissionView: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.permissionView) || undefined
2187
+ collection: normalizeOptionalString((_z = directive.payload) === null || _z === void 0 ? void 0 : _z.collection) || undefined,
2188
+ permissionView: normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.permissionView) || undefined
2180
2189
  });
2181
2190
  }
2182
2191
  return [3 /*break*/, 25];
2183
2192
  case 24:
2184
- _d = _13.sent();
2193
+ _d = _14.sent();
2185
2194
  return [3 /*break*/, 25];
2186
2195
  case 25:
2187
2196
  if (!(directive
@@ -2199,13 +2208,13 @@ function executeAiAssistantCodexRun(payload, context) {
2199
2208
  requestedBreakdowns: requestedBreakdownDimensions,
2200
2209
  strict: true
2201
2210
  }), 'aggregate_only');
2202
- _13.label = 26;
2211
+ _14.label = 26;
2203
2212
  case 26:
2204
- _13.trys.push([26, 28, , 29]);
2213
+ _14.trys.push([26, 28, , 29]);
2205
2214
  strictStart = Date.now();
2206
2215
  return [4 /*yield*/, runCodexInWorkerThread(strictDirectivePrompt, runOptions, codexConfig, streamProgress)];
2207
2216
  case 27:
2208
- strictDirectiveText = _13.sent();
2217
+ strictDirectiveText = _14.sent();
2209
2218
  accumulateCodexUsage(strictDirectivePrompt, strictDirectiveText);
2210
2219
  timingBreakdown.forcedDirectiveMs += Date.now() - strictStart;
2211
2220
  strictDirective = extractAssistantMongoDirective(strictDirectiveText);
@@ -2216,19 +2225,19 @@ function executeAiAssistantCodexRun(payload, context) {
2216
2225
  directiveSource = 'forced';
2217
2226
  lastDirective = strictDirective;
2218
2227
  datedDirectiveRetryUsed = true;
2219
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_0 = directive.payload) === null || _0 === void 0 ? void 0 : _0.collection) || '');
2228
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection) || '');
2220
2229
  recordStep('Directive resolved', {
2221
2230
  source: directiveSource,
2222
2231
  type: directive.type,
2223
- collection: normalizeOptionalString((_1 = directive.payload) === null || _1 === void 0 ? void 0 : _1.collection) || undefined,
2224
- permissionView: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.permissionView) || undefined,
2232
+ collection: normalizeOptionalString((_2 = directive.payload) === null || _2 === void 0 ? void 0 : _2.collection) || undefined,
2233
+ permissionView: normalizeOptionalString((_3 = directive.payload) === null || _3 === void 0 ? void 0 : _3.permissionView) || undefined,
2225
2234
  reportStyle: strictDirectiveIsDated ? 'dated' : 'aggregate_fallback',
2226
2235
  timeGrain: requestedTimeGrain || undefined
2227
2236
  });
2228
2237
  }
2229
2238
  return [3 /*break*/, 29];
2230
2239
  case 28:
2231
- _e = _13.sent();
2240
+ _e = _14.sent();
2232
2241
  return [3 /*break*/, 29];
2233
2242
  case 29:
2234
2243
  if (!(directive
@@ -2246,13 +2255,13 @@ function executeAiAssistantCodexRun(payload, context) {
2246
2255
  requestedBreakdowns: requestedBreakdownDimensions,
2247
2256
  strict: true
2248
2257
  }), 'aggregate_only');
2249
- _13.label = 30;
2258
+ _14.label = 30;
2250
2259
  case 30:
2251
- _13.trys.push([30, 32, , 33]);
2260
+ _14.trys.push([30, 32, , 33]);
2252
2261
  guardStart = Date.now();
2253
2262
  return [4 /*yield*/, runCodexInWorkerThread(guardDirectivePrompt, runOptions, codexConfig, streamProgress)];
2254
2263
  case 31:
2255
- guardDirectiveText = _13.sent();
2264
+ guardDirectiveText = _14.sent();
2256
2265
  accumulateCodexUsage(guardDirectivePrompt, guardDirectiveText);
2257
2266
  timingBreakdown.forcedDirectiveMs += Date.now() - guardStart;
2258
2267
  guardDirective = extractAssistantMongoDirective(guardDirectiveText);
@@ -2261,19 +2270,19 @@ function executeAiAssistantCodexRun(payload, context) {
2261
2270
  directiveSource = 'forced';
2262
2271
  lastDirective = guardDirective;
2263
2272
  datedDirectiveRetryUsed = true;
2264
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_3 = directive.payload) === null || _3 === void 0 ? void 0 : _3.collection) || '');
2273
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_4 = directive.payload) === null || _4 === void 0 ? void 0 : _4.collection) || '');
2265
2274
  recordStep('Directive resolved', {
2266
2275
  source: directiveSource,
2267
2276
  type: directive.type,
2268
- collection: normalizeOptionalString((_4 = directive.payload) === null || _4 === void 0 ? void 0 : _4.collection) || undefined,
2269
- permissionView: normalizeOptionalString((_5 = directive.payload) === null || _5 === void 0 ? void 0 : _5.permissionView) || undefined,
2277
+ collection: normalizeOptionalString((_5 = directive.payload) === null || _5 === void 0 ? void 0 : _5.collection) || undefined,
2278
+ permissionView: normalizeOptionalString((_6 = directive.payload) === null || _6 === void 0 ? void 0 : _6.permissionView) || undefined,
2270
2279
  reportStyle: isAssistantDirectiveDated(guardDirective) ? 'dated' : 'aggregate_fallback',
2271
2280
  timeGrain: requestedTimeGrain || undefined
2272
2281
  });
2273
2282
  }
2274
2283
  return [3 /*break*/, 33];
2275
2284
  case 32:
2276
- _f = _13.sent();
2285
+ _f = _14.sent();
2277
2286
  return [3 /*break*/, 33];
2278
2287
  case 33:
2279
2288
  if (!(directive
@@ -2291,13 +2300,13 @@ function executeAiAssistantCodexRun(payload, context) {
2291
2300
  requestedBreakdowns: requestedBreakdownDimensions,
2292
2301
  strict: true
2293
2302
  }), 'aggregate_only');
2294
- _13.label = 34;
2303
+ _14.label = 34;
2295
2304
  case 34:
2296
- _13.trys.push([34, 36, , 37]);
2305
+ _14.trys.push([34, 36, , 37]);
2297
2306
  groupedStart = Date.now();
2298
2307
  return [4 /*yield*/, runCodexInWorkerThread(groupedDirectivePrompt, runOptions, codexConfig, streamProgress)];
2299
2308
  case 35:
2300
- groupedDirectiveText = _13.sent();
2309
+ groupedDirectiveText = _14.sent();
2301
2310
  accumulateCodexUsage(groupedDirectivePrompt, groupedDirectiveText);
2302
2311
  timingBreakdown.forcedDirectiveMs += Date.now() - groupedStart;
2303
2312
  groupedDirective = extractAssistantMongoDirective(groupedDirectiveText);
@@ -2306,12 +2315,12 @@ function executeAiAssistantCodexRun(payload, context) {
2306
2315
  directiveSource = 'forced';
2307
2316
  lastDirective = groupedDirective;
2308
2317
  datedDirectiveRetryUsed = true;
2309
- collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_6 = directive.payload) === null || _6 === void 0 ? void 0 : _6.collection) || '');
2318
+ collectionSelection = buildCollectionSelectionDetail((collectionTokenization === null || collectionTokenization === void 0 ? void 0 : collectionTokenization.expandedTokens) || [], normalizeOptionalString((_7 = directive.payload) === null || _7 === void 0 ? void 0 : _7.collection) || '');
2310
2319
  recordStep('Directive resolved', {
2311
2320
  source: directiveSource,
2312
2321
  type: directive.type,
2313
- collection: normalizeOptionalString((_7 = directive.payload) === null || _7 === void 0 ? void 0 : _7.collection) || undefined,
2314
- permissionView: normalizeOptionalString((_8 = directive.payload) === null || _8 === void 0 ? void 0 : _8.permissionView) || undefined,
2322
+ collection: normalizeOptionalString((_8 = directive.payload) === null || _8 === void 0 ? void 0 : _8.collection) || undefined,
2323
+ permissionView: normalizeOptionalString((_9 = directive.payload) === null || _9 === void 0 ? void 0 : _9.permissionView) || undefined,
2315
2324
  reportStyle: isAssistantDirectiveDated(groupedDirective)
2316
2325
  ? 'dated'
2317
2326
  : 'grouped',
@@ -2321,7 +2330,7 @@ function executeAiAssistantCodexRun(payload, context) {
2321
2330
  }
2322
2331
  return [3 /*break*/, 37];
2323
2332
  case 36:
2324
- _g = _13.sent();
2333
+ _g = _14.sent();
2325
2334
  return [3 /*break*/, 37];
2326
2335
  case 37:
2327
2336
  if (!directive && dataQuestion) {
@@ -2333,21 +2342,21 @@ function executeAiAssistantCodexRun(payload, context) {
2333
2342
  recordStep('Directive resolved', {
2334
2343
  source: directiveSource,
2335
2344
  type: directive.type,
2336
- collection: normalizeOptionalString((_9 = directive.payload) === null || _9 === void 0 ? void 0 : _9.collection) || undefined,
2337
- permissionView: normalizeOptionalString((_10 = directive.payload) === null || _10 === void 0 ? void 0 : _10.permissionView) || undefined,
2345
+ collection: normalizeOptionalString((_10 = directive.payload) === null || _10 === void 0 ? void 0 : _10.collection) || undefined,
2346
+ permissionView: normalizeOptionalString((_11 = directive.payload) === null || _11 === void 0 ? void 0 : _11.permissionView) || undefined,
2338
2347
  reportStyle: 'heuristic_fallback'
2339
2348
  });
2340
2349
  }
2341
2350
  }
2342
2351
  if (directive) {
2343
- requestedCollection = normalizeOptionalString((_11 = directive.payload) === null || _11 === void 0 ? void 0 : _11.collection);
2352
+ requestedCollection = normalizeOptionalString((_12 = directive.payload) === null || _12 === void 0 ? void 0 : _12.collection);
2344
2353
  allowCollectionOverride = !isAssistantDeterministicHeuristicDirective(directive);
2345
2354
  collectionOverride = allowCollectionOverride
2346
2355
  ? resolveCollectionOverrideWithContext({
2347
2356
  message: message,
2348
2357
  collectionRanking: collectionRanking,
2349
2358
  requestedCollection: requestedCollection,
2350
- permissionView: normalizeOptionalString((_12 = directive.payload) === null || _12 === void 0 ? void 0 : _12.permissionView) || contextRoute,
2359
+ permissionView: normalizeOptionalString((_13 = directive.payload) === null || _13 === void 0 ? void 0 : _13.permissionView) || contextRoute,
2351
2360
  collectionNames: collectionNames
2352
2361
  })
2353
2362
  : null;
@@ -2390,19 +2399,19 @@ function executeAiAssistantCodexRun(payload, context) {
2390
2399
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
2391
2400
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
2392
2401
  });
2393
- _13.label = 39;
2402
+ _14.label = 39;
2394
2403
  case 39:
2395
- _13.trys.push([39, 49, , 50]);
2404
+ _14.trys.push([39, 49, , 50]);
2396
2405
  toolStart = Date.now();
2397
2406
  if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 41];
2398
2407
  return [4 /*yield*/, executeAiAssistantReportBuilderAggregate(toolRequest, context)];
2399
2408
  case 40:
2400
- _h = _13.sent();
2409
+ _h = _14.sent();
2401
2410
  return [3 /*break*/, 43];
2402
2411
  case 41: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
2403
2412
  case 42:
2404
- _h = _13.sent();
2405
- _13.label = 43;
2413
+ _h = _14.sent();
2414
+ _14.label = 43;
2406
2415
  case 43:
2407
2416
  toolResponse = _h;
2408
2417
  timingBreakdown.toolMs = Date.now() - toolStart;
@@ -2429,26 +2438,26 @@ function executeAiAssistantCodexRun(payload, context) {
2429
2438
  case 44:
2430
2439
  recordStep('Drafting response');
2431
2440
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
2432
- _13.label = 45;
2441
+ _14.label = 45;
2433
2442
  case 45:
2434
- _13.trys.push([45, 47, , 48]);
2443
+ _14.trys.push([45, 47, , 48]);
2435
2444
  followupStart = Date.now();
2436
2445
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
2437
2446
  case 46:
2438
- followupText = _13.sent();
2447
+ followupText = _14.sent();
2439
2448
  accumulateCodexUsage(followupPrompt, followupText);
2440
2449
  timingBreakdown.followupMs = Date.now() - followupStart;
2441
2450
  assistantContent = sanitizeAssistantResponse(followupText);
2442
2451
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2443
2452
  return [3 /*break*/, 48];
2444
2453
  case 47:
2445
- _j = _13.sent();
2454
+ _j = _14.sent();
2446
2455
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
2447
2456
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2448
2457
  return [3 /*break*/, 48];
2449
2458
  case 48: return [3 /*break*/, 50];
2450
2459
  case 49:
2451
- error_3 = _13.sent();
2460
+ error_3 = _14.sent();
2452
2461
  assistantContent = buildAssistantToolErrorMessage(error_3);
2453
2462
  toolError = error_3;
2454
2463
  return [3 /*break*/, 50];
@@ -2456,10 +2465,10 @@ function executeAiAssistantCodexRun(payload, context) {
2456
2465
  case 51:
2457
2466
  progressTracker.push('Drafting response');
2458
2467
  recordStep('Drafting response');
2459
- _13.label = 52;
2468
+ _14.label = 52;
2460
2469
  case 52: return [3 /*break*/, 55];
2461
2470
  case 53:
2462
- error_4 = _13.sent();
2471
+ error_4 = _14.sent();
2463
2472
  assistantContent = buildAssistantCodexErrorMessage(error_4);
2464
2473
  recordStep('Error', { message: normalizeOptionalString(error_4 === null || error_4 === void 0 ? void 0 : error_4.message) || 'Unknown error' });
2465
2474
  return [3 /*break*/, 55];
@@ -2490,6 +2499,9 @@ function executeAiAssistantCodexRun(payload, context) {
2490
2499
  });
2491
2500
  }
2492
2501
  finalNow = new Date();
2502
+ _14.label = 56;
2503
+ case 56:
2504
+ _14.trys.push([56, 67, , 78]);
2493
2505
  if (canViewDebug) {
2494
2506
  finishedAt = Date.now();
2495
2507
  codexMs = timingBreakdown.directiveMs
@@ -2557,7 +2569,7 @@ function executeAiAssistantCodexRun(payload, context) {
2557
2569
  }
2558
2570
  });
2559
2571
  }
2560
- finalMetadata = __assign(__assign(__assign(__assign(__assign({ model: codexModel }, (codexFallbackModels.length ? { model_fallbacks: codexFallbackModels } : {})), (requestId ? { request_id: requestId } : {})), (changeHistoryFastPathBypassedReason ? {
2572
+ finalMetadata = __assign(__assign(__assign(__assign(__assign(__assign({ model: codexModel }, (codexFallbackModels.length ? { model_fallbacks: codexFallbackModels } : {})), (requestId ? { request_id: requestId } : {})), { pending: false }), (changeHistoryFastPathBypassedReason ? {
2561
2573
  fast_path_change_history_bypassed_reason: changeHistoryFastPathBypassedReason
2562
2574
  } : {})), (toolResult ? { tool_result: toolResult } : {})), (assistantDebug ? { debug: assistantDebug } : {}));
2563
2575
  finalUsage = codexUsage.total_tokens > 0 ? {
@@ -2566,14 +2578,14 @@ function executeAiAssistantCodexRun(payload, context) {
2566
2578
  output_tokens: codexUsage.output_tokens,
2567
2579
  total_tokens: codexUsage.total_tokens
2568
2580
  } : null;
2569
- if (!finalUsage) return [3 /*break*/, 60];
2581
+ if (!finalUsage) return [3 /*break*/, 61];
2570
2582
  return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
2571
- case 56:
2572
- usageClientId = _13.sent();
2573
- if (!usageClientId) return [3 /*break*/, 60];
2574
- _13.label = 57;
2575
2583
  case 57:
2576
- _13.trys.push([57, 59, , 60]);
2584
+ usageClientId = _14.sent();
2585
+ if (!usageClientId) return [3 /*break*/, 61];
2586
+ _14.label = 58;
2587
+ case 58:
2588
+ _14.trys.push([58, 60, , 61]);
2577
2589
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
2578
2590
  id_client: usageClientId,
2579
2591
  model: finalUsage.model,
@@ -2584,16 +2596,16 @@ function executeAiAssistantCodexRun(payload, context) {
2584
2596
  id_request: requestId || undefined,
2585
2597
  id_conversation: conversation._id
2586
2598
  })];
2587
- case 58:
2588
- _13.sent();
2589
- return [3 /*break*/, 60];
2590
2599
  case 59:
2591
- usageError_1 = _13.sent();
2592
- console.error(new Date(), 'Failed to record codex usage', usageError_1);
2593
- return [3 /*break*/, 60];
2600
+ _14.sent();
2601
+ return [3 /*break*/, 61];
2594
2602
  case 60:
2603
+ usageError_1 = _14.sent();
2604
+ console.error(new Date(), 'Failed to record codex usage', usageError_1);
2605
+ return [3 /*break*/, 61];
2606
+ case 61:
2595
2607
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
2596
- if (!assistantMessageId) return [3 /*break*/, 62];
2608
+ if (!assistantMessageId) return [3 /*break*/, 63];
2597
2609
  setPayload = {
2598
2610
  content: assistantContent,
2599
2611
  metadata: finalMetadata,
@@ -2603,18 +2615,59 @@ function executeAiAssistantCodexRun(payload, context) {
2603
2615
  setPayload.usage = finalUsage;
2604
2616
  }
2605
2617
  return [4 /*yield*/, updateAssistantMessageWithFallback(assistantMessageId, setPayload)];
2606
- case 61:
2607
- _13.sent();
2608
- _13.label = 62;
2609
- case 62: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2610
- case 63:
2611
- _13.sent();
2612
- if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 65];
2613
- return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
2618
+ case 62:
2619
+ _14.sent();
2620
+ _14.label = 63;
2621
+ case 63: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2614
2622
  case 64:
2615
- _13.sent();
2616
- _13.label = 65;
2617
- case 65: return [2 /*return*/, finalAssistantDoc];
2623
+ _14.sent();
2624
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 66];
2625
+ return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
2626
+ case 65:
2627
+ _14.sent();
2628
+ _14.label = 66;
2629
+ case 66: return [2 /*return*/, finalAssistantDoc];
2630
+ case 67:
2631
+ finalizeError_1 = _14.sent();
2632
+ failedAt = new Date();
2633
+ fallbackContent = assistantContent || buildAssistantCodexErrorMessage(finalizeError_1);
2634
+ failureMetadata = __assign(__assign(__assign({ model: codexModel }, (codexFallbackModels.length ? { model_fallbacks: codexFallbackModels } : {})), (requestId ? { request_id: requestId } : {})), { pending: false, failed: true, error_message: normalizeOptionalString(finalizeError_1 === null || finalizeError_1 === void 0 ? void 0 : finalizeError_1.message) || 'Unknown error' });
2635
+ _14.label = 68;
2636
+ case 68:
2637
+ _14.trys.push([68, 72, , 73]);
2638
+ if (!assistantMessageId) return [3 /*break*/, 70];
2639
+ return [4 /*yield*/, updateAssistantMessageWithFallback(assistantMessageId, {
2640
+ content: fallbackContent,
2641
+ metadata: failureMetadata,
2642
+ updatedAt: failedAt
2643
+ })];
2644
+ case 69:
2645
+ _14.sent();
2646
+ _14.label = 70;
2647
+ case 70: return [4 /*yield*/, touchConversation(conversation._id, failedAt, assistantMessageId ? String(assistantMessageId) : undefined)];
2648
+ case 71:
2649
+ _14.sent();
2650
+ return [3 /*break*/, 73];
2651
+ case 72:
2652
+ persistError_1 = _14.sent();
2653
+ console.error(new Date(), 'AI assistant finalize fallback update failed', persistError_1);
2654
+ return [3 /*break*/, 73];
2655
+ case 73:
2656
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 77];
2657
+ _14.label = 74;
2658
+ case 74:
2659
+ _14.trys.push([74, 76, , 77]);
2660
+ return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
2661
+ case 75:
2662
+ _14.sent();
2663
+ return [3 /*break*/, 77];
2664
+ case 76:
2665
+ _k = _14.sent();
2666
+ return [3 /*break*/, 77];
2667
+ case 77:
2668
+ console.error(new Date(), 'AI assistant run finalize failed:', finalizeError_1);
2669
+ return [2 /*return*/, __assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: fallbackContent, metadata: failureMetadata, updatedAt: failedAt })];
2670
+ case 78: return [2 /*return*/];
2618
2671
  }
2619
2672
  });
2620
2673
  }); });
@@ -20441,54 +20494,110 @@ function resolveAssistantDatabaseNameForSystemCollections() {
20441
20494
  }
20442
20495
  function updateAssistantMessageWithFallback(messageId, setPayload) {
20443
20496
  return __awaiter(this, void 0, void 0, function () {
20444
- var error_12, dbName, _a;
20445
- return __generator(this, function (_b) {
20446
- switch (_b.label) {
20497
+ var safeSetPayload, fallbackId, debugEnabled, result, error_12, dbName, messagesCollection, result, _a, retryResult;
20498
+ var _b, _c, _d, _e, _f, _g;
20499
+ return __generator(this, function (_h) {
20500
+ switch (_h.label) {
20447
20501
  case 0:
20448
20502
  if (!messageId || !setPayload || typeof setPayload !== 'object') {
20449
20503
  return [2 /*return*/];
20450
20504
  }
20451
- _b.label = 1;
20505
+ safeSetPayload = sanitizeAssistantMessageSetPayload(setPayload);
20506
+ fallbackId = normalizeOptionalString(typeof messageId === 'string' ? messageId : String(messageId));
20507
+ debugEnabled = shouldLogAssistantFinalizeDebug();
20508
+ _h.label = 1;
20452
20509
  case 1:
20453
- _b.trys.push([1, 3, , 10]);
20454
- return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: messageId }, { $set: setPayload }, undefined, false, false, true)];
20510
+ _h.trys.push([1, 5, , 17]);
20511
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: messageId }, { $set: safeSetPayload }, undefined, false, false, true)];
20455
20512
  case 2:
20456
- _b.sent();
20457
- return [2 /*return*/];
20513
+ result = _h.sent();
20514
+ if (!((result === null || result === void 0 ? void 0 : result.matchedCount) === 0 && fallbackId && fallbackId !== messageId)) return [3 /*break*/, 4];
20515
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: fallbackId }, { $set: safeSetPayload }, undefined, false, false, true)];
20458
20516
  case 3:
20459
- error_12 = _b.sent();
20517
+ result = _h.sent();
20518
+ _h.label = 4;
20519
+ case 4:
20520
+ if (debugEnabled) {
20521
+ console.log(new Date(), '[AI-Dashboard][AI-Assistant] message finalize update', {
20522
+ messageId: fallbackId || messageId,
20523
+ matchedCount: (_b = result === null || result === void 0 ? void 0 : result.matchedCount) !== null && _b !== void 0 ? _b : 0,
20524
+ modifiedCount: (_c = result === null || result === void 0 ? void 0 : result.modifiedCount) !== null && _c !== void 0 ? _c : 0,
20525
+ via: 'collection_manager'
20526
+ });
20527
+ }
20528
+ return [2 /*return*/];
20529
+ case 5:
20530
+ error_12 = _h.sent();
20460
20531
  if (!isAssistantTransactionCommittedError(error_12)) {
20461
20532
  throw error_12;
20462
20533
  }
20534
+ if (debugEnabled) {
20535
+ console.log(new Date(), '[AI-Dashboard][AI-Assistant] message finalize update fallback triggered', {
20536
+ messageId: fallbackId || messageId,
20537
+ reason: normalizeOptionalString(error_12 === null || error_12 === void 0 ? void 0 : error_12.message) || 'transaction_committed'
20538
+ });
20539
+ }
20463
20540
  dbName = resolveAssistantDatabaseNameForSystemCollections();
20464
- _b.label = 4;
20465
- case 4:
20466
- _b.trys.push([4, 6, , 7]);
20467
- return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMongoConnection()
20468
- .db(dbName)
20469
- .collection('ai-terminal-messages')
20470
- .updateOne({ _id: messageId }, { $set: setPayload })];
20471
- case 5:
20472
- _b.sent();
20473
- return [2 /*return*/];
20541
+ _h.label = 6;
20474
20542
  case 6:
20475
- _a = _b.sent();
20476
- return [3 /*break*/, 7];
20477
- case 7: return [4 /*yield*/, (0, promises_1.setTimeout)(15)];
20543
+ _h.trys.push([6, 11, , 12]);
20544
+ messagesCollection = resolveio_server_app_1.ResolveIOServer.getMongoConnection()
20545
+ .db(dbName)
20546
+ .collection('ai-terminal-messages');
20547
+ return [4 /*yield*/, messagesCollection
20548
+ .updateOne({ _id: String(messageId) }, { $set: safeSetPayload })];
20549
+ case 7:
20550
+ result = _h.sent();
20551
+ if (!((result === null || result === void 0 ? void 0 : result.matchedCount) === 0 && fallbackId && fallbackId !== messageId)) return [3 /*break*/, 9];
20552
+ return [4 /*yield*/, messagesCollection
20553
+ .updateOne({ _id: fallbackId }, { $set: safeSetPayload })];
20478
20554
  case 8:
20479
- _b.sent();
20480
- return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: messageId }, { $set: setPayload }, undefined, false, false, true)];
20481
- case 9:
20482
- _b.sent();
20483
- return [3 /*break*/, 10];
20484
- case 10: return [2 /*return*/];
20555
+ result = _h.sent();
20556
+ _h.label = 9;
20557
+ case 9: return [4 /*yield*/, notifyAiTerminalCollectionUpdate('ai-terminal-messages', fallbackId || messageId)];
20558
+ case 10:
20559
+ _h.sent();
20560
+ if (debugEnabled) {
20561
+ console.log(new Date(), '[AI-Dashboard][AI-Assistant] message finalize update', {
20562
+ messageId: fallbackId || messageId,
20563
+ matchedCount: (_d = result === null || result === void 0 ? void 0 : result.matchedCount) !== null && _d !== void 0 ? _d : 0,
20564
+ modifiedCount: (_e = result === null || result === void 0 ? void 0 : result.modifiedCount) !== null && _e !== void 0 ? _e : 0,
20565
+ via: 'direct_mongo_fallback'
20566
+ });
20567
+ }
20568
+ return [2 /*return*/];
20569
+ case 11:
20570
+ _a = _h.sent();
20571
+ return [3 /*break*/, 12];
20572
+ case 12: return [4 /*yield*/, (0, promises_1.setTimeout)(15)];
20573
+ case 13:
20574
+ _h.sent();
20575
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: messageId }, { $set: safeSetPayload }, undefined, false, false, true)];
20576
+ case 14:
20577
+ retryResult = _h.sent();
20578
+ if (!((retryResult === null || retryResult === void 0 ? void 0 : retryResult.matchedCount) === 0 && fallbackId && fallbackId !== messageId)) return [3 /*break*/, 16];
20579
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.updateOne({ _id: fallbackId }, { $set: safeSetPayload }, undefined, false, false, true)];
20580
+ case 15:
20581
+ retryResult = _h.sent();
20582
+ _h.label = 16;
20583
+ case 16:
20584
+ if (debugEnabled) {
20585
+ console.log(new Date(), '[AI-Dashboard][AI-Assistant] message finalize update', {
20586
+ messageId: fallbackId || messageId,
20587
+ matchedCount: (_f = retryResult === null || retryResult === void 0 ? void 0 : retryResult.matchedCount) !== null && _f !== void 0 ? _f : 0,
20588
+ modifiedCount: (_g = retryResult === null || retryResult === void 0 ? void 0 : retryResult.modifiedCount) !== null && _g !== void 0 ? _g : 0,
20589
+ via: 'collection_manager_retry'
20590
+ });
20591
+ }
20592
+ return [3 /*break*/, 17];
20593
+ case 17: return [2 /*return*/];
20485
20594
  }
20486
20595
  });
20487
20596
  });
20488
20597
  }
20489
20598
  function touchConversation(idConversation, timestamp, lastMessageId) {
20490
20599
  return __awaiter(this, void 0, void 0, function () {
20491
- var update, error_13, dbName;
20600
+ var update, error_13, dbName, conversationsCollection;
20492
20601
  return __generator(this, function (_a) {
20493
20602
  switch (_a.label) {
20494
20603
  case 0:
@@ -20501,7 +20610,7 @@ function touchConversation(idConversation, timestamp, lastMessageId) {
20501
20610
  }
20502
20611
  _a.label = 1;
20503
20612
  case 1:
20504
- _a.trys.push([1, 3, , 5]);
20613
+ _a.trys.push([1, 3, , 6]);
20505
20614
  return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.updateOne({ _id: idConversation }, { $set: update }, undefined, false, false, true)];
20506
20615
  case 2:
20507
20616
  _a.sent();
@@ -20512,18 +20621,106 @@ function touchConversation(idConversation, timestamp, lastMessageId) {
20512
20621
  throw error_13;
20513
20622
  }
20514
20623
  dbName = resolveAssistantDatabaseNameForSystemCollections();
20515
- return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMongoConnection()
20516
- .db(dbName)
20517
- .collection('ai-terminal-conversations')
20518
- .updateOne({ _id: idConversation }, { $set: update })];
20624
+ conversationsCollection = resolveio_server_app_1.ResolveIOServer.getMongoConnection()
20625
+ .db(dbName)
20626
+ .collection('ai-terminal-conversations');
20627
+ return [4 /*yield*/, conversationsCollection.updateOne({ _id: idConversation }, { $set: update })];
20519
20628
  case 4:
20520
20629
  _a.sent();
20630
+ return [4 /*yield*/, notifyAiTerminalCollectionUpdate('ai-terminal-conversations', idConversation)];
20631
+ case 5:
20632
+ _a.sent();
20633
+ return [3 /*break*/, 6];
20634
+ case 6: return [2 /*return*/];
20635
+ }
20636
+ });
20637
+ });
20638
+ }
20639
+ function shouldLogAssistantFinalizeDebug() {
20640
+ return parseDebugFlag(process.env.AI_DASHBOARD_DEBUG)
20641
+ || parseDebugFlag(process.env.AI_ASSISTANT_WORKER_DEBUG);
20642
+ }
20643
+ function notifyAiTerminalCollectionUpdate(collection, documentId) {
20644
+ return __awaiter(this, void 0, void 0, function () {
20645
+ var subManager, _a;
20646
+ var _b, _c;
20647
+ return __generator(this, function (_d) {
20648
+ switch (_d.label) {
20649
+ case 0:
20650
+ try {
20651
+ resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(collection, true);
20652
+ }
20653
+ catch (_e) { }
20654
+ _d.label = 1;
20655
+ case 1:
20656
+ _d.trys.push([1, 4, , 5]);
20657
+ subManager = (_c = (_b = resolveio_server_app_1.ResolveIOServer.getMainServer()) === null || _b === void 0 ? void 0 : _b.getSubscriptionManager) === null || _c === void 0 ? void 0 : _c.call(_b);
20658
+ if (!(subManager && typeof subManager.invalidatePubsCache === 'function')) return [3 /*break*/, 3];
20659
+ return [4 /*yield*/, subManager.invalidatePubsCache(collection, 'update', documentId)];
20660
+ case 2:
20661
+ _d.sent();
20662
+ _d.label = 3;
20663
+ case 3: return [3 /*break*/, 5];
20664
+ case 4:
20665
+ _a = _d.sent();
20521
20666
  return [3 /*break*/, 5];
20522
20667
  case 5: return [2 /*return*/];
20523
20668
  }
20524
20669
  });
20525
20670
  });
20526
20671
  }
20672
+ function sanitizeAssistantMessageSetPayload(setPayload) {
20673
+ var next = __assign({}, setPayload);
20674
+ if (next.metadata && typeof next.metadata === 'object') {
20675
+ next.metadata = sanitizeMongoSafeObject(next.metadata);
20676
+ }
20677
+ return next;
20678
+ }
20679
+ function sanitizeMongoSafeObject(value) {
20680
+ var e_57, _a;
20681
+ if (value === null || value === undefined) {
20682
+ return value;
20683
+ }
20684
+ if (Array.isArray(value)) {
20685
+ return value.map(function (entry) { return sanitizeMongoSafeObject(entry); });
20686
+ }
20687
+ if (value instanceof Date) {
20688
+ return value;
20689
+ }
20690
+ if (isMongoObjectId(value)) {
20691
+ return value;
20692
+ }
20693
+ if (!isPlainObject(value)) {
20694
+ return value;
20695
+ }
20696
+ var out = {};
20697
+ try {
20698
+ for (var _b = __values(Object.entries(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
20699
+ var _d = __read(_c.value, 2), rawKey = _d[0], rawValue = _d[1];
20700
+ var key = sanitizeMongoKey(rawKey);
20701
+ out[key] = sanitizeMongoSafeObject(rawValue);
20702
+ }
20703
+ }
20704
+ catch (e_57_1) { e_57 = { error: e_57_1 }; }
20705
+ finally {
20706
+ try {
20707
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
20708
+ }
20709
+ finally { if (e_57) throw e_57.error; }
20710
+ }
20711
+ return out;
20712
+ }
20713
+ function sanitizeMongoKey(rawKey) {
20714
+ var key = String(rawKey || '');
20715
+ if (!key) {
20716
+ return '_';
20717
+ }
20718
+ var sanitized = key.replace(/\./g, '__dot__');
20719
+ if (sanitized.startsWith('$')) {
20720
+ sanitized = "_dollar_".concat(sanitized.slice(1));
20721
+ }
20722
+ return sanitized || '_';
20723
+ }
20527
20724
  function normalizeOptionalString(value) {
20528
20725
  var raw = typeof value === 'string' ? value.trim() : '';
20529
20726
  return raw || '';
@@ -20610,7 +20807,7 @@ function estimateUsage(messages, responseText, model) {
20610
20807
  };
20611
20808
  }
20612
20809
  function evaluateGuardrails(message) {
20613
- var e_57, _a;
20810
+ var e_58, _a;
20614
20811
  var normalized = String(message || '').toLowerCase();
20615
20812
  var identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(normalized);
20616
20813
  if (identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked) {
@@ -20636,12 +20833,12 @@ function evaluateGuardrails(message) {
20636
20833
  }
20637
20834
  }
20638
20835
  }
20639
- catch (e_57_1) { e_57 = { error: e_57_1 }; }
20836
+ catch (e_58_1) { e_58 = { error: e_58_1 }; }
20640
20837
  finally {
20641
20838
  try {
20642
20839
  if (patterns_3_1 && !patterns_3_1.done && (_a = patterns_3.return)) _a.call(patterns_3);
20643
20840
  }
20644
- finally { if (e_57) throw e_57.error; }
20841
+ finally { if (e_58) throw e_58.error; }
20645
20842
  }
20646
20843
  return null;
20647
20844
  }