@resolveio/server-lib 22.1.23 → 22.1.25

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.
@@ -445,6 +445,7 @@ var AI_ASSISTANT_COLLECTION_GENERIC_TOKENS = new Set([
445
445
  'list',
446
446
  'show'
447
447
  ]);
448
+ var AI_ASSISTANT_INVOICE_PERMISSION_PATTERN = /invoice/i;
448
449
  var AI_ASSISTANT_FIELD_TOKEN_SYNONYMS = {
449
450
  volume: ['quantity', 'qty', 'amount', 'gallons', 'gallon', 'liters', 'liter', 'litre'],
450
451
  quantity: ['volume', 'qty', 'amount', 'gallons', 'gallon'],
@@ -912,14 +913,20 @@ function loadAiTerminalMethods(methodManager) {
912
913
  }),
913
914
  function: function (payload) {
914
915
  return __awaiter(this, void 0, void 0, function () {
915
- var now, doc, result;
916
+ var idUser, now, doc, result;
916
917
  var _a;
917
918
  return __generator(this, function (_b) {
918
919
  switch (_b.label) {
919
920
  case 0:
921
+ idUser = normalizeOptionalString((this === null || this === void 0 ? void 0 : this.id_user) || '');
922
+ if (!idUser) {
923
+ throw new Error('Unauthorized.');
924
+ }
920
925
  now = new Date();
921
- _a = {};
922
- return [4 /*yield*/, resolveClientIdFromConfig(payload.id_client, this === null || this === void 0 ? void 0 : this.id_user)];
926
+ _a = {
927
+ id_user: idUser
928
+ };
929
+ return [4 /*yield*/, resolveClientIdFromConfig(payload.id_client, idUser)];
923
930
  case 1:
924
931
  doc = (_a.id_client = _b.sent(),
925
932
  _a.id_app = normalizeOptionalString(payload.id_app),
@@ -956,10 +963,14 @@ function loadAiTerminalMethods(methodManager) {
956
963
  }),
957
964
  function: function (id_conversation, patch) {
958
965
  return __awaiter(this, void 0, void 0, function () {
959
- var update;
966
+ var idUser, update;
960
967
  return __generator(this, function (_a) {
961
968
  switch (_a.label) {
962
969
  case 0:
970
+ idUser = normalizeOptionalString((this === null || this === void 0 ? void 0 : this.id_user) || '');
971
+ if (!idUser) {
972
+ throw new Error('Unauthorized.');
973
+ }
963
974
  update = {
964
975
  updatedAt: new Date()
965
976
  };
@@ -981,7 +992,7 @@ function loadAiTerminalMethods(methodManager) {
981
992
  if (patch.metadata !== undefined) {
982
993
  update.metadata = patch.metadata || {};
983
994
  }
984
- return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.updateOne({ _id: id_conversation }, { $set: update })];
995
+ return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.updateOne({ _id: id_conversation, id_user: idUser }, { $set: update })];
985
996
  case 1:
986
997
  _a.sent();
987
998
  return [2 /*return*/, { id_conversation: id_conversation }];
@@ -998,13 +1009,25 @@ function loadAiTerminalMethods(methodManager) {
998
1009
  }),
999
1010
  function: function (id_conversation) {
1000
1011
  return __awaiter(this, void 0, void 0, function () {
1012
+ var idUser, conversation;
1001
1013
  return __generator(this, function (_a) {
1002
1014
  switch (_a.label) {
1003
- case 0: return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.deleteMany({ id_conversation: id_conversation })];
1015
+ case 0:
1016
+ idUser = normalizeOptionalString((this === null || this === void 0 ? void 0 : this.id_user) || '');
1017
+ if (!idUser) {
1018
+ throw new Error('Unauthorized.');
1019
+ }
1020
+ return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.findById(id_conversation)];
1004
1021
  case 1:
1005
- _a.sent();
1006
- return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.deleteOne({ _id: id_conversation })];
1022
+ conversation = _a.sent();
1023
+ if (!conversation || normalizeOptionalString(conversation.id_user) !== idUser) {
1024
+ throw new Error('Conversation not found.');
1025
+ }
1026
+ return [4 /*yield*/, ai_terminal_message_collection_1.AiTerminalMessages.deleteMany({ id_conversation: id_conversation })];
1007
1027
  case 2:
1028
+ _a.sent();
1029
+ return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.deleteOne({ _id: id_conversation, id_user: idUser })];
1030
+ case 3:
1008
1031
  _a.sent();
1009
1032
  return [2 /*return*/, { id_conversation: id_conversation }];
1010
1033
  }
@@ -1033,10 +1056,20 @@ function loadAiTerminalMethods(methodManager) {
1033
1056
  }),
1034
1057
  function: function (id_conversation, file_name, content_base64, size, content_type) {
1035
1058
  return __awaiter(this, void 0, void 0, function () {
1036
- var limits, safeName, uploadRoot, targetDir, targetPath, dataBuffer, data;
1059
+ var idUser, conversation, limits, safeName, uploadRoot, targetDir, targetPath, dataBuffer, data;
1037
1060
  return __generator(this, function (_a) {
1038
1061
  switch (_a.label) {
1039
1062
  case 0:
1063
+ idUser = normalizeOptionalString((this === null || this === void 0 ? void 0 : this.id_user) || '');
1064
+ if (!idUser) {
1065
+ throw new Error('Unauthorized.');
1066
+ }
1067
+ return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.findById(id_conversation)];
1068
+ case 1:
1069
+ conversation = _a.sent();
1070
+ if (!conversation || normalizeOptionalString(conversation.id_user) !== idUser) {
1071
+ throw new Error('Conversation not found.');
1072
+ }
1040
1073
  limits = resolveUploadLimits();
1041
1074
  if (size > limits.maxFileBytes) {
1042
1075
  throw new Error("File exceeds ".concat(limits.maxFileMb, "MB limit."));
@@ -1045,7 +1078,7 @@ function loadAiTerminalMethods(methodManager) {
1045
1078
  uploadRoot = resolveUploadRoot();
1046
1079
  targetDir = path.join(uploadRoot, id_conversation);
1047
1080
  return [4 /*yield*/, fs_1.promises.mkdir(targetDir, { recursive: true })];
1048
- case 1:
1081
+ case 2:
1049
1082
  _a.sent();
1050
1083
  targetPath = path.join(targetDir, safeName);
1051
1084
  dataBuffer = Buffer.from(content_base64, 'base64');
@@ -1056,7 +1089,7 @@ function loadAiTerminalMethods(methodManager) {
1056
1089
  }
1057
1090
  }
1058
1091
  return [4 /*yield*/, fs_1.promises.writeFile(targetPath, data)];
1059
- case 2:
1092
+ case 3:
1060
1093
  _a.sent();
1061
1094
  return [2 /*return*/, {
1062
1095
  id_file: (0, common_1.objectIdHexString)(),
@@ -1264,6 +1297,9 @@ function executeAiTerminalRun(payload, context) {
1264
1297
  if (!message) {
1265
1298
  throw new Error('Message is required.');
1266
1299
  }
1300
+ if (!(context === null || context === void 0 ? void 0 : context.id_user)) {
1301
+ throw new Error('Unauthorized.');
1302
+ }
1267
1303
  requestId = normalizeOptionalString(input.request_id);
1268
1304
  identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(message);
1269
1305
  if (!(identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked)) return [3 /*break*/, 5];
@@ -1718,7 +1754,7 @@ function executeAiAssistantCodexRun(payload, context) {
1718
1754
  insertResult = _d.sent();
1719
1755
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1720
1756
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1721
- 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, 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;
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;
1722
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;
1723
1759
  return __generator(this, function (_13) {
1724
1760
  switch (_13.label) {
@@ -1816,7 +1852,7 @@ function executeAiAssistantCodexRun(payload, context) {
1816
1852
  });
1817
1853
  _13.label = 1;
1818
1854
  case 1:
1819
- _13.trys.push([1, 52, 53, 54]);
1855
+ _13.trys.push([1, 53, 54, 55]);
1820
1856
  hintSeed = [message, contextRoute].filter(Boolean).join(' ');
1821
1857
  termExpansion = expandAssistantTermSynonyms(hintSeed);
1822
1858
  hintText = termExpansion.expanded || hintSeed;
@@ -2329,7 +2365,22 @@ function executeAiAssistantCodexRun(payload, context) {
2329
2365
  if (cleanedResponseText) {
2330
2366
  assistantContent = sanitizeAssistantResponse(cleanedResponseText);
2331
2367
  }
2332
- if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 50];
2368
+ deniedModuleByIntent = resolveAssistantIntentDeniedModule({
2369
+ user: user,
2370
+ isSuperAdmin: isSuperAdmin,
2371
+ message: message
2372
+ });
2373
+ if (!deniedModuleByIntent) return [3 /*break*/, 38];
2374
+ permissionLabel = formatAssistantModulePermissionLabel(deniedModuleByIntent);
2375
+ progressTracker.push('Grabbing Data');
2376
+ recordStep('Grabbing Data: denied', {
2377
+ reason: "".concat(deniedModuleByIntent, "_permission_required")
2378
+ });
2379
+ assistantContent = "I couldn't run that request because this account does not have ".concat(permissionLabel, " permission.");
2380
+ toolError = new Error('AI assistant report builder bridge: Access denied.');
2381
+ return [3 /*break*/, 52];
2382
+ case 38:
2383
+ if (!((directive === null || directive === void 0 ? void 0 : directive.payload) && AI_ASSISTANT_TOOL_MAX_STEPS > 0)) return [3 /*break*/, 51];
2333
2384
  effectiveDirective = collectionOverride
2334
2385
  ? __assign(__assign({}, directive), { payload: __assign(__assign({}, (directive.payload || {})), { collection: collectionOverride.to }) }) : directive;
2335
2386
  toolRequest = buildAssistantToolRequest(effectiveDirective, input);
@@ -2339,20 +2390,20 @@ function executeAiAssistantCodexRun(payload, context) {
2339
2390
  collection: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.collection) || undefined,
2340
2391
  permissionView: normalizeOptionalString(toolRequest === null || toolRequest === void 0 ? void 0 : toolRequest.permissionView) || undefined
2341
2392
  });
2342
- _13.label = 38;
2343
- case 38:
2344
- _13.trys.push([38, 48, , 49]);
2393
+ _13.label = 39;
2394
+ case 39:
2395
+ _13.trys.push([39, 49, , 50]);
2345
2396
  toolStart = Date.now();
2346
- if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 40];
2397
+ if (!(effectiveDirective.type === 'aggregate')) return [3 /*break*/, 41];
2347
2398
  return [4 /*yield*/, executeAiAssistantReportBuilderAggregate(toolRequest, context)];
2348
- case 39:
2399
+ case 40:
2349
2400
  _h = _13.sent();
2350
- return [3 /*break*/, 42];
2351
- case 40: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
2352
- case 41:
2353
- _h = _13.sent();
2354
- _13.label = 42;
2401
+ return [3 /*break*/, 43];
2402
+ case 41: return [4 /*yield*/, executeAiAssistantReportBuilderRead(toolRequest, context)];
2355
2403
  case 42:
2404
+ _h = _13.sent();
2405
+ _13.label = 43;
2406
+ case 43:
2356
2407
  toolResponse = _h;
2357
2408
  timingBreakdown.toolMs = Date.now() - toolStart;
2358
2409
  toolResponseDebug = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object'
@@ -2368,54 +2419,54 @@ function executeAiAssistantCodexRun(payload, context) {
2368
2419
  progressTracker.push('Drafting response');
2369
2420
  skipFollowupCodex = usedDeterministicHeuristicFastPath
2370
2421
  || isAssistantDeterministicHeuristicDirective(effectiveDirective);
2371
- if (!skipFollowupCodex) return [3 /*break*/, 43];
2422
+ if (!skipFollowupCodex) return [3 /*break*/, 44];
2372
2423
  recordStep('Drafting response: deterministic summary', {
2373
2424
  reason: normalizeOptionalString(effectiveDirective.rawLine) || 'deterministic_heuristic'
2374
2425
  });
2375
2426
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
2376
2427
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2377
- return [3 /*break*/, 47];
2378
- case 43:
2428
+ return [3 /*break*/, 48];
2429
+ case 44:
2379
2430
  recordStep('Drafting response');
2380
2431
  followupPrompt = buildAssistantCodexToolFollowupPrompt(message, attachmentData.promptText, historyLines.join('\n'), assistantContext, toolPayload.prompt);
2381
- _13.label = 44;
2382
- case 44:
2383
- _13.trys.push([44, 46, , 47]);
2432
+ _13.label = 45;
2433
+ case 45:
2434
+ _13.trys.push([45, 47, , 48]);
2384
2435
  followupStart = Date.now();
2385
2436
  return [4 /*yield*/, runCodexInWorkerThread(followupPrompt, runOptions, codexConfig, streamProgress)];
2386
- case 45:
2437
+ case 46:
2387
2438
  followupText = _13.sent();
2388
2439
  accumulateCodexUsage(followupPrompt, followupText);
2389
2440
  timingBreakdown.followupMs = Date.now() - followupStart;
2390
2441
  assistantContent = sanitizeAssistantResponse(followupText);
2391
2442
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2392
- return [3 /*break*/, 47];
2393
- case 46:
2443
+ return [3 /*break*/, 48];
2444
+ case 47:
2394
2445
  _j = _13.sent();
2395
2446
  assistantContent = buildAssistantToolFallbackResponse(toolPayload.result);
2396
2447
  assistantContent = applyAssistantDisplayTableToResponse(assistantContent, toolPayload.result.output.display);
2397
- return [3 /*break*/, 47];
2398
- case 47: return [3 /*break*/, 49];
2399
- case 48:
2448
+ return [3 /*break*/, 48];
2449
+ case 48: return [3 /*break*/, 50];
2450
+ case 49:
2400
2451
  error_3 = _13.sent();
2401
2452
  assistantContent = buildAssistantToolErrorMessage(error_3);
2402
2453
  toolError = error_3;
2403
- return [3 /*break*/, 49];
2404
- case 49: return [3 /*break*/, 51];
2405
- case 50:
2454
+ return [3 /*break*/, 50];
2455
+ case 50: return [3 /*break*/, 52];
2456
+ case 51:
2406
2457
  progressTracker.push('Drafting response');
2407
2458
  recordStep('Drafting response');
2408
- _13.label = 51;
2409
- case 51: return [3 /*break*/, 54];
2410
- case 52:
2459
+ _13.label = 52;
2460
+ case 52: return [3 /*break*/, 55];
2461
+ case 53:
2411
2462
  error_4 = _13.sent();
2412
2463
  assistantContent = buildAssistantCodexErrorMessage(error_4);
2413
2464
  recordStep('Error', { message: normalizeOptionalString(error_4 === null || error_4 === void 0 ? void 0 : error_4.message) || 'Unknown error' });
2414
- return [3 /*break*/, 54];
2415
- case 53:
2465
+ return [3 /*break*/, 55];
2466
+ case 54:
2416
2467
  progressTracker.stop();
2417
2468
  return [7 /*endfinally*/];
2418
- case 54:
2469
+ case 55:
2419
2470
  if (!assistantContent) {
2420
2471
  assistantContent = buildAssistantCodexErrorMessage(null);
2421
2472
  }
@@ -2515,14 +2566,14 @@ function executeAiAssistantCodexRun(payload, context) {
2515
2566
  output_tokens: codexUsage.output_tokens,
2516
2567
  total_tokens: codexUsage.total_tokens
2517
2568
  } : null;
2518
- if (!finalUsage) return [3 /*break*/, 59];
2569
+ if (!finalUsage) return [3 /*break*/, 60];
2519
2570
  return [4 /*yield*/, resolveClientId(conversation, input.id_client, context === null || context === void 0 ? void 0 : context.id_user)];
2520
- case 55:
2521
- usageClientId = _13.sent();
2522
- if (!usageClientId) return [3 /*break*/, 59];
2523
- _13.label = 56;
2524
2571
  case 56:
2525
- _13.trys.push([56, 58, , 59]);
2572
+ usageClientId = _13.sent();
2573
+ if (!usageClientId) return [3 /*break*/, 60];
2574
+ _13.label = 57;
2575
+ case 57:
2576
+ _13.trys.push([57, 59, , 60]);
2526
2577
  return [4 /*yield*/, (0, openai_usage_ledger_manager_1.recordOpenAIUsage)({
2527
2578
  id_client: usageClientId,
2528
2579
  model: finalUsage.model,
@@ -2533,16 +2584,16 @@ function executeAiAssistantCodexRun(payload, context) {
2533
2584
  id_request: requestId || undefined,
2534
2585
  id_conversation: conversation._id
2535
2586
  })];
2536
- case 57:
2537
- _13.sent();
2538
- return [3 /*break*/, 59];
2539
2587
  case 58:
2588
+ _13.sent();
2589
+ return [3 /*break*/, 60];
2590
+ case 59:
2540
2591
  usageError_1 = _13.sent();
2541
2592
  console.error(new Date(), 'Failed to record codex usage', usageError_1);
2542
- return [3 /*break*/, 59];
2543
- case 59:
2593
+ return [3 /*break*/, 60];
2594
+ case 60:
2544
2595
  finalAssistantDoc = __assign(__assign(__assign(__assign({}, assistantDoc), { _id: assistantMessageId, content: assistantContent, metadata: finalMetadata }), (finalUsage ? { usage: finalUsage } : {})), { updatedAt: finalNow });
2545
- if (!assistantMessageId) return [3 /*break*/, 61];
2596
+ if (!assistantMessageId) return [3 /*break*/, 62];
2546
2597
  setPayload = {
2547
2598
  content: assistantContent,
2548
2599
  metadata: finalMetadata,
@@ -2552,18 +2603,18 @@ function executeAiAssistantCodexRun(payload, context) {
2552
2603
  setPayload.usage = finalUsage;
2553
2604
  }
2554
2605
  return [4 /*yield*/, updateAssistantMessageWithFallback(assistantMessageId, setPayload)];
2555
- case 60:
2606
+ case 61:
2556
2607
  _13.sent();
2557
- _13.label = 61;
2558
- case 61: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2559
- case 62:
2608
+ _13.label = 62;
2609
+ case 62: return [4 /*yield*/, touchConversation(conversation._id, finalNow, assistantMessageId ? String(assistantMessageId) : undefined)];
2610
+ case 63:
2560
2611
  _13.sent();
2561
- if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 64];
2612
+ if (!(input.delete_files_after_run !== false)) return [3 /*break*/, 65];
2562
2613
  return [4 /*yield*/, cleanupAttachments(attachmentData.attachments)];
2563
- case 63:
2614
+ case 64:
2564
2615
  _13.sent();
2565
- _13.label = 64;
2566
- case 64: return [2 /*return*/, finalAssistantDoc];
2616
+ _13.label = 65;
2617
+ case 65: return [2 /*return*/, finalAssistantDoc];
2567
2618
  }
2568
2619
  });
2569
2620
  }); });
@@ -9669,7 +9720,7 @@ function isDisplayObjectLike(value) {
9669
9720
  }
9670
9721
  function ensureAssistantReadAccess(context, permissionView, collection) {
9671
9722
  return __awaiter(this, void 0, void 0, function () {
9672
- var idUser, user, isSuperAdmin, canViewDebug, normalizedCollection, normalizedPermission, requiresInvoiceAccess, hasInvoiceAccess, hasViewAccess;
9723
+ var idUser, user, isSuperAdmin, canViewDebug, normalizedCollection, normalizedPermission, permissionModule, collectionModule, requestedModule, requiresInvoiceAccess, hasInvoiceAccess, hasViewAccess, hasModuleAccess;
9673
9724
  var _a;
9674
9725
  return __generator(this, function (_b) {
9675
9726
  switch (_b.label) {
@@ -9694,10 +9745,17 @@ function ensureAssistantReadAccess(context, permissionView, collection) {
9694
9745
  if (!normalizedPermission) {
9695
9746
  throw new Error('AI assistant report builder bridge: Permission scope required.');
9696
9747
  }
9697
- requiresInvoiceAccess = normalizedCollection ? requiresInvoicePermission(normalizedCollection) : false;
9748
+ permissionModule = resolveAssistantPrimaryModuleFromText(normalizedPermission);
9749
+ collectionModule = permissionModule ? null : resolveAssistantPrimaryModuleFromText(normalizedCollection);
9750
+ requestedModule = permissionModule || collectionModule;
9751
+ requiresInvoiceAccess = (normalizedCollection ? requiresInvoicePermission(normalizedCollection) : false)
9752
+ || AI_ASSISTANT_INVOICE_PERMISSION_PATTERN.test(normalizedPermission);
9698
9753
  hasInvoiceAccess = requiresInvoiceAccess && userHasInvoiceAccess(user);
9699
9754
  hasViewAccess = userHasViewPermission(user, normalizedPermission);
9700
- if (!hasViewAccess && !hasInvoiceAccess) {
9755
+ hasModuleAccess = requestedModule
9756
+ ? userHasAssistantChangeModuleAccess(user, requestedModule)
9757
+ : false;
9758
+ if (!hasViewAccess && !hasInvoiceAccess && !hasModuleAccess) {
9701
9759
  throw new Error('AI assistant report builder bridge: Access denied.');
9702
9760
  }
9703
9761
  if (requiresInvoiceAccess && !hasInvoiceAccess) {
@@ -16281,27 +16339,166 @@ function fetchAssistantProbeDocs(params) {
16281
16339
  })
16282
16340
  .toArray();
16283
16341
  }
16284
- function userHasViewPermission(user, view) {
16285
- var _a, _b, _c;
16286
- if (!user || !view) {
16342
+ var AI_ASSISTANT_PERMISSION_ACTION_TOKENS = new Set([
16343
+ 'list',
16344
+ 'detail',
16345
+ 'new',
16346
+ 'edit',
16347
+ 'delete',
16348
+ 'create',
16349
+ 'dashboard',
16350
+ 'report',
16351
+ 'reports',
16352
+ 'calendar',
16353
+ 'board',
16354
+ 'timeline',
16355
+ 'settings',
16356
+ 'setting',
16357
+ 'view'
16358
+ ]);
16359
+ function tokenizeAssistantPermissionScope(value) {
16360
+ var normalizedRoute = normalizeRouteMatchKey(value);
16361
+ if (!normalizedRoute) {
16362
+ return [];
16363
+ }
16364
+ var rawTokens = normalizedRoute
16365
+ .split(/[^a-z0-9]+/g)
16366
+ .map(function (token) { return token.trim(); })
16367
+ .filter(Boolean);
16368
+ var tokens = [];
16369
+ rawTokens.forEach(function (token) {
16370
+ normalizeCollectionToken(token).forEach(function (normalized) {
16371
+ if (!normalized) {
16372
+ return;
16373
+ }
16374
+ tokens.push(normalized);
16375
+ });
16376
+ });
16377
+ return Array.from(new Set(tokens));
16378
+ }
16379
+ function splitAssistantPermissionTokenSets(value) {
16380
+ var tokens = tokenizeAssistantPermissionScope(value);
16381
+ var actionTokens = new Set();
16382
+ var domainTokens = new Set();
16383
+ tokens.forEach(function (token) {
16384
+ if (AI_ASSISTANT_PERMISSION_ACTION_TOKENS.has(token)) {
16385
+ actionTokens.add(token);
16386
+ return;
16387
+ }
16388
+ domainTokens.add(token);
16389
+ });
16390
+ return {
16391
+ tokens: new Set(tokens),
16392
+ domainTokens: domainTokens,
16393
+ actionTokens: actionTokens
16394
+ };
16395
+ }
16396
+ function isAssistantTokenSetSubset(subset, superset) {
16397
+ var e_43, _a;
16398
+ if (!subset.size) {
16287
16399
  return false;
16288
16400
  }
16289
- if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
16401
+ try {
16402
+ for (var subset_1 = __values(subset), subset_1_1 = subset_1.next(); !subset_1_1.done; subset_1_1 = subset_1.next()) {
16403
+ var token = subset_1_1.value;
16404
+ if (!superset.has(token)) {
16405
+ return false;
16406
+ }
16407
+ }
16408
+ }
16409
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
16410
+ finally {
16411
+ try {
16412
+ if (subset_1_1 && !subset_1_1.done && (_a = subset_1.return)) _a.call(subset_1);
16413
+ }
16414
+ finally { if (e_43) throw e_43.error; }
16415
+ }
16416
+ return true;
16417
+ }
16418
+ function buildAssistantPermissionRegex(value) {
16419
+ var tokens = tokenizeAssistantPermissionScope(value);
16420
+ if (!tokens.length) {
16421
+ return null;
16422
+ }
16423
+ var _a = __read(tokens), first = _a[0], rest = _a.slice(1);
16424
+ var pattern = "(?:^|[^a-z0-9])".concat(escapeRegexValue(first), "s?");
16425
+ rest.forEach(function (token) {
16426
+ pattern += "(?:[^a-z0-9]+".concat(escapeRegexValue(token), "s?)");
16427
+ });
16428
+ pattern += '(?:$|[^a-z0-9])';
16429
+ return new RegExp(pattern, 'i');
16430
+ }
16431
+ function isAssistantViewPermissionMatch(grantedPermission, requestedView) {
16432
+ var grantedRoute = normalizeRouteMatchKey(grantedPermission);
16433
+ var requestedRoute = normalizeRouteMatchKey(requestedView);
16434
+ if (!grantedRoute || !requestedRoute) {
16435
+ return false;
16436
+ }
16437
+ if (grantedRoute === requestedRoute
16438
+ || grantedRoute.startsWith("".concat(requestedRoute, "/"))
16439
+ || requestedRoute.startsWith("".concat(grantedRoute, "/"))) {
16290
16440
  return true;
16291
16441
  }
16292
- var groups = Array.isArray((_b = user.roles) === null || _b === void 0 ? void 0 : _b.groups) ? user.roles.groups : [];
16293
- var miscs = Array.isArray((_c = user.roles) === null || _c === void 0 ? void 0 : _c.miscs) ? user.roles.miscs : [];
16294
- if (groups.some(function (group) { return Array.isArray(group.views) && group.views.some(function (v) { return v.startsWith(view); }); })) {
16442
+ var grantedTokens = splitAssistantPermissionTokenSets(grantedRoute);
16443
+ var requestedTokens = splitAssistantPermissionTokenSets(requestedRoute);
16444
+ if (!grantedTokens.tokens.size || !requestedTokens.tokens.size) {
16445
+ return false;
16446
+ }
16447
+ if (grantedTokens.actionTokens.size && requestedTokens.actionTokens.size) {
16448
+ var hasSharedAction = Array.from(requestedTokens.actionTokens)
16449
+ .some(function (token) { return grantedTokens.actionTokens.has(token); });
16450
+ if (!hasSharedAction) {
16451
+ return false;
16452
+ }
16453
+ }
16454
+ if (!grantedTokens.domainTokens.size || !requestedTokens.domainTokens.size) {
16455
+ return false;
16456
+ }
16457
+ if (isAssistantTokenSetSubset(requestedTokens.domainTokens, grantedTokens.domainTokens)) {
16458
+ return true;
16459
+ }
16460
+ if (requestedTokens.domainTokens.size > 1
16461
+ && grantedTokens.domainTokens.size > 1
16462
+ && isAssistantTokenSetSubset(grantedTokens.domainTokens, requestedTokens.domainTokens)) {
16295
16463
  return true;
16296
16464
  }
16297
- if (miscs.some(function (v) { return v.startsWith(view); })) {
16465
+ var sharedTokenCount = 0;
16466
+ requestedTokens.tokens.forEach(function (token) {
16467
+ if (grantedTokens.tokens.has(token)) {
16468
+ sharedTokenCount += 1;
16469
+ }
16470
+ });
16471
+ var requestedCoverage = requestedTokens.tokens.size
16472
+ ? sharedTokenCount / requestedTokens.tokens.size
16473
+ : 0;
16474
+ if (sharedTokenCount >= 2 && requestedCoverage >= 0.8) {
16298
16475
  return true;
16299
16476
  }
16300
- if (groups.some(function (group) { return group.name === view; })) {
16477
+ var requestedRegex = buildAssistantPermissionRegex(requestedRoute);
16478
+ if (requestedRegex && requestedRegex.test(grantedRoute)) {
16479
+ return true;
16480
+ }
16481
+ var grantedRegex = buildAssistantPermissionRegex(grantedRoute);
16482
+ if (grantedRegex && grantedRegex.test(requestedRoute)) {
16301
16483
  return true;
16302
16484
  }
16303
16485
  return false;
16304
16486
  }
16487
+ function userHasViewPermission(user, view) {
16488
+ var _a, _b;
16489
+ if (!user || !view) {
16490
+ return false;
16491
+ }
16492
+ if ((_a = user.roles) === null || _a === void 0 ? void 0 : _a.super_admin) {
16493
+ return true;
16494
+ }
16495
+ var permissions = collectUserViewPermissions(user);
16496
+ if (permissions.some(function (permission) { return isAssistantViewPermissionMatch(permission, view); })) {
16497
+ return true;
16498
+ }
16499
+ var groups = Array.isArray((_b = user.roles) === null || _b === void 0 ? void 0 : _b.groups) ? user.roles.groups : [];
16500
+ return groups.some(function (group) { return isAssistantViewPermissionMatch(normalizeOptionalString(group === null || group === void 0 ? void 0 : group.name), view); });
16501
+ }
16305
16502
  function collectUserViewPermissions(user) {
16306
16503
  var _a, _b;
16307
16504
  if (!user) {
@@ -16338,7 +16535,7 @@ function userHasViewTokenPermission(user, tokenRegex) {
16338
16535
  return permissions.some(function (view) { return tokenRegex.test(view); });
16339
16536
  }
16340
16537
  function userHasInvoiceAccess(user) {
16341
- return userHasViewTokenPermission(user, /invoice/i);
16538
+ return userHasViewTokenPermission(user, AI_ASSISTANT_INVOICE_PERMISSION_PATTERN);
16342
16539
  }
16343
16540
  function resolveAssistantUserAccessTier(user) {
16344
16541
  var _a, _b;
@@ -16353,7 +16550,29 @@ function requiresInvoicePermission(collection) {
16353
16550
  if (!normalized) {
16354
16551
  return false;
16355
16552
  }
16356
- return normalized.includes('invoice');
16553
+ return AI_ASSISTANT_INVOICE_PERMISSION_PATTERN.test(normalized);
16554
+ }
16555
+ function resolveAssistantPrimaryModuleFromText(text) {
16556
+ var modules = resolveAssistantChangeModulesFromText(text)
16557
+ .filter(function (module) { return module !== 'general' && module !== 'internal'; });
16558
+ return modules.length ? modules[0] : null;
16559
+ }
16560
+ function formatAssistantModulePermissionLabel(module) {
16561
+ var normalized = normalizeOptionalString(module).replace(/[_-]+/g, ' ').trim();
16562
+ return normalized || 'module';
16563
+ }
16564
+ function resolveAssistantIntentDeniedModule(params) {
16565
+ if (!(params === null || params === void 0 ? void 0 : params.user) || (params === null || params === void 0 ? void 0 : params.isSuperAdmin)) {
16566
+ return null;
16567
+ }
16568
+ var requestedModule = resolveAssistantPrimaryModuleFromText((params === null || params === void 0 ? void 0 : params.message) || '');
16569
+ if (!requestedModule) {
16570
+ return null;
16571
+ }
16572
+ if (userHasAssistantChangeModuleAccess(params.user, requestedModule)) {
16573
+ return null;
16574
+ }
16575
+ return requestedModule;
16357
16576
  }
16358
16577
  function redactSensitiveFields(value) {
16359
16578
  if (Array.isArray(value)) {
@@ -16566,8 +16785,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
16566
16785
  }
16567
16786
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
16568
16787
  return __awaiter(this, void 0, void 0, function () {
16569
- var _a, _b, _c, _d, message, payload, status_1, e_43_1;
16570
- var _e, e_43, _f, _g;
16788
+ var _a, _b, _c, _d, message, payload, status_1, e_44_1;
16789
+ var _e, e_44, _f, _g;
16571
16790
  return __generator(this, function (_h) {
16572
16791
  switch (_h.label) {
16573
16792
  case 0:
@@ -16594,8 +16813,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
16594
16813
  return [3 /*break*/, 1];
16595
16814
  case 4: return [3 /*break*/, 11];
16596
16815
  case 5:
16597
- e_43_1 = _h.sent();
16598
- e_43 = { error: e_43_1 };
16816
+ e_44_1 = _h.sent();
16817
+ e_44 = { error: e_44_1 };
16599
16818
  return [3 /*break*/, 11];
16600
16819
  case 6:
16601
16820
  _h.trys.push([6, , 9, 10]);
@@ -16606,7 +16825,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
16606
16825
  _h.label = 8;
16607
16826
  case 8: return [3 /*break*/, 10];
16608
16827
  case 9:
16609
- if (e_43) throw e_43.error;
16828
+ if (e_44) throw e_44.error;
16610
16829
  return [7 /*endfinally*/];
16611
16830
  case 10: return [7 /*endfinally*/];
16612
16831
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -16950,8 +17169,8 @@ function buildAssistantWorkspaceRootCandidates(params) {
16950
17169
  }
16951
17170
  function resolveAssistantWorkspaceRoot() {
16952
17171
  return __awaiter(this, void 0, void 0, function () {
16953
- var candidates, firstExisting, firstNestedGitRoot, candidates_8, candidates_8_1, candidate, _a, gitRoot, nestedGitRoots, e_44_1;
16954
- var e_44, _b;
17172
+ var candidates, firstExisting, firstNestedGitRoot, candidates_8, candidates_8_1, candidate, _a, gitRoot, nestedGitRoots, e_45_1;
17173
+ var e_45, _b;
16955
17174
  return __generator(this, function (_c) {
16956
17175
  switch (_c.label) {
16957
17176
  case 0:
@@ -16998,14 +17217,14 @@ function resolveAssistantWorkspaceRoot() {
16998
17217
  return [3 /*break*/, 2];
16999
17218
  case 8: return [3 /*break*/, 11];
17000
17219
  case 9:
17001
- e_44_1 = _c.sent();
17002
- e_44 = { error: e_44_1 };
17220
+ e_45_1 = _c.sent();
17221
+ e_45 = { error: e_45_1 };
17003
17222
  return [3 /*break*/, 11];
17004
17223
  case 10:
17005
17224
  try {
17006
17225
  if (candidates_8_1 && !candidates_8_1.done && (_b = candidates_8.return)) _b.call(candidates_8);
17007
17226
  }
17008
- finally { if (e_44) throw e_44.error; }
17227
+ finally { if (e_45) throw e_45.error; }
17009
17228
  return [7 /*endfinally*/];
17010
17229
  case 11:
17011
17230
  if (firstNestedGitRoot) {
@@ -17408,7 +17627,7 @@ var AI_ASSISTANT_BREAKDOWN_DIMENSION_STOPWORDS = new Set([
17408
17627
  'by'
17409
17628
  ]);
17410
17629
  function normalizeAssistantBreakdownDimension(value) {
17411
- var e_45, _a;
17630
+ var e_46, _a;
17412
17631
  var normalized = normalizeOptionalString(value)
17413
17632
  .toLowerCase()
17414
17633
  .replace(/[^a-z0-9_\s-]+/g, ' ')
@@ -17440,12 +17659,12 @@ function normalizeAssistantBreakdownDimension(value) {
17440
17659
  }
17441
17660
  }
17442
17661
  }
17443
- catch (e_45_1) { e_45 = { error: e_45_1 }; }
17662
+ catch (e_46_1) { e_46 = { error: e_46_1 }; }
17444
17663
  finally {
17445
17664
  try {
17446
17665
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
17447
17666
  }
17448
- finally { if (e_45) throw e_45.error; }
17667
+ finally { if (e_46) throw e_46.error; }
17449
17668
  }
17450
17669
  if (!kept.length) {
17451
17670
  return '';
@@ -17643,7 +17862,7 @@ function resolveAssistantPlannerEnabled() {
17643
17862
  return raw === undefined ? true : raw === true;
17644
17863
  }
17645
17864
  function resolveAssistantPlannerKnownRoutes(user, isSuperAdmin) {
17646
- var e_46, _a;
17865
+ var e_47, _a;
17647
17866
  var _b;
17648
17867
  if (isSuperAdmin === void 0) { isSuperAdmin = false; }
17649
17868
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
@@ -17657,12 +17876,12 @@ function resolveAssistantPlannerKnownRoutes(user, isSuperAdmin) {
17657
17876
  }
17658
17877
  }
17659
17878
  }
17660
- catch (e_46_1) { e_46 = { error: e_46_1 }; }
17879
+ catch (e_47_1) { e_47 = { error: e_47_1 }; }
17661
17880
  finally {
17662
17881
  try {
17663
17882
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
17664
17883
  }
17665
- finally { if (e_46) throw e_46.error; }
17884
+ finally { if (e_47) throw e_47.error; }
17666
17885
  }
17667
17886
  var normalizedRoutes = Array.from(unique);
17668
17887
  var allowedRoutes = collectAssistantAllowedRoutesForUser(user, normalizedRoutes, isSuperAdmin);
@@ -17901,7 +18120,7 @@ function normalizeRouteMatchKey(value) {
17901
18120
  return normalizeRouteKey(value).toLowerCase();
17902
18121
  }
17903
18122
  function buildClientRouteIndex() {
17904
- var e_47, _a;
18123
+ var e_48, _a;
17905
18124
  var _b;
17906
18125
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
17907
18126
  var set = new Set();
@@ -17920,12 +18139,12 @@ function buildClientRouteIndex() {
17920
18139
  }
17921
18140
  }
17922
18141
  }
17923
- catch (e_47_1) { e_47 = { error: e_47_1 }; }
18142
+ catch (e_48_1) { e_48 = { error: e_48_1 }; }
17924
18143
  finally {
17925
18144
  try {
17926
18145
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
17927
18146
  }
17928
- finally { if (e_47) throw e_47.error; }
18147
+ finally { if (e_48) throw e_48.error; }
17929
18148
  }
17930
18149
  return { set: set, map: map, size: routes.length };
17931
18150
  }
@@ -18091,16 +18310,15 @@ function collectAssistantAllowedRoutesForUser(user, allRoutes, isSuperAdmin) {
18091
18310
  seen.add(normalized);
18092
18311
  allowed.push(normalized);
18093
18312
  };
18094
- var allRouteEntries = normalizedRoutes.map(function (route) { return ({ route: route, routeKey: route.toLowerCase() }); });
18313
+ var allRouteEntries = normalizedRoutes.map(function (route) { return ({ route: route }); });
18095
18314
  views.forEach(function (view) {
18096
- var viewKey = view.toLowerCase();
18097
- var canonical = normalizedRoutes.find(function (route) { return route.toLowerCase() === viewKey; });
18315
+ var canonical = normalizedRoutes.find(function (route) { return normalizeRouteMatchKey(route) === normalizeRouteMatchKey(view); });
18098
18316
  if (canonical) {
18099
18317
  push(canonical);
18100
18318
  }
18101
18319
  var matched = false;
18102
18320
  allRouteEntries.forEach(function (entry) {
18103
- if (entry.routeKey === viewKey || entry.routeKey.startsWith("".concat(viewKey, "/"))) {
18321
+ if (isAssistantViewPermissionMatch(view, entry.route)) {
18104
18322
  push(entry.route);
18105
18323
  matched = true;
18106
18324
  }
@@ -18565,7 +18783,7 @@ function userHasAssistantChangeModuleAccess(user, module) {
18565
18783
  case 'delivery':
18566
18784
  return userHasViewTokenPermission(user, /delivery|route|dispatch|work[-_/ ]?order|bol|pso|sales[-_/ ]?order|truck[-_/ ]?treat(?:ing)?|treater|specialty|batch[-_/ ]?(?:treat(?:ing)?|job)|continuous|ats|automated[-_/ ]?treatment[-_/ ]?system|isotank|chemical[-_/ ]?trailer|vac[-_/ ]?truck|asset|treatment[-_/ ]?plan|treatments?/i);
18567
18785
  case 'blend':
18568
- return userHasViewTokenPermission(user, /blend|chemical|mix/i);
18786
+ return userHasViewTokenPermission(user, /blend|mix/i);
18569
18787
  case 'chemical':
18570
18788
  return userHasViewTokenPermission(user, /chemical|blend|product|item|inventory/i);
18571
18789
  case 'job':
@@ -18705,8 +18923,8 @@ function shouldSkipAssistantGitDiscoveryDirectory(name) {
18705
18923
  }
18706
18924
  function resolveAssistantWorkspaceGitRoots(workspaceRoot) {
18707
18925
  return __awaiter(this, void 0, void 0, function () {
18708
- var roots, seen, push, _a, configuredRoots, configuredRoots_1, configuredRoots_1_1, configuredRoot, _b, e_48_1, queue, queued, enqueue, next, entries, _c, entries_1, entries_1_1, entry, childName, candidate, gitPath, _d, e_49_1;
18709
- var e_48, _e, e_49, _f;
18926
+ var roots, seen, push, _a, configuredRoots, configuredRoots_1, configuredRoots_1_1, configuredRoot, _b, e_49_1, queue, queued, enqueue, next, entries, _c, entries_1, entries_1_1, entry, childName, candidate, gitPath, _d, e_50_1;
18927
+ var e_49, _e, e_50, _f;
18710
18928
  var _g;
18711
18929
  return __generator(this, function (_h) {
18712
18930
  switch (_h.label) {
@@ -18751,14 +18969,14 @@ function resolveAssistantWorkspaceGitRoots(workspaceRoot) {
18751
18969
  return [3 /*break*/, 3];
18752
18970
  case 6: return [3 /*break*/, 9];
18753
18971
  case 7:
18754
- e_48_1 = _h.sent();
18755
- e_48 = { error: e_48_1 };
18972
+ e_49_1 = _h.sent();
18973
+ e_49 = { error: e_49_1 };
18756
18974
  return [3 /*break*/, 9];
18757
18975
  case 8:
18758
18976
  try {
18759
18977
  if (configuredRoots_1_1 && !configuredRoots_1_1.done && (_e = configuredRoots_1.return)) _e.call(configuredRoots_1);
18760
18978
  }
18761
- finally { if (e_48) throw e_48.error; }
18979
+ finally { if (e_49) throw e_49.error; }
18762
18980
  return [7 /*endfinally*/];
18763
18981
  case 9:
18764
18982
  queue = [];
@@ -18798,7 +19016,7 @@ function resolveAssistantWorkspaceGitRoots(workspaceRoot) {
18798
19016
  return [3 /*break*/, 14];
18799
19017
  case 14:
18800
19018
  _h.trys.push([14, 21, 22, 23]);
18801
- entries_1 = (e_49 = void 0, __values(entries)), entries_1_1 = entries_1.next();
19019
+ entries_1 = (e_50 = void 0, __values(entries)), entries_1_1 = entries_1.next();
18802
19020
  _h.label = 15;
18803
19021
  case 15:
18804
19022
  if (!!entries_1_1.done) return [3 /*break*/, 20];
@@ -18837,14 +19055,14 @@ function resolveAssistantWorkspaceGitRoots(workspaceRoot) {
18837
19055
  return [3 /*break*/, 15];
18838
19056
  case 20: return [3 /*break*/, 23];
18839
19057
  case 21:
18840
- e_49_1 = _h.sent();
18841
- e_49 = { error: e_49_1 };
19058
+ e_50_1 = _h.sent();
19059
+ e_50 = { error: e_50_1 };
18842
19060
  return [3 /*break*/, 23];
18843
19061
  case 22:
18844
19062
  try {
18845
19063
  if (entries_1_1 && !entries_1_1.done && (_f = entries_1.return)) _f.call(entries_1);
18846
19064
  }
18847
- finally { if (e_49) throw e_49.error; }
19065
+ finally { if (e_50) throw e_50.error; }
18848
19066
  return [7 /*endfinally*/];
18849
19067
  case 23: return [3 /*break*/, 10];
18850
19068
  case 24: return [2 /*return*/, roots];
@@ -19147,8 +19365,8 @@ function syncAssistantGitMirror(repoUrl) {
19147
19365
  }
19148
19366
  function resolveAssistantChangeHistoryGitRoots(workspaceRoot) {
19149
19367
  return __awaiter(this, void 0, void 0, function () {
19150
- var roots, repoUrls, mirroredRoots, repoUrls_1, repoUrls_1_1, repoUrl, mirrorRoot, e_50_1;
19151
- var e_50, _a;
19368
+ var roots, repoUrls, mirroredRoots, repoUrls_1, repoUrls_1_1, repoUrl, mirrorRoot, e_51_1;
19369
+ var e_51, _a;
19152
19370
  return __generator(this, function (_b) {
19153
19371
  switch (_b.label) {
19154
19372
  case 0: return [4 /*yield*/, resolveAssistantWorkspaceGitRoots(workspaceRoot)];
@@ -19182,14 +19400,14 @@ function resolveAssistantChangeHistoryGitRoots(workspaceRoot) {
19182
19400
  return [3 /*break*/, 3];
19183
19401
  case 6: return [3 /*break*/, 9];
19184
19402
  case 7:
19185
- e_50_1 = _b.sent();
19186
- e_50 = { error: e_50_1 };
19403
+ e_51_1 = _b.sent();
19404
+ e_51 = { error: e_51_1 };
19187
19405
  return [3 /*break*/, 9];
19188
19406
  case 8:
19189
19407
  try {
19190
19408
  if (repoUrls_1_1 && !repoUrls_1_1.done && (_a = repoUrls_1.return)) _a.call(repoUrls_1);
19191
19409
  }
19192
- finally { if (e_50) throw e_50.error; }
19410
+ finally { if (e_51) throw e_51.error; }
19193
19411
  return [7 /*endfinally*/];
19194
19412
  case 9: return [2 /*return*/, mirroredRoots];
19195
19413
  }
@@ -19198,8 +19416,8 @@ function resolveAssistantChangeHistoryGitRoots(workspaceRoot) {
19198
19416
  }
19199
19417
  function resolveAssistantChangeHistoryFastPathResponse(params) {
19200
19418
  return __awaiter(this, void 0, void 0, function () {
19201
- var workspaceRoot, _a, gitRoots, featureKeywords, sawExecutionError, bestFallback, gitRoots_1, gitRoots_1_1, gitRoot, _b, branch, _c, _d, limit, historyDepth, rawHistory, commits, summary, hasKeywordMatches, _e, e_51_1;
19202
- var e_51, _f;
19419
+ var workspaceRoot, _a, gitRoots, featureKeywords, sawExecutionError, bestFallback, gitRoots_1, gitRoots_1_1, gitRoot, _b, branch, _c, _d, limit, historyDepth, rawHistory, commits, summary, hasKeywordMatches, _e, e_52_1;
19420
+ var e_52, _f;
19203
19421
  return __generator(this, function (_g) {
19204
19422
  switch (_g.label) {
19205
19423
  case 0:
@@ -19321,14 +19539,14 @@ function resolveAssistantChangeHistoryFastPathResponse(params) {
19321
19539
  return [3 /*break*/, 7];
19322
19540
  case 20: return [3 /*break*/, 23];
19323
19541
  case 21:
19324
- e_51_1 = _g.sent();
19325
- e_51 = { error: e_51_1 };
19542
+ e_52_1 = _g.sent();
19543
+ e_52 = { error: e_52_1 };
19326
19544
  return [3 /*break*/, 23];
19327
19545
  case 22:
19328
19546
  try {
19329
19547
  if (gitRoots_1_1 && !gitRoots_1_1.done && (_f = gitRoots_1.return)) _f.call(gitRoots_1);
19330
19548
  }
19331
- finally { if (e_51) throw e_51.error; }
19549
+ finally { if (e_52) throw e_52.error; }
19332
19550
  return [7 /*endfinally*/];
19333
19551
  case 23:
19334
19552
  if (bestFallback) {
@@ -19509,7 +19727,7 @@ function sanitizeAssistantResponse(value) {
19509
19727
  return normalizeAssistantRoutes(normalizedCurrency);
19510
19728
  }
19511
19729
  function evaluateAssistantGuardrails(message) {
19512
- var e_52, _a;
19730
+ var e_53, _a;
19513
19731
  var normalized = String(message || '').toLowerCase();
19514
19732
  var identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(normalized);
19515
19733
  if (identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked) {
@@ -19559,12 +19777,12 @@ function evaluateAssistantGuardrails(message) {
19559
19777
  }
19560
19778
  }
19561
19779
  }
19562
- catch (e_52_1) { e_52 = { error: e_52_1 }; }
19780
+ catch (e_53_1) { e_53 = { error: e_53_1 }; }
19563
19781
  finally {
19564
19782
  try {
19565
19783
  if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
19566
19784
  }
19567
- finally { if (e_52) throw e_52.error; }
19785
+ finally { if (e_53) throw e_53.error; }
19568
19786
  }
19569
19787
  return null;
19570
19788
  }
@@ -19679,7 +19897,7 @@ function tokenizeArithmeticExpression(expression) {
19679
19897
  return tokens;
19680
19898
  }
19681
19899
  function evaluateArithmeticExpression(expression) {
19682
- var e_53, _a, e_54, _b;
19900
+ var e_54, _a, e_55, _b;
19683
19901
  var tokens = tokenizeArithmeticExpression(expression);
19684
19902
  if (!tokens || !tokens.length) {
19685
19903
  return null;
@@ -19736,12 +19954,12 @@ function evaluateArithmeticExpression(expression) {
19736
19954
  prevToken = token;
19737
19955
  }
19738
19956
  }
19739
- catch (e_53_1) { e_53 = { error: e_53_1 }; }
19957
+ catch (e_54_1) { e_54 = { error: e_54_1 }; }
19740
19958
  finally {
19741
19959
  try {
19742
19960
  if (tokens_2_1 && !tokens_2_1.done && (_a = tokens_2.return)) _a.call(tokens_2);
19743
19961
  }
19744
- finally { if (e_53) throw e_53.error; }
19962
+ finally { if (e_54) throw e_54.error; }
19745
19963
  }
19746
19964
  while (ops.length) {
19747
19965
  var op = ops.pop();
@@ -19781,12 +19999,12 @@ function evaluateArithmeticExpression(expression) {
19781
19999
  stack.push(Number(token));
19782
20000
  }
19783
20001
  }
19784
- catch (e_54_1) { e_54 = { error: e_54_1 }; }
20002
+ catch (e_55_1) { e_55 = { error: e_55_1 }; }
19785
20003
  finally {
19786
20004
  try {
19787
20005
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
19788
20006
  }
19789
- finally { if (e_54) throw e_54.error; }
20007
+ finally { if (e_55) throw e_55.error; }
19790
20008
  }
19791
20009
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
19792
20010
  return null;
@@ -19970,8 +20188,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
19970
20188
  }
19971
20189
  function readAttachmentContents(attachments) {
19972
20190
  return __awaiter(this, void 0, void 0, function () {
19973
- var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_55_1;
19974
- var e_55, _b;
20191
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_56_1;
20192
+ var e_56, _b;
19975
20193
  return __generator(this, function (_c) {
19976
20194
  switch (_c.label) {
19977
20195
  case 0:
@@ -20050,14 +20268,14 @@ function readAttachmentContents(attachments) {
20050
20268
  return [3 /*break*/, 2];
20051
20269
  case 10: return [3 /*break*/, 13];
20052
20270
  case 11:
20053
- e_55_1 = _c.sent();
20054
- e_55 = { error: e_55_1 };
20271
+ e_56_1 = _c.sent();
20272
+ e_56 = { error: e_56_1 };
20055
20273
  return [3 /*break*/, 13];
20056
20274
  case 12:
20057
20275
  try {
20058
20276
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
20059
20277
  }
20060
- finally { if (e_55) throw e_55.error; }
20278
+ finally { if (e_56) throw e_56.error; }
20061
20279
  return [7 /*endfinally*/];
20062
20280
  case 13: return [2 /*return*/, {
20063
20281
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -20153,25 +20371,36 @@ function resolveClientIdFromConfig(explicit, contextUserId) {
20153
20371
  }
20154
20372
  function ensureConversation(input, mode, contextUserId) {
20155
20373
  return __awaiter(this, void 0, void 0, function () {
20156
- var idConversation, existing, now, resolvedClientId, doc, result;
20374
+ var idUser, idConversation, existing, existingUserId, now, resolvedClientId, doc, result;
20157
20375
  return __generator(this, function (_a) {
20158
20376
  switch (_a.label) {
20159
20377
  case 0:
20378
+ idUser = normalizeOptionalString(contextUserId);
20379
+ if (!idUser) {
20380
+ throw new Error('Unauthorized.');
20381
+ }
20160
20382
  idConversation = normalizeOptionalString(input.id_conversation);
20161
20383
  if (!idConversation) return [3 /*break*/, 2];
20162
20384
  return [4 /*yield*/, ai_terminal_conversation_collection_1.AiTerminalConversations.findById(idConversation)];
20163
20385
  case 1:
20164
20386
  existing = _a.sent();
20165
20387
  if (existing) {
20166
- return [2 /*return*/, existing];
20388
+ existingUserId = normalizeOptionalString(existing.id_user);
20389
+ if (existingUserId && existingUserId === idUser) {
20390
+ return [2 /*return*/, existing];
20391
+ }
20392
+ if (existingUserId && existingUserId !== idUser) {
20393
+ throw new Error('Conversation access denied.');
20394
+ }
20167
20395
  }
20168
20396
  _a.label = 2;
20169
20397
  case 2:
20170
20398
  now = new Date();
20171
- return [4 /*yield*/, resolveClientIdFromConfig(input.id_client, contextUserId)];
20399
+ return [4 /*yield*/, resolveClientIdFromConfig(input.id_client, idUser)];
20172
20400
  case 3:
20173
20401
  resolvedClientId = _a.sent();
20174
20402
  doc = {
20403
+ id_user: idUser,
20175
20404
  id_client: resolvedClientId,
20176
20405
  id_app: normalizeOptionalString(input.id_app),
20177
20406
  title: 'New Conversation',
@@ -20381,7 +20610,7 @@ function estimateUsage(messages, responseText, model) {
20381
20610
  };
20382
20611
  }
20383
20612
  function evaluateGuardrails(message) {
20384
- var e_56, _a;
20613
+ var e_57, _a;
20385
20614
  var normalized = String(message || '').toLowerCase();
20386
20615
  var identityGuardrail = evaluateAssistantIdentityDisclosureGuardrail(normalized);
20387
20616
  if (identityGuardrail === null || identityGuardrail === void 0 ? void 0 : identityGuardrail.blocked) {
@@ -20407,12 +20636,12 @@ function evaluateGuardrails(message) {
20407
20636
  }
20408
20637
  }
20409
20638
  }
20410
- catch (e_56_1) { e_56 = { error: e_56_1 }; }
20639
+ catch (e_57_1) { e_57 = { error: e_57_1 }; }
20411
20640
  finally {
20412
20641
  try {
20413
20642
  if (patterns_3_1 && !patterns_3_1.done && (_a = patterns_3.return)) _a.call(patterns_3);
20414
20643
  }
20415
- finally { if (e_56) throw e_56.error; }
20644
+ finally { if (e_57) throw e_57.error; }
20416
20645
  }
20417
20646
  return null;
20418
20647
  }