@resolveio/server-lib 22.1.7 → 22.1.8

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.
@@ -132,6 +132,7 @@ exports.collectUserViewPermissions = collectUserViewPermissions;
132
132
  exports.userHasInvoiceAccess = userHasInvoiceAccess;
133
133
  exports.resolveAssistantUserAccessTier = resolveAssistantUserAccessTier;
134
134
  exports.resolveCodexThoughtLevel = resolveCodexThoughtLevel;
135
+ exports.buildAssistantWorkspaceRootCandidates = buildAssistantWorkspaceRootCandidates;
135
136
  exports.classifyAssistantRequestType = classifyAssistantRequestType;
136
137
  exports.shouldRunAssistantPlanner = shouldRunAssistantPlanner;
137
138
  exports.collectAssistantAllowedRoutesForUser = collectAssistantAllowedRoutesForUser;
@@ -392,33 +393,10 @@ var AI_ASSISTANT_FIELD_TOKEN_SYNONYMS = {
392
393
  payment: ['paid', 'revenue', 'sales', 'billing', 'total', 'amount']
393
394
  };
394
395
  var AI_ASSISTANT_ID_LOOKUP_HINTS = {
395
- customer: ['customers', 'customer-versions'],
396
- chemical: ['chemicals', 'chemical-versions'],
397
- well: ['wells', 'well-groups', 'production-locations', 'locations'],
398
- location: ['locations', 'production-locations'],
399
- invoice: ['invoices']
396
+ user: ['users', 'user-versions'],
397
+ supportticket: ['support-tickets', 'support-ticket']
400
398
  };
401
399
  var AI_ASSISTANT_TERM_SYNONYMS = [
402
- {
403
- label: 'truck treating jobs',
404
- pattern: /\btruck\s+treating\s+jobs?\b/i,
405
- expansions: ['truck treating deliveries', 'truck-treating-deliveries', 'truck treating route events']
406
- },
407
- {
408
- label: 'active clients',
409
- pattern: /\b(?:how\s+many\s+)?active\s+(?:clients?|customers?)\b/i,
410
- expansions: ['customers', 'clients', 'customer status', 'client status']
411
- },
412
- {
413
- label: 'blend tickets',
414
- pattern: /\bblend(?:ing)?\s+tickets?\b/i,
415
- expansions: ['chemical blends', 'chemical-blends', 'report-chemical-blends', 'blend batches']
416
- },
417
- {
418
- label: 'revenue',
419
- pattern: /\b(revenue|sales|billing)\b/i,
420
- expansions: ['invoice', 'invoices', 'paid invoices', 'invoice payments', 'billing', 'sales']
421
- },
422
400
  {
423
401
  label: 'support tickets',
424
402
  pattern: /\bsupport[\s-]*tickets?\b/i,
@@ -3204,12 +3182,12 @@ function executeAiAssistantMongoRead(payload, context) {
3204
3182
  }
3205
3183
  function executeAiAssistantMongoAggregate(payload, context) {
3206
3184
  return __awaiter(this, void 0, void 0, function () {
3207
- var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, crossCollectionCandidates, crossCollectionCandidates_2, crossCollectionCandidates_2_1, candidateCollection, fallbackPayload, fallbackResult, existingFallbacks, e_2_1, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
3208
- var e_2, _o;
3185
+ var input, rawCollection, retryState, triedCollections, crossCollectionRetryEnabled, dbName, db, collectionResolution, collection, bridgeCollection, retryRootCollection, schemaFields, effectivePermissionView, _a, user, isSuperAdmin, customerId, fallbackMeta, baseQuery, stripped, userId, normalizedClient, shouldScopeByClient, _b, clientScopedQuery, scopedQuery, normalizedPipeline, sanitizedPipeline, strippedPipeline, pipelineWithScope, normalizedOptions, limitedPipeline, executedPipeline, dateField, aggregateOptions, runAggregateWithRepair, initialAggregate, documents, probeDocs, fallback, fallbackPipeline, fallbackAggregate, fallbackDocs, createdFallback, createdPipeline, createdAggregate, createdDocs, expanded, expandedAggregate, expandedDocs, completionFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, completionExprFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, unwindFallback, shouldUnwind, _c, _d, fallbackPipeline, fallbackAggregate, fallbackDocs, nameFallback, fallbackPipeline, fallbackAggregate, fallbackDocs, _e, _loop_1, i, state_1, matchFields_1, _f, aliases, rewrittenPipeline, fallbackAggregate, fallbackDocs, _loop_2, i, state_2, nestedFallbacks, nestedFallbacks_1, nestedFallbacks_1_1, nestedFallback, fallbackPayload, fallbackResult, existingFallbacks, error_6, errorMessage, existingErrors, e_2_1, baseCollection, fallbackPayload, fallbackResult, existingFallbacks, crossCollectionCandidates, crossCollectionCandidates_2, crossCollectionCandidates_2_1, candidateCollection, fallbackPayload, fallbackResult, existingFallbacks, e_3_1, matchStages, diagnostics, combinedMatch, nameFields, dateFields, queryNoName, _g, queryNoDate, _h, _j, _k, _l, allCollections, base, alt, altCount, _m, verification, sanitizedDocuments, includeIds, displayDocs, idLookupDisplay, display;
3186
+ var e_2, _o, e_3, _p;
3209
3187
  var _this = this;
3210
- var _p, _q;
3211
- return __generator(this, function (_r) {
3212
- switch (_r.label) {
3188
+ var _q, _r;
3189
+ return __generator(this, function (_s) {
3190
+ switch (_s.label) {
3213
3191
  case 0:
3214
3192
  input = payload || {};
3215
3193
  rawCollection = normalizeOptionalString(input.collection);
@@ -3226,11 +3204,11 @@ function executeAiAssistantMongoAggregate(payload, context) {
3226
3204
  db = resolveio_server_app_1.ResolveIOServer.getMongoConnection().db(dbName);
3227
3205
  return [4 /*yield*/, resolveAssistantCollectionName(db, dbName, rawCollection)];
3228
3206
  case 1:
3229
- collectionResolution = _r.sent();
3207
+ collectionResolution = _s.sent();
3230
3208
  collection = collectionResolution.name || rawCollection;
3231
3209
  return [4 /*yield*/, resolveAssistantReportBuilderBridgeCollection(collection, db, dbName)];
3232
3210
  case 2:
3233
- bridgeCollection = _r.sent();
3211
+ bridgeCollection = _s.sent();
3234
3212
  if (bridgeCollection.fallbackFrom) {
3235
3213
  collection = bridgeCollection.collection;
3236
3214
  }
@@ -3242,11 +3220,11 @@ function executeAiAssistantMongoAggregate(payload, context) {
3242
3220
  : input.permissionView;
3243
3221
  return [4 /*yield*/, ensureAssistantReadAccess(context, effectivePermissionView, collection)];
3244
3222
  case 3:
3245
- _a = _r.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
3223
+ _a = _s.sent(), user = _a.user, isSuperAdmin = _a.isSuperAdmin;
3246
3224
  if (!isSuperAdmin && AI_ASSISTANT_BLOCKED_COLLECTIONS.has(collection)) {
3247
3225
  throw new Error('AI assistant report builder bridge: Access denied.');
3248
3226
  }
3249
- customerId = normalizeOptionalString((_p = user === null || user === void 0 ? void 0 : user.other) === null || _p === void 0 ? void 0 : _p.id_customer);
3227
+ customerId = normalizeOptionalString((_q = user === null || user === void 0 ? void 0 : user.other) === null || _q === void 0 ? void 0 : _q.id_customer);
3250
3228
  fallbackMeta = {};
3251
3229
  if (bridgeCollection.fallbackFrom) {
3252
3230
  fallbackMeta.reportBuilderBridge = {
@@ -3283,11 +3261,11 @@ function executeAiAssistantMongoAggregate(payload, context) {
3283
3261
  if (!(!isSuperAdmin && normalizedClient)) return [3 /*break*/, 5];
3284
3262
  return [4 /*yield*/, collectionHasClientIndex(db, dbName, collection)];
3285
3263
  case 4:
3286
- _b = _r.sent();
3264
+ _b = _s.sent();
3287
3265
  return [3 /*break*/, 6];
3288
3266
  case 5:
3289
3267
  _b = false;
3290
- _r.label = 6;
3268
+ _s.label = 6;
3291
3269
  case 6:
3292
3270
  shouldScopeByClient = _b;
3293
3271
  clientScopedQuery = shouldScopeByClient
@@ -3315,7 +3293,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3315
3293
  }
3316
3294
  aggregateOptions = __assign(__assign({}, normalizedOptions.aggregateOptions), { readPreference: AI_ASSISTANT_READ_PREFERENCE });
3317
3295
  runAggregateWithRepair = function (pipeline, stage) { return __awaiter(_this, void 0, void 0, function () {
3318
- var docs, error_6, isDateRepair, isRankSortByRepair, repaired, docs;
3296
+ var docs, error_7, isDateRepair, isRankSortByRepair, repaired, docs;
3319
3297
  return __generator(this, function (_a) {
3320
3298
  switch (_a.label) {
3321
3299
  case 0:
@@ -3327,17 +3305,17 @@ function executeAiAssistantMongoAggregate(payload, context) {
3327
3305
  docs = _a.sent();
3328
3306
  return [2 /*return*/, { documents: docs, pipeline: pipeline }];
3329
3307
  case 2:
3330
- error_6 = _a.sent();
3331
- isDateRepair = isAssistantDateArithmeticArgumentError(error_6);
3332
- isRankSortByRepair = isAssistantRankSortByError(error_6);
3308
+ error_7 = _a.sent();
3309
+ isDateRepair = isAssistantDateArithmeticArgumentError(error_7);
3310
+ isRankSortByRepair = isAssistantRankSortByError(error_7);
3333
3311
  if (!isDateRepair && !isRankSortByRepair) {
3334
- throw error_6;
3312
+ throw error_7;
3335
3313
  }
3336
3314
  repaired = isDateRepair
3337
3315
  ? repairAssistantDateArithmeticInPipeline(pipeline)
3338
3316
  : repairAssistantRankSortByInPipeline(pipeline);
3339
3317
  if (!repaired.changed || containsForbiddenMongoOperators(repaired.pipeline)) {
3340
- throw error_6;
3318
+ throw error_7;
3341
3319
  }
3342
3320
  return [4 /*yield*/, db.collection(collection)
3343
3321
  .aggregate(repaired.pipeline, aggregateOptions)
@@ -3367,7 +3345,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3367
3345
  }); };
3368
3346
  return [4 /*yield*/, runAggregateWithRepair(executedPipeline, 'initial')];
3369
3347
  case 7:
3370
- initialAggregate = _r.sent();
3348
+ initialAggregate = _s.sent();
3371
3349
  documents = initialAggregate.documents;
3372
3350
  executedPipeline = initialAggregate.pipeline;
3373
3351
  dateField = findAggregateDateField(executedPipeline);
@@ -3380,14 +3358,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3380
3358
  if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 9];
3381
3359
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'date_field_fallback')];
3382
3360
  case 8:
3383
- fallbackAggregate = _r.sent();
3361
+ fallbackAggregate = _s.sent();
3384
3362
  fallbackDocs = fallbackAggregate.documents;
3385
3363
  if (fallbackDocs.length) {
3386
3364
  documents = fallbackDocs;
3387
3365
  executedPipeline = fallbackAggregate.pipeline;
3388
3366
  fallbackMeta.dateField.used = true;
3389
3367
  }
3390
- _r.label = 9;
3368
+ _s.label = 9;
3391
3369
  case 9:
3392
3370
  if (!(!documents.length && dateField !== 'createdAt')) return [3 /*break*/, 11];
3393
3371
  createdFallback = { from: dateField, to: 'createdAt', attempted: true, used: false };
@@ -3396,14 +3374,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3396
3374
  if (!!containsForbiddenMongoOperators(createdPipeline)) return [3 /*break*/, 11];
3397
3375
  return [4 /*yield*/, runAggregateWithRepair(createdPipeline, 'date_field_created_at')];
3398
3376
  case 10:
3399
- createdAggregate = _r.sent();
3377
+ createdAggregate = _s.sent();
3400
3378
  createdDocs = createdAggregate.documents;
3401
3379
  if (createdDocs.length) {
3402
3380
  documents = createdDocs;
3403
3381
  executedPipeline = createdAggregate.pipeline;
3404
3382
  fallbackMeta.dateFieldCreatedAt.used = true;
3405
3383
  }
3406
- _r.label = 11;
3384
+ _s.label = 11;
3407
3385
  case 11:
3408
3386
  if (!!documents.length) return [3 /*break*/, 13];
3409
3387
  expanded = expandAggregateDateMatchFallback(executedPipeline, schemaFields);
@@ -3416,14 +3394,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3416
3394
  if (!!containsForbiddenMongoOperators(expanded.pipeline)) return [3 /*break*/, 13];
3417
3395
  return [4 /*yield*/, runAggregateWithRepair(expanded.pipeline, 'date_fields_expanded')];
3418
3396
  case 12:
3419
- expandedAggregate = _r.sent();
3397
+ expandedAggregate = _s.sent();
3420
3398
  expandedDocs = expandedAggregate.documents;
3421
3399
  if (expandedDocs.length) {
3422
3400
  documents = expandedDocs;
3423
3401
  executedPipeline = expandedAggregate.pipeline;
3424
3402
  fallbackMeta.dateFieldsExpanded.used = true;
3425
3403
  }
3426
- _r.label = 13;
3404
+ _s.label = 13;
3427
3405
  case 13:
3428
3406
  if (!!documents.length) return [3 /*break*/, 17];
3429
3407
  completionFallback = resolveAggregateCompletionFallback(executedPipeline);
@@ -3440,14 +3418,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3440
3418
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 15];
3441
3419
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'completion_add_fields')];
3442
3420
  case 14:
3443
- fallbackAggregate = _r.sent();
3421
+ fallbackAggregate = _s.sent();
3444
3422
  fallbackDocs = fallbackAggregate.documents;
3445
3423
  if (fallbackDocs.length) {
3446
3424
  documents = fallbackDocs;
3447
3425
  executedPipeline = fallbackAggregate.pipeline;
3448
3426
  fallbackMeta.completion.used = true;
3449
3427
  }
3450
- _r.label = 15;
3428
+ _s.label = 15;
3451
3429
  case 15:
3452
3430
  if (!!documents.length) return [3 /*break*/, 17];
3453
3431
  completionExprFallback = resolveAggregateCompletionExprFallback(executedPipeline);
@@ -3464,23 +3442,23 @@ function executeAiAssistantMongoAggregate(payload, context) {
3464
3442
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 17];
3465
3443
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'completion_expr')];
3466
3444
  case 16:
3467
- fallbackAggregate = _r.sent();
3445
+ fallbackAggregate = _s.sent();
3468
3446
  fallbackDocs = fallbackAggregate.documents;
3469
3447
  if (fallbackDocs.length) {
3470
3448
  documents = fallbackDocs;
3471
3449
  executedPipeline = fallbackAggregate.pipeline;
3472
3450
  fallbackMeta.completion.used = true;
3473
3451
  }
3474
- _r.label = 17;
3452
+ _s.label = 17;
3475
3453
  case 17:
3476
3454
  if (!(documents.length <= 1)) return [3 /*break*/, 26];
3477
3455
  unwindFallback = resolveAggregateUnwindFallback(executedPipeline);
3478
3456
  if (!unwindFallback) return [3 /*break*/, 26];
3479
3457
  fallbackMeta.unwind = { path: unwindFallback.path, attempted: true, used: false };
3480
3458
  shouldUnwind = false;
3481
- _r.label = 18;
3459
+ _s.label = 18;
3482
3460
  case 18:
3483
- _r.trys.push([18, 21, , 22]);
3461
+ _s.trys.push([18, 21, , 22]);
3484
3462
  _c = probeDocs;
3485
3463
  if (_c) return [3 /*break*/, 20];
3486
3464
  return [4 /*yield*/, fetchAssistantProbeDocs({
@@ -3492,14 +3470,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3492
3470
  includeClientScope: shouldScopeByClient
3493
3471
  })];
3494
3472
  case 19:
3495
- _c = (_r.sent());
3496
- _r.label = 20;
3473
+ _c = (_s.sent());
3474
+ _s.label = 20;
3497
3475
  case 20:
3498
3476
  probeDocs = _c;
3499
3477
  shouldUnwind = probeDocs.length ? hasArrayValueAtPath(probeDocs, unwindFallback.path) : false;
3500
3478
  return [3 /*break*/, 22];
3501
3479
  case 21:
3502
- _d = _r.sent();
3480
+ _d = _s.sent();
3503
3481
  shouldUnwind = false;
3504
3482
  return [3 /*break*/, 22];
3505
3483
  case 22:
@@ -3508,18 +3486,18 @@ function executeAiAssistantMongoAggregate(payload, context) {
3508
3486
  if (!!containsForbiddenMongoOperators(fallbackPipeline)) return [3 /*break*/, 24];
3509
3487
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'unwind')];
3510
3488
  case 23:
3511
- fallbackAggregate = _r.sent();
3489
+ fallbackAggregate = _s.sent();
3512
3490
  fallbackDocs = fallbackAggregate.documents;
3513
3491
  if (fallbackDocs.length > documents.length) {
3514
3492
  documents = fallbackDocs;
3515
3493
  executedPipeline = fallbackAggregate.pipeline;
3516
3494
  fallbackMeta.unwind.used = true;
3517
3495
  }
3518
- _r.label = 24;
3496
+ _s.label = 24;
3519
3497
  case 24: return [3 /*break*/, 26];
3520
3498
  case 25:
3521
3499
  fallbackMeta.unwind.skipped = 'not_array';
3522
- _r.label = 26;
3500
+ _s.label = 26;
3523
3501
  case 26:
3524
3502
  if (!!documents.length) return [3 /*break*/, 28];
3525
3503
  nameFallback = resolveAggregateNameMatchFallback(executedPipeline);
@@ -3534,14 +3512,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3534
3512
  if (!(fallbackPipeline.length && !containsForbiddenMongoOperators(fallbackPipeline))) return [3 /*break*/, 28];
3535
3513
  return [4 /*yield*/, runAggregateWithRepair(fallbackPipeline, 'name_match')];
3536
3514
  case 27:
3537
- fallbackAggregate = _r.sent();
3515
+ fallbackAggregate = _s.sent();
3538
3516
  fallbackDocs = fallbackAggregate.documents;
3539
3517
  if (fallbackDocs.length) {
3540
3518
  documents = fallbackDocs;
3541
3519
  executedPipeline = fallbackAggregate.pipeline;
3542
3520
  fallbackMeta.nameMatch.used = true;
3543
3521
  }
3544
- _r.label = 28;
3522
+ _s.label = 28;
3545
3523
  case 28:
3546
3524
  if (!!documents.length) return [3 /*break*/, 34];
3547
3525
  _e = probeDocs;
@@ -3555,14 +3533,14 @@ function executeAiAssistantMongoAggregate(payload, context) {
3555
3533
  includeClientScope: shouldScopeByClient
3556
3534
  })];
3557
3535
  case 29:
3558
- _e = (_r.sent());
3559
- _r.label = 30;
3536
+ _e = (_s.sent());
3537
+ _s.label = 30;
3560
3538
  case 30:
3561
3539
  probeDocs = _e;
3562
3540
  _loop_1 = function (i) {
3563
3541
  var stage, chemicalLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3564
- return __generator(this, function (_s) {
3565
- switch (_s.label) {
3542
+ return __generator(this, function (_t) {
3543
+ switch (_t.label) {
3566
3544
  case 0:
3567
3545
  stage = executedPipeline[i];
3568
3546
  if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
@@ -3578,7 +3556,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3578
3556
  probeDocs: probeDocs || undefined
3579
3557
  })];
3580
3558
  case 1:
3581
- chemicalLookup = _s.sent();
3559
+ chemicalLookup = _t.sent();
3582
3560
  if (!chemicalLookup) {
3583
3561
  return [2 /*return*/, "continue"];
3584
3562
  }
@@ -3587,7 +3565,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3587
3565
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 3];
3588
3566
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'chemical_lookup')];
3589
3567
  case 2:
3590
- fallbackAggregate = _s.sent();
3568
+ fallbackAggregate = _t.sent();
3591
3569
  fallbackDocs = fallbackAggregate.documents;
3592
3570
  if (fallbackDocs.length) {
3593
3571
  documents = fallbackDocs;
@@ -3595,21 +3573,21 @@ function executeAiAssistantMongoAggregate(payload, context) {
3595
3573
  fallbackMeta.chemicalLookup.used = true;
3596
3574
  return [2 /*return*/, "break"];
3597
3575
  }
3598
- _s.label = 3;
3576
+ _t.label = 3;
3599
3577
  case 3: return [2 /*return*/];
3600
3578
  }
3601
3579
  });
3602
3580
  };
3603
3581
  i = 0;
3604
- _r.label = 31;
3582
+ _s.label = 31;
3605
3583
  case 31:
3606
3584
  if (!(i < (executedPipeline || []).length)) return [3 /*break*/, 34];
3607
3585
  return [5 /*yield**/, _loop_1(i)];
3608
3586
  case 32:
3609
- state_1 = _r.sent();
3587
+ state_1 = _s.sent();
3610
3588
  if (state_1 === "break")
3611
3589
  return [3 /*break*/, 34];
3612
- _r.label = 33;
3590
+ _s.label = 33;
3613
3591
  case 33:
3614
3592
  i += 1;
3615
3593
  return [3 /*break*/, 31];
@@ -3635,8 +3613,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
3635
3613
  includeClientScope: shouldScopeByClient
3636
3614
  })];
3637
3615
  case 35:
3638
- _f = (_r.sent());
3639
- _r.label = 36;
3616
+ _f = (_s.sent());
3617
+ _s.label = 36;
3640
3618
  case 36:
3641
3619
  probeDocs = _f;
3642
3620
  if (!probeDocs.length) return [3 /*break*/, 38];
@@ -3655,27 +3633,27 @@ function executeAiAssistantMongoAggregate(payload, context) {
3655
3633
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 38];
3656
3634
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'query_field_aliases')];
3657
3635
  case 37:
3658
- fallbackAggregate = _r.sent();
3636
+ fallbackAggregate = _s.sent();
3659
3637
  fallbackDocs = fallbackAggregate.documents;
3660
3638
  if (fallbackDocs.length) {
3661
3639
  documents = fallbackDocs;
3662
3640
  executedPipeline = fallbackAggregate.pipeline;
3663
3641
  fallbackMeta.queryFieldAliases.used = true;
3664
3642
  }
3665
- _r.label = 38;
3643
+ _s.label = 38;
3666
3644
  case 38:
3667
3645
  if (!!documents.length) return [3 /*break*/, 42];
3668
3646
  _loop_2 = function (i) {
3669
- var stage, _t, idLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3670
- return __generator(this, function (_u) {
3671
- switch (_u.label) {
3647
+ var stage, _u, idLookup, rewrittenPipeline, fallbackAggregate, fallbackDocs;
3648
+ return __generator(this, function (_v) {
3649
+ switch (_v.label) {
3672
3650
  case 0:
3673
3651
  stage = executedPipeline[i];
3674
3652
  if (!stage || typeof stage !== 'object' || !stage.$match || typeof stage.$match !== 'object') {
3675
3653
  return [2 /*return*/, "continue"];
3676
3654
  }
3677
- _t = probeDocs;
3678
- if (_t) return [3 /*break*/, 2];
3655
+ _u = probeDocs;
3656
+ if (_u) return [3 /*break*/, 2];
3679
3657
  return [4 /*yield*/, fetchAssistantProbeDocs({
3680
3658
  db: db,
3681
3659
  collection: collection,
@@ -3685,10 +3663,10 @@ function executeAiAssistantMongoAggregate(payload, context) {
3685
3663
  includeClientScope: shouldScopeByClient
3686
3664
  })];
3687
3665
  case 1:
3688
- _t = (_u.sent());
3689
- _u.label = 2;
3666
+ _u = (_v.sent());
3667
+ _v.label = 2;
3690
3668
  case 2:
3691
- probeDocs = _t;
3669
+ probeDocs = _u;
3692
3670
  return [4 /*yield*/, applyIdLookupFallbackToQuery({
3693
3671
  query: stage.$match,
3694
3672
  db: db,
@@ -3699,7 +3677,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3699
3677
  probeDocs: probeDocs || undefined
3700
3678
  })];
3701
3679
  case 3:
3702
- idLookup = _u.sent();
3680
+ idLookup = _v.sent();
3703
3681
  if (!idLookup) {
3704
3682
  return [2 /*return*/, "continue"];
3705
3683
  }
@@ -3708,7 +3686,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
3708
3686
  if (!!containsForbiddenMongoOperators(rewrittenPipeline)) return [3 /*break*/, 5];
3709
3687
  return [4 /*yield*/, runAggregateWithRepair(rewrittenPipeline, 'id_lookup')];
3710
3688
  case 4:
3711
- fallbackAggregate = _u.sent();
3689
+ fallbackAggregate = _v.sent();
3712
3690
  fallbackDocs = fallbackAggregate.documents;
3713
3691
  if (fallbackDocs.length) {
3714
3692
  documents = fallbackDocs;
@@ -3716,37 +3694,122 @@ function executeAiAssistantMongoAggregate(payload, context) {
3716
3694
  fallbackMeta.idLookup.used = true;
3717
3695
  return [2 /*return*/, "break"];
3718
3696
  }
3719
- _u.label = 5;
3697
+ _v.label = 5;
3720
3698
  case 5: return [2 /*return*/];
3721
3699
  }
3722
3700
  });
3723
3701
  };
3724
3702
  i = 0;
3725
- _r.label = 39;
3703
+ _s.label = 39;
3726
3704
  case 39:
3727
3705
  if (!(i < (executedPipeline || []).length)) return [3 /*break*/, 42];
3728
3706
  return [5 /*yield**/, _loop_2(i)];
3729
3707
  case 40:
3730
- state_2 = _r.sent();
3708
+ state_2 = _s.sent();
3731
3709
  if (state_2 === "break")
3732
3710
  return [3 /*break*/, 42];
3733
- _r.label = 41;
3711
+ _s.label = 41;
3734
3712
  case 41:
3735
3713
  i += 1;
3736
3714
  return [3 /*break*/, 39];
3737
3715
  case 42:
3738
- if (!!documents.length) return [3 /*break*/, 45];
3739
- return [4 /*yield*/, resolveBaseCollectionFromReport(db, dbName, collection)];
3716
+ if (!!documents.length) return [3 /*break*/, 53];
3717
+ return [4 /*yield*/, resolveAssistantNestedAggregateFallbacks({
3718
+ db: db,
3719
+ dbName: dbName,
3720
+ currentCollection: collection,
3721
+ pipeline: executedPipeline || [],
3722
+ triedCollections: triedCollections
3723
+ })];
3740
3724
  case 43:
3741
- baseCollection = _r.sent();
3742
- if (!(baseCollection && baseCollection !== collection)) return [3 /*break*/, 45];
3725
+ nestedFallbacks = _s.sent();
3726
+ if (!nestedFallbacks.length) return [3 /*break*/, 53];
3727
+ fallbackMeta.relationshipRetry = {
3728
+ from: collection,
3729
+ root: retryRootCollection,
3730
+ candidates: nestedFallbacks.map(function (entry) { return ({
3731
+ collection: entry.collection,
3732
+ prefix: entry.prefix,
3733
+ rewrittenFields: entry.rewrittenFields
3734
+ }); }),
3735
+ attempted: true,
3736
+ used: false
3737
+ };
3738
+ _s.label = 44;
3739
+ case 44:
3740
+ _s.trys.push([44, 51, 52, 53]);
3741
+ nestedFallbacks_1 = __values(nestedFallbacks), nestedFallbacks_1_1 = nestedFallbacks_1.next();
3742
+ _s.label = 45;
3743
+ case 45:
3744
+ if (!!nestedFallbacks_1_1.done) return [3 /*break*/, 50];
3745
+ nestedFallback = nestedFallbacks_1_1.value;
3746
+ addAssistantCollectionToTriedSet(triedCollections, nestedFallback.collection);
3747
+ fallbackPayload = __assign(__assign({}, input), { collection: nestedFallback.collection, pipeline: nestedFallback.pipeline, permissionView: resolveDefaultAssistantPermissionView(nestedFallback.collection), __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
3748
+ rootCollection: retryRootCollection,
3749
+ disableCrossCollectionRetry: true
3750
+ }) });
3751
+ _s.label = 46;
3752
+ case 46:
3753
+ _s.trys.push([46, 48, , 49]);
3754
+ return [4 /*yield*/, executeAiAssistantMongoAggregate(fallbackPayload, context)];
3755
+ case 47:
3756
+ fallbackResult = _s.sent();
3757
+ if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
3758
+ if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
3759
+ existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
3760
+ ? fallbackResult.debug.fallbacks
3761
+ : {};
3762
+ fallbackResult.debug.fallbacks = __assign(__assign({}, existingFallbacks), { relationshipRetry: {
3763
+ from: collection,
3764
+ to: nestedFallback.collection,
3765
+ prefix: nestedFallback.prefix,
3766
+ rewrittenFields: nestedFallback.rewrittenFields,
3767
+ root: retryRootCollection,
3768
+ used: true
3769
+ } });
3770
+ }
3771
+ return [2 /*return*/, fallbackResult];
3772
+ }
3773
+ return [3 /*break*/, 49];
3774
+ case 48:
3775
+ error_6 = _s.sent();
3776
+ errorMessage = normalizeOptionalString(error_6 === null || error_6 === void 0 ? void 0 : error_6.message) || 'Unknown error';
3777
+ existingErrors = Array.isArray(fallbackMeta.relationshipRetry.errors)
3778
+ ? fallbackMeta.relationshipRetry.errors
3779
+ : [];
3780
+ fallbackMeta.relationshipRetry.errors = __spreadArray(__spreadArray([], __read(existingErrors), false), [{
3781
+ collection: nestedFallback.collection,
3782
+ prefix: nestedFallback.prefix,
3783
+ error: errorMessage
3784
+ }], false);
3785
+ return [3 /*break*/, 49];
3786
+ case 49:
3787
+ nestedFallbacks_1_1 = nestedFallbacks_1.next();
3788
+ return [3 /*break*/, 45];
3789
+ case 50: return [3 /*break*/, 53];
3790
+ case 51:
3791
+ e_2_1 = _s.sent();
3792
+ e_2 = { error: e_2_1 };
3793
+ return [3 /*break*/, 53];
3794
+ case 52:
3795
+ try {
3796
+ if (nestedFallbacks_1_1 && !nestedFallbacks_1_1.done && (_o = nestedFallbacks_1.return)) _o.call(nestedFallbacks_1);
3797
+ }
3798
+ finally { if (e_2) throw e_2.error; }
3799
+ return [7 /*endfinally*/];
3800
+ case 53:
3801
+ if (!!documents.length) return [3 /*break*/, 56];
3802
+ return [4 /*yield*/, resolveBaseCollectionFromReport(db, dbName, collection)];
3803
+ case 54:
3804
+ baseCollection = _s.sent();
3805
+ if (!(baseCollection && baseCollection !== collection)) return [3 /*break*/, 56];
3743
3806
  addAssistantCollectionToTriedSet(triedCollections, baseCollection);
3744
3807
  fallbackPayload = __assign(__assign({}, input), { collection: baseCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
3745
3808
  rootCollection: retryRootCollection
3746
3809
  }) });
3747
3810
  return [4 /*yield*/, executeAiAssistantMongoAggregate(fallbackPayload, context)];
3748
- case 44:
3749
- fallbackResult = _r.sent();
3811
+ case 55:
3812
+ fallbackResult = _s.sent();
3750
3813
  if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
3751
3814
  if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
3752
3815
  existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
@@ -3763,13 +3826,13 @@ function executeAiAssistantMongoAggregate(payload, context) {
3763
3826
  if (isSuperAdmin) {
3764
3827
  fallbackMeta.reportFallback = { from: collection, to: baseCollection, attempted: true, used: false };
3765
3828
  }
3766
- _r.label = 45;
3767
- case 45:
3768
- if (!(!documents.length && crossCollectionRetryEnabled)) return [3 /*break*/, 54];
3829
+ _s.label = 56;
3830
+ case 56:
3831
+ if (!(!documents.length && crossCollectionRetryEnabled)) return [3 /*break*/, 65];
3769
3832
  return [4 /*yield*/, resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections)];
3770
- case 46:
3771
- crossCollectionCandidates = _r.sent();
3772
- if (!crossCollectionCandidates.length) return [3 /*break*/, 54];
3833
+ case 57:
3834
+ crossCollectionCandidates = _s.sent();
3835
+ if (!crossCollectionCandidates.length) return [3 /*break*/, 65];
3773
3836
  fallbackMeta.collectionRetry = {
3774
3837
  from: collection,
3775
3838
  root: retryRootCollection,
@@ -3777,13 +3840,13 @@ function executeAiAssistantMongoAggregate(payload, context) {
3777
3840
  attempted: true,
3778
3841
  used: false
3779
3842
  };
3780
- _r.label = 47;
3781
- case 47:
3782
- _r.trys.push([47, 52, 53, 54]);
3843
+ _s.label = 58;
3844
+ case 58:
3845
+ _s.trys.push([58, 63, 64, 65]);
3783
3846
  crossCollectionCandidates_2 = __values(crossCollectionCandidates), crossCollectionCandidates_2_1 = crossCollectionCandidates_2.next();
3784
- _r.label = 48;
3785
- case 48:
3786
- if (!!crossCollectionCandidates_2_1.done) return [3 /*break*/, 51];
3847
+ _s.label = 59;
3848
+ case 59:
3849
+ if (!!crossCollectionCandidates_2_1.done) return [3 /*break*/, 62];
3787
3850
  candidateCollection = crossCollectionCandidates_2_1.value;
3788
3851
  addAssistantCollectionToTriedSet(triedCollections, candidateCollection);
3789
3852
  fallbackPayload = __assign(__assign({}, input), { collection: candidateCollection, __assistantRetryState: buildAssistantRetryState(retryState, triedCollections, {
@@ -3791,8 +3854,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
3791
3854
  disableCrossCollectionRetry: true
3792
3855
  }) });
3793
3856
  return [4 /*yield*/, executeAiAssistantMongoAggregate(fallbackPayload, context)];
3794
- case 49:
3795
- fallbackResult = _r.sent();
3857
+ case 60:
3858
+ fallbackResult = _s.sent();
3796
3859
  if (Array.isArray(fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.documents) && fallbackResult.documents.length) {
3797
3860
  if (isSuperAdmin && (fallbackResult === null || fallbackResult === void 0 ? void 0 : fallbackResult.debug) && typeof fallbackResult.debug === 'object') {
3798
3861
  existingFallbacks = fallbackResult.debug.fallbacks && typeof fallbackResult.debug.fallbacks === 'object'
@@ -3808,62 +3871,62 @@ function executeAiAssistantMongoAggregate(payload, context) {
3808
3871
  }
3809
3872
  return [2 /*return*/, fallbackResult];
3810
3873
  }
3811
- _r.label = 50;
3812
- case 50:
3874
+ _s.label = 61;
3875
+ case 61:
3813
3876
  crossCollectionCandidates_2_1 = crossCollectionCandidates_2.next();
3814
- return [3 /*break*/, 48];
3815
- case 51: return [3 /*break*/, 54];
3816
- case 52:
3817
- e_2_1 = _r.sent();
3818
- e_2 = { error: e_2_1 };
3819
- return [3 /*break*/, 54];
3820
- case 53:
3877
+ return [3 /*break*/, 59];
3878
+ case 62: return [3 /*break*/, 65];
3879
+ case 63:
3880
+ e_3_1 = _s.sent();
3881
+ e_3 = { error: e_3_1 };
3882
+ return [3 /*break*/, 65];
3883
+ case 64:
3821
3884
  try {
3822
- if (crossCollectionCandidates_2_1 && !crossCollectionCandidates_2_1.done && (_o = crossCollectionCandidates_2.return)) _o.call(crossCollectionCandidates_2);
3885
+ if (crossCollectionCandidates_2_1 && !crossCollectionCandidates_2_1.done && (_p = crossCollectionCandidates_2.return)) _p.call(crossCollectionCandidates_2);
3823
3886
  }
3824
- finally { if (e_2) throw e_2.error; }
3887
+ finally { if (e_3) throw e_3.error; }
3825
3888
  return [7 /*endfinally*/];
3826
- case 54:
3827
- if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 71];
3889
+ case 65:
3890
+ if (!(!documents.length && isSuperAdmin)) return [3 /*break*/, 82];
3828
3891
  matchStages = (executedPipeline || []).filter(function (stage) { return stage && typeof stage === 'object' && stage.$match && typeof stage.$match === 'object'; });
3829
3892
  diagnostics = {};
3830
- if (!matchStages.length) return [3 /*break*/, 71];
3893
+ if (!matchStages.length) return [3 /*break*/, 82];
3831
3894
  combinedMatch = matchStages.reduce(function (acc, stage) { return ({ $and: __spreadArray(__spreadArray([], __read((acc.$and || [])), false), [stage.$match], false) }); }, { $and: [] });
3832
3895
  nameFields = collectMatchFieldsByCondition(combinedMatch, function (field, condition) { return isRegexMatchCondition(condition)
3833
3896
  || (typeof condition === 'string' && shouldApplyAssistantNameRegex(field)); });
3834
3897
  dateFields = collectMatchFieldsByCondition(combinedMatch, function (_field, condition) { return isDateCondition(condition); });
3835
3898
  diagnostics.nameFields = nameFields.length ? nameFields : undefined;
3836
3899
  diagnostics.dateFields = dateFields.length ? dateFields : undefined;
3837
- _r.label = 55;
3838
- case 55:
3839
- _r.trys.push([55, 60, , 61]);
3840
- if (!nameFields.length) return [3 /*break*/, 57];
3900
+ _s.label = 66;
3901
+ case 66:
3902
+ _s.trys.push([66, 71, , 72]);
3903
+ if (!nameFields.length) return [3 /*break*/, 68];
3841
3904
  queryNoName = stripMatchFields(combinedMatch, nameFields);
3842
3905
  _g = diagnostics;
3843
3906
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoName, {
3844
3907
  readPreference: AI_ASSISTANT_READ_PREFERENCE
3845
3908
  })];
3846
- case 56:
3847
- _g.recentCount = _r.sent();
3848
- _r.label = 57;
3849
- case 57:
3850
- if (!dateFields.length) return [3 /*break*/, 59];
3909
+ case 67:
3910
+ _g.recentCount = _s.sent();
3911
+ _s.label = 68;
3912
+ case 68:
3913
+ if (!dateFields.length) return [3 /*break*/, 70];
3851
3914
  queryNoDate = stripMatchFields(combinedMatch, dateFields);
3852
3915
  _h = diagnostics;
3853
3916
  return [4 /*yield*/, db.collection(collection).countDocuments(queryNoDate, {
3854
3917
  readPreference: AI_ASSISTANT_READ_PREFERENCE
3855
3918
  })];
3856
- case 58:
3857
- _h.nameMatchCount = _r.sent();
3858
- _r.label = 59;
3859
- case 59: return [3 /*break*/, 61];
3860
- case 60:
3861
- _j = _r.sent();
3862
- return [3 /*break*/, 61];
3863
- case 61:
3864
- _r.trys.push([61, 64, , 65]);
3919
+ case 69:
3920
+ _h.nameMatchCount = _s.sent();
3921
+ _s.label = 70;
3922
+ case 70: return [3 /*break*/, 72];
3923
+ case 71:
3924
+ _j = _s.sent();
3925
+ return [3 /*break*/, 72];
3926
+ case 72:
3927
+ _s.trys.push([72, 75, , 76]);
3865
3928
  _k = probeDocs;
3866
- if (_k) return [3 /*break*/, 63];
3929
+ if (_k) return [3 /*break*/, 74];
3867
3930
  return [4 /*yield*/, fetchAssistantProbeDocs({
3868
3931
  db: db,
3869
3932
  collection: collection,
@@ -3872,52 +3935,52 @@ function executeAiAssistantMongoAggregate(payload, context) {
3872
3935
  isSuperAdmin: isSuperAdmin,
3873
3936
  includeClientScope: shouldScopeByClient
3874
3937
  })];
3875
- case 62:
3876
- _k = (_r.sent());
3877
- _r.label = 63;
3878
- case 63:
3938
+ case 73:
3939
+ _k = (_s.sent());
3940
+ _s.label = 74;
3941
+ case 74:
3879
3942
  probeDocs = _k;
3880
3943
  if (probeDocs.length && nameFields.length) {
3881
3944
  diagnostics.chemicalIdDetected = detectChemicalIdFromProbe(probeDocs, nameFields);
3882
3945
  }
3883
- return [3 /*break*/, 65];
3884
- case 64:
3885
- _l = _r.sent();
3886
- return [3 /*break*/, 65];
3887
- case 65:
3888
- _r.trys.push([65, 69, , 70]);
3946
+ return [3 /*break*/, 76];
3947
+ case 75:
3948
+ _l = _s.sent();
3949
+ return [3 /*break*/, 76];
3950
+ case 76:
3951
+ _s.trys.push([76, 80, , 81]);
3889
3952
  return [4 /*yield*/, listAssistantCollections(db, dbName)];
3890
- case 66:
3891
- allCollections = _r.sent();
3953
+ case 77:
3954
+ allCollections = _s.sent();
3892
3955
  base = stripVersionSuffix(collection.startsWith('report-') ? collection.slice('report-'.length) : collection);
3893
3956
  alt = collection.startsWith('report-') ? base : "report-".concat(base);
3894
- if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 68];
3957
+ if (!(alt && alt !== collection && allCollections.includes(alt))) return [3 /*break*/, 79];
3895
3958
  return [4 /*yield*/, db.collection(alt).countDocuments({}, { readPreference: AI_ASSISTANT_READ_PREFERENCE })];
3896
- case 67:
3897
- altCount = _r.sent();
3959
+ case 78:
3960
+ altCount = _s.sent();
3898
3961
  diagnostics.alternateCollection = alt;
3899
3962
  diagnostics.alternateCollectionCount = altCount;
3900
- _r.label = 68;
3901
- case 68: return [3 /*break*/, 70];
3902
- case 69:
3903
- _m = _r.sent();
3904
- return [3 /*break*/, 70];
3905
- case 70:
3963
+ _s.label = 79;
3964
+ case 79: return [3 /*break*/, 81];
3965
+ case 80:
3966
+ _m = _s.sent();
3967
+ return [3 /*break*/, 81];
3968
+ case 81:
3906
3969
  fallbackMeta.zeroDiagnostics = diagnostics;
3907
- _r.label = 71;
3908
- case 71: return [4 /*yield*/, verifyAssistantAggregateReliability({
3970
+ _s.label = 82;
3971
+ case 82: return [4 /*yield*/, verifyAssistantAggregateReliability({
3909
3972
  db: db,
3910
3973
  collection: collection,
3911
3974
  pipeline: executedPipeline,
3912
3975
  documents: documents,
3913
3976
  aggregateOptions: aggregateOptions
3914
3977
  })];
3915
- case 72:
3916
- verification = _r.sent();
3978
+ case 83:
3979
+ verification = _s.sent();
3917
3980
  sanitizedDocuments = isSuperAdmin
3918
3981
  ? documents
3919
3982
  : documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
3920
- includeIds = ((_q = input.options) === null || _q === void 0 ? void 0 : _q.includeIds) === true;
3983
+ includeIds = ((_r = input.options) === null || _r === void 0 ? void 0 : _r.includeIds) === true;
3921
3984
  displayDocs = sanitizedDocuments.map(function (doc) { return flattenForTable(doc, {
3922
3985
  includeGroupFromId: true,
3923
3986
  includeIds: true
@@ -3931,8 +3994,8 @@ function executeAiAssistantMongoAggregate(payload, context) {
3931
3994
  idCustomer: customerId,
3932
3995
  isSuperAdmin: isSuperAdmin
3933
3996
  })];
3934
- case 73:
3935
- idLookupDisplay = _r.sent();
3997
+ case 84:
3998
+ idLookupDisplay = _s.sent();
3936
3999
  if (idLookupDisplay === null || idLookupDisplay === void 0 ? void 0 : idLookupDisplay.docs) {
3937
4000
  displayDocs = idLookupDisplay.docs;
3938
4001
  }
@@ -4620,100 +4683,6 @@ function buildAssistantToolRequest(directive, payload) {
4620
4683
  }
4621
4684
  return request;
4622
4685
  }
4623
- function normalizeAssistantRevenueTimeGrain(value) {
4624
- var normalized = normalizeOptionalString(value).toLowerCase();
4625
- if (!normalized) {
4626
- return null;
4627
- }
4628
- if (normalized.startsWith('day')) {
4629
- return 'day';
4630
- }
4631
- if (normalized.startsWith('week')) {
4632
- return 'week';
4633
- }
4634
- if (normalized.startsWith('month')) {
4635
- return 'month';
4636
- }
4637
- if (normalized.startsWith('quarter')) {
4638
- return 'quarter';
4639
- }
4640
- if (normalized.startsWith('year')) {
4641
- return 'year';
4642
- }
4643
- return null;
4644
- }
4645
- function convertAssistantRevenueWindowAmount(amount, fromUnit, toUnit) {
4646
- if (fromUnit === toUnit) {
4647
- return amount;
4648
- }
4649
- var daysPerUnit = {
4650
- day: 1,
4651
- week: 7,
4652
- month: 30,
4653
- quarter: 91,
4654
- year: 365
4655
- };
4656
- var fromDays = amount * (daysPerUnit[fromUnit] || 1);
4657
- var converted = (0, common_1.round)(fromDays / (daysPerUnit[toUnit] || 1));
4658
- return Math.min(Math.max(converted, 1), 400);
4659
- }
4660
- function resolveAssistantRevenueByTimeRequest(text, scope) {
4661
- if (scope === void 0) { scope = 'overall'; }
4662
- var normalized = normalizeOptionalString(text).toLowerCase();
4663
- if (!normalized) {
4664
- return null;
4665
- }
4666
- if (!/\b(revenue|invoice)\b/.test(normalized)) {
4667
- return null;
4668
- }
4669
- var byCustomer = /\b(?:by|per)\s+(?:each\s+)?(?:customer|client|account)s?\b/.test(normalized)
4670
- || /\bfor\s+each\s+(?:customer|client|account)\b/.test(normalized);
4671
- if (scope === 'overall' && byCustomer) {
4672
- return null;
4673
- }
4674
- if (scope === 'by_customer' && !byCustomer) {
4675
- return null;
4676
- }
4677
- var grain = null;
4678
- if (/\b(?:by|per)\s+day\b|\bdaily\b/.test(normalized)) {
4679
- grain = 'day';
4680
- }
4681
- else if (/\b(?:by|per)\s+week\b|\bweekly\b/.test(normalized)) {
4682
- grain = 'week';
4683
- }
4684
- else if (/\b(?:by|per)\s+month\b|\bmonthly\b/.test(normalized)) {
4685
- grain = 'month';
4686
- }
4687
- else if (/\b(?:by|per)\s+quarter\b|\bquarterly\b/.test(normalized)) {
4688
- grain = 'quarter';
4689
- }
4690
- else if (/\b(?:by|per)\s+year\b|\byearly\b|\bannually\b/.test(normalized)) {
4691
- grain = 'year';
4692
- }
4693
- if (!grain) {
4694
- return null;
4695
- }
4696
- var defaults = {
4697
- day: 30,
4698
- week: 12,
4699
- month: 6,
4700
- quarter: 8,
4701
- year: 3
4702
- };
4703
- var amount = defaults[grain];
4704
- var explicitRangeMatch = normalized.match(/\b(?:last|past|previous|over\s+the\s+last)\s+(\d+)\s+(day|week|month|quarter|year)s?\b/);
4705
- if ((explicitRangeMatch === null || explicitRangeMatch === void 0 ? void 0 : explicitRangeMatch[1]) && (explicitRangeMatch === null || explicitRangeMatch === void 0 ? void 0 : explicitRangeMatch[2])) {
4706
- var parsedAmount = Number(explicitRangeMatch[1]);
4707
- var parsedUnit = normalizeAssistantRevenueTimeGrain(explicitRangeMatch[2]);
4708
- if (Number.isFinite(parsedAmount) && parsedAmount > 0 && parsedUnit) {
4709
- amount = convertAssistantRevenueWindowAmount((0, common_1.round)(parsedAmount), parsedUnit, grain);
4710
- }
4711
- }
4712
- return {
4713
- grain: grain,
4714
- amount: Math.min(Math.max((0, common_1.round)(amount), 1), 400)
4715
- };
4716
- }
4717
4686
  function buildAssistantTrimmedStringExpr(value) {
4718
4687
  return {
4719
4688
  $trim: {
@@ -4763,1032 +4732,580 @@ function buildAssistantInvoiceCustomerLabelExpr() {
4763
4732
  }
4764
4733
  };
4765
4734
  }
4766
- function resolveAssistantRevenueByTimePipelineLimit(request, scope) {
4767
- var amount = Math.min(Math.max((0, common_1.round)(request.amount), 1), 400);
4768
- if (scope !== 'by_customer') {
4769
- return Math.min(Math.max(amount * 2, 20), 200);
4770
- }
4771
- // Customer breakdowns need much higher pre-pivot row coverage so each customer appears.
4772
- var perBucketTargets = {
4773
- day: 120,
4774
- week: 220,
4775
- month: 350,
4776
- quarter: 450,
4777
- year: 600
4778
- };
4779
- var perBucketTarget = perBucketTargets[request.grain] || 300;
4780
- return Math.min(Math.max(amount * perBucketTarget, 400), 5000);
4781
- }
4782
- function buildAssistantInvoiceRevenueByTimePipeline(request, scope) {
4783
- var _a, _b, _c;
4784
- if (scope === void 0) { scope = 'overall'; }
4785
- var grain = request.grain;
4786
- var amount = Math.min(Math.max((0, common_1.round)(request.amount), 1), 400);
4787
- var byCustomer = scope === 'by_customer';
4788
- var limit = resolveAssistantRevenueByTimePipelineLimit(request, scope);
4789
- var effectiveDateExpr = { $ifNull: ['$date_paid', { $ifNull: ['$date_invoiced', '$createdAt'] }] };
4790
- var effectiveTotalExpr = { $ifNull: ['$paid_total', '$grand_total'] };
4791
- var customerExpr = buildAssistantInvoiceCustomerLabelExpr();
4792
- var startDateExpr = grain === 'quarter'
4793
- ? { $dateSubtract: { startDate: '$$NOW', unit: 'month', amount: amount * 3 } }
4794
- : { $dateSubtract: { startDate: '$$NOW', unit: grain, amount: amount } };
4795
- var baseStages = [
4796
- {
4797
- $addFields: {
4798
- effective_date: effectiveDateExpr,
4799
- effective_total: effectiveTotalExpr
4800
- }
4801
- },
4802
- {
4803
- $match: {
4804
- effective_date: {
4805
- $gte: startDateExpr,
4806
- $lt: '$$NOW'
4807
- }
4808
- }
4809
- }
4810
- ];
4811
- if (grain === 'quarter') {
4812
- return __spreadArray(__spreadArray([], __read(baseStages), false), [
4813
- {
4814
- $group: {
4815
- _id: __assign(__assign({}, (byCustomer ? { customer: customerExpr } : {})), { year: { $year: '$effective_date' }, quarter: { $ceil: { $divide: [{ $month: '$effective_date' }, 3] } } }),
4816
- total_revenue: { $sum: { $ifNull: ['$effective_total', 0] } }
4817
- }
4818
- },
4819
- {
4820
- $project: __assign(__assign({ _id: 0 }, (byCustomer ? { customer: '$_id.customer' } : {})), { quarter: { $concat: [{ $toString: '$_id.year' }, '-Q', { $toString: '$_id.quarter' }] }, total_revenue: 1 })
4821
- },
4822
- { $sort: byCustomer ? { customer: 1, quarter: 1 } : { quarter: 1 } },
4823
- { $limit: limit }
4824
- ], false);
4825
- }
4826
- if (grain === 'year') {
4827
- return __spreadArray(__spreadArray([], __read(baseStages), false), [
4828
- {
4829
- $group: {
4830
- _id: byCustomer
4831
- ? { customer: customerExpr, year: { $year: '$effective_date' } }
4832
- : { year: { $year: '$effective_date' } },
4833
- total_revenue: { $sum: { $ifNull: ['$effective_total', 0] } }
4834
- }
4835
- },
4836
- {
4837
- $project: __assign(__assign({ _id: 0 }, (byCustomer ? { customer: '$_id.customer' } : {})), { year: '$_id.year', total_revenue: 1 })
4838
- },
4839
- { $sort: byCustomer ? { customer: 1, year: 1 } : { year: 1 } },
4840
- { $limit: limit }
4841
- ], false);
4842
- }
4843
- var bucketField = grain;
4844
- var dateFormat = grain === 'day'
4845
- ? '%Y-%m-%d'
4846
- : grain === 'week'
4847
- ? '%Y-%m-%d'
4848
- : '%Y-%m';
4849
- var dateTruncExpr = grain === 'week'
4850
- ? { $dateTrunc: { date: '$effective_date', unit: 'week', startOfWeek: 'monday' } }
4851
- : { $dateTrunc: { date: '$effective_date', unit: grain } };
4852
- return __spreadArray(__spreadArray([], __read(baseStages), false), [
4853
- {
4854
- $group: {
4855
- _id: byCustomer
4856
- ? { customer: customerExpr, bucket: dateTruncExpr }
4857
- : dateTruncExpr,
4858
- total_revenue: { $sum: { $ifNull: ['$effective_total', 0] } }
4859
- }
4860
- },
4861
- {
4862
- $project: __assign(__assign({ _id: 0 }, (byCustomer ? { customer: '$_id.customer' } : {})), (_a = {}, _a[bucketField] = {
4863
- $dateToString: {
4864
- format: dateFormat,
4865
- date: byCustomer ? '$_id.bucket' : '$_id'
4866
- }
4867
- }, _a.total_revenue = 1, _a))
4868
- },
4869
- { $sort: byCustomer ? (_b = { customer: 1 }, _b[bucketField] = 1, _b) : (_c = {}, _c[bucketField] = 1, _c) },
4870
- { $limit: limit }
4871
- ], false);
4872
- }
4873
- function isAssistantRevenueByTimeHeuristicDirective(directive) {
4874
- var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4875
- return rawLine.includes('heuristic_agg(invoice-revenue-time-');
4876
- }
4877
- function isAssistantBlendRedUltraLiftHeuristicDirective(directive) {
4878
- var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4879
- return rawLine.includes('heuristic_agg(blend-red-ultra-lift)');
4880
- }
4881
- function isAssistantActiveClientsHeuristicDirective(directive) {
4882
- var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4883
- return rawLine.includes('heuristic_read(active-clients-count)');
4884
- }
4885
- function isAssistantInvoiceTopCustomersHeuristicDirective(directive) {
4886
- var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4887
- return rawLine.includes('heuristic_agg(invoice-top-customers)');
4888
- }
4889
- function isAssistantOperationalHeuristicDirective(directive) {
4890
- var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
4891
- return rawLine.includes('heuristic_agg(work-order-status)')
4892
- || rawLine.includes('heuristic_agg(work-order-completed-per-day)')
4893
- || rawLine.includes('heuristic_agg(work-order-top-customers)')
4894
- || rawLine.includes('heuristic_agg(work-order-jobs-top-volume)')
4895
- || rawLine.includes('heuristic_agg(blend-last10-summary)')
4896
- || rawLine.includes('heuristic_agg(blend-throughput-by-day)')
4897
- || rawLine.includes('heuristic_agg(deliveries-per-driver-last-month)')
4898
- || rawLine.includes('heuristic_agg(deliveries-per-driver-last-30d-top10)')
4899
- || rawLine.includes('heuristic_agg(last-deliveries)')
4900
- || rawLine.includes('heuristic_agg(invoice-missing-invoiced-date-created-this-month)')
4901
- || rawLine.includes('heuristic_agg(support-ticket-billable-hours-user-month-last-6m)');
4902
- }
4903
- function isAssistantDeterministicHeuristicDirective(directive) {
4904
- return isAssistantRevenueByTimeHeuristicDirective(directive)
4905
- || isAssistantActiveClientsHeuristicDirective(directive)
4906
- || isAssistantInvoiceTopCustomersHeuristicDirective(directive)
4907
- || isAssistantOperationalHeuristicDirective(directive)
4908
- || isAssistantBlendRedUltraLiftHeuristicDirective(directive);
4909
- }
4910
- function buildAssistantHeuristicDirective(message, collectionHints) {
4911
- var text = normalizeOptionalString(message).toLowerCase();
4912
- if (!text) {
4735
+ var AI_ASSISTANT_NUMBER_WORDS = {
4736
+ one: 1,
4737
+ two: 2,
4738
+ three: 3,
4739
+ four: 4,
4740
+ five: 5,
4741
+ six: 6,
4742
+ seven: 7,
4743
+ eight: 8,
4744
+ nine: 9,
4745
+ ten: 10,
4746
+ eleven: 11,
4747
+ twelve: 12
4748
+ };
4749
+ function parseAssistantNumericToken(value) {
4750
+ var normalized = normalizeOptionalString(value).toLowerCase();
4751
+ if (!normalized) {
4913
4752
  return null;
4914
4753
  }
4915
- if (/\bhow\s+many\b.*\bactive\b.*\b(clients?|customers?)\b/.test(text)
4916
- || /\bactive\b.*\b(clients?|customers?)\b.*\bhow\s+many\b/.test(text)) {
4917
- var mergedHints = mergeAssistantHintValues(collectionHints, resolveAssistantDefaultCollectionHints(message));
4918
- var customerCollection = mergedHints.includes('customers')
4919
- ? 'customers'
4920
- : (mergedHints.includes('clients') ? 'clients' : 'customers');
4921
- return {
4922
- type: 'read',
4923
- payload: {
4924
- collection: customerCollection,
4925
- permissionView: '/client/list',
4926
- query: {
4927
- $or: [
4928
- { status: { $regex: '^active$', $options: 'i' } },
4929
- { state: { $regex: '^active$', $options: 'i' } },
4930
- { active: true },
4931
- { is_active: true },
4932
- { enabled: true },
4933
- { is_enabled: true }
4934
- ]
4935
- },
4936
- options: {
4937
- projection: {
4938
- status: 1,
4939
- state: 1,
4940
- active: 1,
4941
- is_active: 1,
4942
- enabled: 1,
4943
- is_enabled: 1
4944
- },
4945
- limit: 0,
4946
- includeTotal: true
4947
- }
4948
- },
4949
- cleaned: '',
4950
- rawLine: 'HEURISTIC_READ(active-clients-count)'
4951
- };
4754
+ if (/^\d+$/.test(normalized)) {
4755
+ var parsed = Number(normalized);
4756
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
4952
4757
  }
4953
- var revenueByCustomerTime = resolveAssistantRevenueByTimeRequest(text, 'by_customer');
4954
- if (revenueByCustomerTime) {
4955
- var customerLimit = resolveAssistantRevenueByTimePipelineLimit(revenueByCustomerTime, 'by_customer');
4956
- return {
4957
- type: 'aggregate',
4958
- payload: {
4959
- collection: 'invoices',
4960
- permissionView: '/invoice/list',
4961
- pipeline: buildAssistantInvoiceRevenueByTimePipeline(revenueByCustomerTime, 'by_customer'),
4962
- options: {
4963
- allowDiskUse: true,
4964
- export: true,
4965
- limit: customerLimit
4966
- }
4967
- },
4968
- cleaned: '',
4969
- rawLine: "HEURISTIC_AGG(invoice-revenue-time-customer-".concat(revenueByCustomerTime.grain, ")")
4970
- };
4758
+ var wordValue = AI_ASSISTANT_NUMBER_WORDS[normalized];
4759
+ return Number.isFinite(wordValue) && wordValue > 0 ? wordValue : null;
4760
+ }
4761
+ function resolveAssistantGenericTimeUnit(value) {
4762
+ var normalized = normalizeOptionalString(value).toLowerCase();
4763
+ if (!normalized) {
4764
+ return null;
4971
4765
  }
4972
- var revenueByTime = resolveAssistantRevenueByTimeRequest(text, 'overall');
4973
- if (revenueByTime) {
4974
- return {
4975
- type: 'aggregate',
4976
- payload: {
4977
- collection: 'invoices',
4978
- permissionView: '/invoice/list',
4979
- pipeline: buildAssistantInvoiceRevenueByTimePipeline(revenueByTime, 'overall')
4980
- },
4981
- cleaned: '',
4982
- rawLine: "HEURISTIC_AGG(invoice-revenue-time-".concat(revenueByTime.grain, ")")
4983
- };
4766
+ if (normalized.startsWith('day')) {
4767
+ return 'day';
4984
4768
  }
4985
- if (/\b(last|latest|recent)\s+20\b/.test(text)
4986
- && /\bwork[\s-]*orders?\b/.test(text)
4987
- && /\b(group(ed)?\s+by|by|per)\s+status\b/.test(text)) {
4988
- return {
4989
- type: 'aggregate',
4990
- payload: {
4991
- collection: 'work-order-dynamics',
4992
- permissionView: '/work-order-dynamic/list',
4993
- pipeline: [
4994
- {
4995
- $addFields: {
4996
- date_created_at: { $ifNull: ['$date_created', '$createdAt'] }
4997
- }
4998
- },
4999
- {
5000
- $match: {
5001
- date_created_at: {
5002
- $gte: { $dateTrunc: { date: '$$NOW', unit: 'week', startOfWeek: 'monday' } },
5003
- $lt: '$$NOW'
5004
- }
5005
- }
5006
- },
5007
- { $sort: { date_created_at: -1, _id: -1 } },
5008
- { $limit: 20 },
5009
- {
5010
- $group: {
5011
- _id: { $ifNull: ['$status', 'Unknown'] },
5012
- work_order_count: { $sum: 1 }
5013
- }
5014
- },
5015
- {
5016
- $project: {
5017
- _id: 0,
5018
- status: '$_id',
5019
- work_order_count: 1
5020
- }
5021
- },
5022
- { $sort: { work_order_count: -1, status: 1 } }
5023
- ]
5024
- },
5025
- cleaned: '',
5026
- rawLine: 'HEURISTIC_AGG(work-order-status)'
5027
- };
4769
+ if (normalized.startsWith('week')) {
4770
+ return 'week';
5028
4771
  }
5029
- if (/\bwork[\s-]*orders?\b/.test(text)
5030
- && /\b(completed|complete)\b/.test(text)
5031
- && /\b(per|by)\s+day\b/.test(text)
5032
- && /\b(last|past)\s+30\s+days?\b/.test(text)) {
5033
- return {
5034
- type: 'aggregate',
5035
- payload: {
5036
- collection: 'work-order-dynamics',
5037
- permissionView: '/work-order-dynamic/list',
5038
- pipeline: [
5039
- {
5040
- $match: {
5041
- date_completed: {
5042
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 30 } },
5043
- $lt: '$$NOW'
5044
- }
5045
- }
5046
- },
5047
- {
5048
- $group: {
5049
- _id: {
5050
- $dateToString: {
5051
- format: '%Y-%m-%d',
5052
- date: '$date_completed',
5053
- timezone: 'UTC'
5054
- }
5055
- },
5056
- completed_work_orders: { $sum: 1 }
5057
- }
5058
- },
5059
- { $sort: { _id: 1 } },
5060
- {
5061
- $project: {
5062
- _id: 0,
5063
- day_utc: '$_id',
5064
- completed_work_orders: 1
5065
- }
5066
- }
5067
- ]
5068
- },
5069
- cleaned: '',
5070
- rawLine: 'HEURISTIC_AGG(work-order-completed-per-day)'
5071
- };
4772
+ if (normalized.startsWith('month')) {
4773
+ return 'month';
5072
4774
  }
5073
- if (/\btop\s+10\b/.test(text)
5074
- && /\bcustomers?\b/.test(text)
5075
- && /\bwork[\s-]*orders?\b/.test(text)
5076
- && /\b(last|past)\s+6\s+months?\b/.test(text)) {
5077
- return {
5078
- type: 'aggregate',
5079
- payload: {
5080
- collection: 'work-order-dynamics',
5081
- permissionView: '/work-order-dynamic/list',
5082
- pipeline: [
5083
- {
5084
- $match: {
5085
- date_created: {
5086
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'month', amount: 6 } },
5087
- $lt: '$$NOW'
5088
- }
5089
- }
5090
- },
5091
- {
5092
- $group: {
5093
- _id: { $ifNull: ['$customer', 'Unknown'] },
5094
- work_order_count: { $sum: 1 }
5095
- }
5096
- },
5097
- { $sort: { work_order_count: -1, _id: 1 } },
5098
- { $limit: 10 },
5099
- {
5100
- $project: {
5101
- _id: 0,
5102
- customer: '$_id',
5103
- work_order_count: 1
5104
- }
5105
- }
5106
- ]
5107
- },
5108
- cleaned: '',
5109
- rawLine: 'HEURISTIC_AGG(work-order-top-customers)'
5110
- };
4775
+ if (normalized.startsWith('year')) {
4776
+ return 'year';
5111
4777
  }
5112
- if (/\bblend(?:ing)?\b/.test(text)
5113
- && /\b(last\s+10)\b/.test(text)
5114
- && /\b(summarize|summary)\b/.test(text)
5115
- && /\btickets?\b/.test(text)) {
5116
- return {
5117
- type: 'aggregate',
5118
- payload: {
5119
- collection: 'chemical-blends',
5120
- permissionView: '/report-builder/list',
5121
- pipeline: [
5122
- { $sort: { date: -1, createdAt: -1, _id: -1 } },
5123
- { $limit: 10 },
5124
- {
5125
- $project: {
5126
- _id: 0,
5127
- product: buildAssistantTrimmedStringExpr({ $ifNull: ['$blend_name', '$chemical'] }),
5128
- total_volume: { $ifNull: ['$chemical_recipe_quantity', 0] },
5129
- volume_unit: buildAssistantTrimmedStringExpr({
5130
- $cond: [{ $eq: ['$blend_in_pounds', true] }, 'lb', 'gal']
5131
- }),
5132
- created_date: { $ifNull: ['$date', '$createdAt'] },
5133
- batch_number: buildAssistantTrimmedStringExpr('$batch_number')
5134
- }
5135
- }
5136
- ]
5137
- },
5138
- cleaned: '',
5139
- rawLine: 'HEURISTIC_AGG(blend-last10-summary)'
5140
- };
4778
+ return null;
4779
+ }
4780
+ function resolveAssistantGenericWindow(message) {
4781
+ var normalized = normalizeOptionalString(message).toLowerCase();
4782
+ if (!normalized) {
4783
+ return null;
5141
4784
  }
5142
- if (/\bblend(?:ing)?\b/.test(text)
5143
- && /\bthroughput\b/.test(text)
5144
- && /\b(per|by)\s+day\b/.test(text)
5145
- && /\b(last|past)\s+2\s+weeks?\b/.test(text)) {
5146
- return {
5147
- type: 'aggregate',
5148
- payload: {
5149
- collection: 'chemical-blends',
5150
- permissionView: '/report-builder/list',
5151
- pipeline: [
5152
- {
5153
- $match: {
5154
- date: {
5155
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 14 } },
5156
- $lt: '$$NOW'
5157
- }
5158
- }
5159
- },
5160
- {
5161
- $group: {
5162
- _id: {
5163
- $dateToString: {
5164
- format: '%Y-%m-%d',
5165
- date: '$date',
5166
- timezone: 'UTC'
5167
- }
5168
- },
5169
- blend_count: { $sum: 1 },
5170
- total_volume: { $sum: { $ifNull: ['$chemical_recipe_quantity', 0] } }
5171
- }
5172
- },
5173
- { $sort: { _id: 1 } },
5174
- {
5175
- $project: {
5176
- _id: 0,
5177
- day_utc: '$_id',
5178
- blend_count: 1,
5179
- total_volume: 1
5180
- }
5181
- }
5182
- ]
5183
- },
5184
- cleaned: '',
5185
- rawLine: 'HEURISTIC_AGG(blend-throughput-by-day)'
5186
- };
4785
+ var explicit = normalized.match(/\b(?:last|past|previous|over\s+the\s+last)\s+(\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(day|week|month|year)s?\b/);
4786
+ if ((explicit === null || explicit === void 0 ? void 0 : explicit[1]) && (explicit === null || explicit === void 0 ? void 0 : explicit[2])) {
4787
+ var amount = parseAssistantNumericToken(explicit[1]);
4788
+ var unit = resolveAssistantGenericTimeUnit(explicit[2]);
4789
+ if (amount && unit) {
4790
+ return {
4791
+ unit: unit,
4792
+ amount: amount,
4793
+ fullCalendarPeriods: unit === 'month' || unit === 'year'
4794
+ };
4795
+ }
5187
4796
  }
5188
- if (/\bdeliver(?:y|ies)\b/.test(text)
5189
- && /\bdrivers?\b/.test(text)
5190
- && /\blast\s+month\b/.test(text)) {
5191
- var thisMonthStart = { $dateTrunc: { date: '$$NOW', unit: 'month' } };
5192
- return {
5193
- type: 'aggregate',
5194
- payload: {
5195
- collection: 'work-order-dynamics',
5196
- permissionView: '/work-order-dynamic/list',
5197
- pipeline: [
5198
- {
5199
- $match: {
5200
- date_completed: {
5201
- $gte: { $dateSubtract: { startDate: thisMonthStart, unit: 'month', amount: 1 } },
5202
- $lt: thisMonthStart
5203
- },
5204
- status: { $in: ['Completed', 'Closed'] }
5205
- }
5206
- },
5207
- { $unwind: { path: '$drivers', preserveNullAndEmptyArrays: true } },
5208
- {
5209
- $group: {
5210
- _id: { $ifNull: ['$drivers.user', 'Unassigned'] },
5211
- delivery_count: { $sum: 1 }
5212
- }
5213
- },
5214
- { $sort: { delivery_count: -1, _id: 1 } },
5215
- {
5216
- $project: {
5217
- _id: 0,
5218
- driver: '$_id',
5219
- delivery_count: 1
5220
- }
5221
- }
5222
- ]
5223
- },
5224
- cleaned: '',
5225
- rawLine: 'HEURISTIC_AGG(deliveries-per-driver-last-month)'
5226
- };
4797
+ if (/\b(?:last|past|previous|over\s+the\s+last)\s+year\b/.test(normalized)) {
4798
+ return { unit: 'year', amount: 1, fullCalendarPeriods: true };
5227
4799
  }
5228
- if (/\bdeliver(?:y|ies)\b/.test(text)
5229
- && /\bdrivers?\b/.test(text)
5230
- && /\b(last|past)\s+30\s+days?\b/.test(text)
5231
- && /\btop\s+10\b/.test(text)) {
5232
- return {
5233
- type: 'aggregate',
5234
- payload: {
5235
- collection: 'production-deliveries',
5236
- permissionView: '/dashboard/driver',
5237
- pipeline: [
5238
- {
5239
- $addFields: {
5240
- effective_date: { $ifNull: ['$date', { $ifNull: ['$date_created', '$createdAt'] }] },
5241
- driver_label: buildAssistantTrimmedStringExpr({
5242
- $ifNull: [
5243
- '$driver',
5244
- {
5245
- $ifNull: [
5246
- '$driver_name',
5247
- {
5248
- $ifNull: [
5249
- '$driver.fullname',
5250
- {
5251
- $ifNull: [
5252
- '$driver.name',
5253
- {
5254
- $ifNull: [
5255
- { $toString: '$id_driver' },
5256
- 'Unknown Driver'
5257
- ]
5258
- }
5259
- ]
5260
- }
5261
- ]
5262
- }
5263
- ]
5264
- }
5265
- ]
5266
- })
5267
- }
5268
- },
5269
- {
5270
- $match: {
5271
- effective_date: {
5272
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 30 } },
5273
- $lt: '$$NOW'
5274
- }
5275
- }
5276
- },
5277
- {
5278
- $group: {
5279
- _id: '$driver_label',
5280
- delivery_count: { $sum: 1 }
5281
- }
5282
- },
5283
- { $sort: { delivery_count: -1, _id: 1 } },
5284
- { $limit: 10 },
5285
- {
5286
- $project: {
5287
- _id: 0,
5288
- driver: '$_id',
5289
- delivery_count: 1
5290
- }
5291
- }
5292
- ]
5293
- },
5294
- cleaned: '',
5295
- rawLine: 'HEURISTIC_AGG(deliveries-per-driver-last-30d-top10)'
5296
- };
4800
+ if (/\b(?:last|past|previous)\s+month\b/.test(normalized)) {
4801
+ return { unit: 'month', amount: 1, fullCalendarPeriods: true };
5297
4802
  }
5298
- if (/(which\s+blends?|blends?\s+used).*(red\s+ultra\s+lift|chemical\s+red\s+ultra\s+lift)/.test(text)
5299
- && /(last|past)\s+30\s+days/.test(text)) {
5300
- return {
5301
- type: 'aggregate',
5302
- payload: {
5303
- collection: 'chemical-blends',
5304
- permissionView: '/chemical-blends/list',
5305
- pipeline: [
5306
- {
5307
- $addFields: {
5308
- effective_date: { $ifNull: ['$date', '$date_created', '$createdAt'] },
5309
- blend_chemical_rows: {
5310
- $cond: [
5311
- { $isArray: '$blend_chemicals' },
5312
- '$blend_chemicals',
5313
- {
5314
- $cond: [
5315
- { $isArray: '$chemicals' },
5316
- '$chemicals',
5317
- []
5318
- ]
5319
- }
5320
- ]
5321
- }
5322
- }
5323
- },
5324
- {
5325
- $match: {
5326
- effective_date: {
5327
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 30 } },
5328
- $lt: '$$NOW'
5329
- }
5330
- }
5331
- },
5332
- { $unwind: { path: '$blend_chemical_rows', preserveNullAndEmptyArrays: false } },
5333
- {
5334
- $match: {
5335
- $or: [
5336
- { 'blend_chemical_rows.chemical': /red\s+ultra\s+lift/i },
5337
- { 'blend_chemical_rows.name': /red\s+ultra\s+lift/i },
5338
- { chemical: /red\s+ultra\s+lift/i },
5339
- { blend_name: /red\s+ultra\s+lift/i }
5340
- ]
5341
- }
5342
- },
5343
- {
5344
- $project: {
5345
- _id: 0,
5346
- blend_name: { $ifNull: ['$blend_name', '$name'] },
5347
- lot_batch: {
5348
- $ifNull: [
5349
- '$batch_number',
5350
- {
5351
- $ifNull: [
5352
- '$blend_chemical_rows.lot_number',
5353
- {
5354
- $ifNull: [
5355
- '$blend_chemical_rows.batch',
5356
- {
5357
- $ifNull: ['$blend_chemical_rows.lot', '$blend_chemical_rows.batch_number']
5358
- }
5359
- ]
5360
- }
5361
- ]
5362
- }
5363
- ]
5364
- },
5365
- volume: {
5366
- $ifNull: [
5367
- '$blend_chemical_rows.quantity_recipe_gallons',
5368
- {
5369
- $ifNull: [
5370
- '$blend_chemical_rows.quantity_recipe',
5371
- {
5372
- $ifNull: [
5373
- '$blend_chemical_rows.chemical_recipe_quantity',
5374
- {
5375
- $ifNull: ['$blend_chemical_rows.quantity', '$blend_chemical_rows.volume']
5376
- }
5377
- ]
5378
- }
5379
- ]
5380
- }
5381
- ]
5382
- },
5383
- unit: {
5384
- $ifNull: [
5385
- '$blend_chemical_rows.unit',
5386
- { $cond: [{ $eq: ['$blend_in_pounds', true] }, 'lb', 'gal'] }
5387
- ]
5388
- },
5389
- blend_date: '$effective_date'
5390
- }
5391
- },
5392
- { $sort: { blend_date: -1 } },
5393
- { $limit: 50 }
5394
- ]
5395
- },
5396
- cleaned: '',
5397
- rawLine: 'HEURISTIC_AGG(blend-red-ultra-lift)'
5398
- };
4803
+ if (/\b(?:last|past|previous)\s+week\b/.test(normalized)) {
4804
+ return { unit: 'week', amount: 1, fullCalendarPeriods: true };
5399
4805
  }
5400
- if (/(top\s+10).*(customers?).*(invoice)/.test(text)) {
5401
- return {
5402
- type: 'aggregate',
5403
- payload: {
5404
- collection: 'invoices',
5405
- permissionView: '/invoice/list',
5406
- pipeline: [
5407
- {
5408
- $addFields: {
5409
- effective_date: { $ifNull: ['$date_paid', { $ifNull: ['$date_invoiced', '$createdAt'] }] },
5410
- effective_total: { $ifNull: ['$paid_total', '$grand_total'] }
5411
- }
5412
- },
5413
- {
5414
- $match: {
5415
- effective_date: {
5416
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'month', amount: 6 } },
5417
- $lt: '$$NOW'
5418
- }
5419
- }
5420
- },
5421
- {
5422
- $group: {
5423
- _id: buildAssistantInvoiceCustomerLabelExpr(),
5424
- invoice_total: { $sum: { $ifNull: ['$effective_total', 0] } },
5425
- invoice_count: { $sum: 1 }
5426
- }
5427
- },
5428
- {
5429
- $project: {
5430
- _id: 0,
5431
- customer: '$_id',
5432
- invoice_total: 1,
5433
- invoice_count: 1
5434
- }
5435
- },
5436
- { $sort: { invoice_total: -1, invoice_count: -1 } },
5437
- { $limit: 10 }
5438
- ]
5439
- },
5440
- cleaned: '',
5441
- rawLine: 'HEURISTIC_AGG(invoice-top-customers)'
5442
- };
4806
+ if (/\b(?:last|past|previous)\s+30\s+days?\b/.test(normalized)) {
4807
+ return { unit: 'day', amount: 30, fullCalendarPeriods: false };
5443
4808
  }
5444
- if (/\binvoices?\b/.test(text)
5445
- && /(\bmissing\b|\bwithout\b|\bno\b)/.test(text)
5446
- && /(\binvoic(?:ed|e)\s+date\b|\bdate[\s_-]*invoic(?:ed|e)\b)/.test(text)
5447
- && /\bthis\s+month\b/.test(text)) {
5448
- var thisMonthStart = { $dateTrunc: { date: '$$NOW', unit: 'month' } };
5449
- return {
5450
- type: 'aggregate',
5451
- payload: {
5452
- collection: 'invoices',
5453
- permissionView: '/invoice/list',
5454
- pipeline: [
5455
- {
5456
- $addFields: {
5457
- created_date: { $ifNull: ['$createdAt', { $ifNull: ['$date_created', '$date'] }] },
5458
- invoiced_date: { $ifNull: ['$date_invoiced', '$date_invoice'] }
5459
- }
5460
- },
5461
- {
5462
- $match: {
5463
- created_date: {
5464
- $gte: thisMonthStart,
5465
- $lt: '$$NOW'
5466
- }
5467
- }
5468
- },
5469
- {
5470
- $match: {
5471
- $expr: {
5472
- $or: [
5473
- { $eq: [{ $type: '$invoiced_date' }, 'missing'] },
5474
- { $eq: ['$invoiced_date', null] },
5475
- {
5476
- $and: [
5477
- { $eq: [{ $type: '$invoiced_date' }, 'string'] },
5478
- { $eq: [{ $trim: { input: '$invoiced_date' } }, ''] }
5479
- ]
5480
- }
5481
- ]
5482
- }
5483
- }
5484
- },
5485
- {
5486
- $project: {
5487
- _id: 0,
5488
- invoice_number: { $ifNull: ['$invoice_number_string', '$invoice_number'] },
5489
- customer: buildAssistantInvoiceCustomerLabelExpr(),
5490
- created_date: 1,
5491
- due_date: '$date_due',
5492
- sub_total: { $ifNull: ['$sub_total', '$subtotal'] },
5493
- total: { $ifNull: ['$grand_total', '$paid_total'] }
5494
- }
5495
- },
5496
- { $sort: { created_date: -1, invoice_number: 1 } },
5497
- { $limit: 200 }
5498
- ],
5499
- options: {
5500
- allowDiskUse: true,
5501
- export: true,
5502
- limit: 200
5503
- }
5504
- },
5505
- cleaned: '',
5506
- rawLine: 'HEURISTIC_AGG(invoice-missing-invoiced-date-created-this-month)'
5507
- };
4809
+ return null;
4810
+ }
4811
+ function resolveAssistantGenericTimeGrain(message) {
4812
+ var normalized = normalizeOptionalString(message).toLowerCase();
4813
+ if (!normalized) {
4814
+ return null;
5508
4815
  }
5509
- if (/\bsupport[\s-]*tickets?\b/.test(text)
5510
- && /\b(hours?|billable)\b/.test(text)
5511
- && /\b(last|past)\s+6\s+months?\b/.test(text)
5512
- && /(\b(per|by|each)\s+user\b|\buser\b)/.test(text)
5513
- && /(\b(per|by|each)\s+month\b|\bmonth\b)/.test(text)) {
5514
- return {
5515
- type: 'aggregate',
5516
- payload: {
5517
- collection: 'support-tickets',
5518
- permissionView: '/support-ticket/list',
5519
- pipeline: [
5520
- {
5521
- $addFields: {
5522
- effective_date: { $ifNull: ['$date', { $ifNull: ['$date_created', { $ifNull: ['$createdAt', '$updatedAt'] }] }] },
5523
- billable_hours_value: {
5524
- $convert: {
5525
- input: {
5526
- $ifNull: [
5527
- '$hours_billed',
5528
- {
5529
- $ifNull: [
5530
- '$billable_hours',
5531
- {
5532
- $ifNull: [
5533
- '$hours',
5534
- {
5535
- $ifNull: [
5536
- '$total_hours',
5537
- { $ifNull: ['$time.hours', { $ifNull: ['$billing.hours', 0] }] }
5538
- ]
5539
- }
5540
- ]
5541
- }
5542
- ]
5543
- }
5544
- ]
5545
- },
5546
- to: 'double',
5547
- onError: 0,
5548
- onNull: 0
5549
- }
5550
- },
5551
- user_label: buildAssistantTrimmedStringExpr({
5552
- $ifNull: [
5553
- '$user.fullname',
5554
- {
5555
- $ifNull: [
5556
- '$user.name',
5557
- {
5558
- $ifNull: [
5559
- '$employee.fullname',
5560
- {
5561
- $ifNull: [
5562
- '$employee.name',
5563
- {
5564
- $ifNull: [
5565
- '$created.name',
5566
- {
5567
- $ifNull: [
5568
- { $toString: '$id_user' },
5569
- 'Unknown User'
5570
- ]
5571
- }
5572
- ]
5573
- }
5574
- ]
5575
- }
5576
- ]
5577
- }
5578
- ]
5579
- }
5580
- ]
5581
- })
5582
- }
5583
- },
5584
- {
5585
- $match: {
5586
- effective_date: {
5587
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'month', amount: 6 } },
5588
- $lt: '$$NOW'
5589
- }
5590
- }
5591
- },
5592
- {
5593
- $group: {
5594
- _id: {
5595
- user: '$user_label',
5596
- bucket: {
5597
- $dateTrunc: {
5598
- date: '$effective_date',
5599
- unit: 'month'
5600
- }
5601
- }
5602
- },
5603
- billable_hours: { $sum: '$billable_hours_value' },
5604
- ticket_count: { $sum: 1 }
5605
- }
5606
- },
5607
- {
5608
- $project: {
5609
- _id: 0,
5610
- user: '$_id.user',
5611
- month: {
5612
- $dateToString: {
5613
- format: '%Y-%m',
5614
- date: '$_id.bucket'
5615
- }
5616
- },
5617
- billable_hours: 1,
5618
- ticket_count: 1
5619
- }
5620
- },
5621
- { $sort: { user: 1, month: 1 } },
5622
- { $limit: 400 }
5623
- ],
5624
- options: {
5625
- allowDiskUse: true,
5626
- export: true,
5627
- limit: 400
5628
- }
5629
- },
5630
- cleaned: '',
5631
- rawLine: 'HEURISTIC_AGG(support-ticket-billable-hours-user-month-last-6m)'
5632
- };
4816
+ if (/\b(?:per|by|each)\s+day\b|\bdaily\b/.test(normalized)) {
4817
+ return 'day';
4818
+ }
4819
+ if (/\b(?:per|by|each)\s+week\b|\bweekly\b/.test(normalized)) {
4820
+ return 'week';
4821
+ }
4822
+ if (/\b(?:per|by|each)\s+month\b|\bmonthly\b/.test(normalized)) {
4823
+ return 'month';
4824
+ }
4825
+ if (/\b(?:per|by|each)\s+year\b|\byearly\b|\bannually\b/.test(normalized)) {
4826
+ return 'year';
4827
+ }
4828
+ return null;
4829
+ }
4830
+ function resolveAssistantGenericPersonName(message) {
4831
+ var e_4, _a;
4832
+ var raw = normalizeOptionalString(message);
4833
+ if (!raw) {
4834
+ return null;
4835
+ }
4836
+ var patterns = [
4837
+ /\b(?:has|for|by)\s+([a-z][a-z]+(?:\s+[a-z][a-z]+){0,2})\s+(?:billed|logged|worked|recorded|entered)\b/i,
4838
+ /\b(?:for|by)\s+([a-z][a-z]+(?:\s+[a-z][a-z]+){0,2})\b/i
4839
+ ];
4840
+ try {
4841
+ for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
4842
+ var pattern = patterns_1_1.value;
4843
+ var match = raw.match(pattern);
4844
+ var candidate = normalizeOptionalString(match === null || match === void 0 ? void 0 : match[1]);
4845
+ if (!candidate) {
4846
+ continue;
4847
+ }
4848
+ var tokenized = tokenizeCollectionText(candidate);
4849
+ if (!tokenized.length) {
4850
+ continue;
4851
+ }
4852
+ if (['month', 'week', 'year', 'day', 'hours', 'hour'].includes(tokenized[0])) {
4853
+ continue;
4854
+ }
4855
+ return candidate;
4856
+ }
4857
+ }
4858
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
4859
+ finally {
4860
+ try {
4861
+ if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
4862
+ }
4863
+ finally { if (e_4) throw e_4.error; }
4864
+ }
4865
+ return null;
4866
+ }
4867
+ function analyzeAssistantGenericHoursIntent(message) {
4868
+ var normalized = normalizeOptionalString(message).toLowerCase();
4869
+ if (!normalized) {
4870
+ return null;
4871
+ }
4872
+ var hasHoursSignal = /\b(hours?|billable|billed|logged|labor|time(?:\s+entry|sheet|tracking)?)\b/.test(normalized);
4873
+ var hasQuestionSignal = /\b(how\s+many|total|sum|average|avg)\b/.test(normalized);
4874
+ if (!hasHoursSignal || !hasQuestionSignal) {
4875
+ return null;
4876
+ }
4877
+ var window = resolveAssistantGenericWindow(normalized);
4878
+ if (!window) {
4879
+ return null;
4880
+ }
4881
+ var requestedGrain = resolveAssistantGenericTimeGrain(normalized);
4882
+ var averageOverWindow = /\b(avg|average)\b/.test(normalized)
4883
+ && /\b(each|per|by)\s+(day|week|month|year)\b/.test(normalized);
4884
+ var timeGrain = requestedGrain || window.unit;
4885
+ if (averageOverWindow && !requestedGrain && window.unit === 'year') {
4886
+ timeGrain = 'month';
4887
+ }
4888
+ return {
4889
+ timeGrain: timeGrain,
4890
+ windowUnit: window.unit,
4891
+ windowAmount: window.amount,
4892
+ fullCalendarPeriods: window.fullCalendarPeriods,
4893
+ averageOverWindow: averageOverWindow,
4894
+ personName: resolveAssistantGenericPersonName(message)
4895
+ };
4896
+ }
4897
+ function convertAssistantGenericWindowAmount(amount, fromUnit, toUnit) {
4898
+ if (fromUnit === toUnit) {
4899
+ return amount;
5633
4900
  }
5634
- if (/(last\s+20).*(deliver(?:y|ies)).*(product).*(destination)/.test(text)) {
4901
+ var daysPerUnit = {
4902
+ day: 1,
4903
+ week: 7,
4904
+ month: 30,
4905
+ year: 365
4906
+ };
4907
+ var fromDays = amount * (daysPerUnit[fromUnit] || 1);
4908
+ var converted = (0, common_1.round)(fromDays / (daysPerUnit[toUnit] || 1));
4909
+ return Math.max(converted, 1);
4910
+ }
4911
+ function resolveAssistantAverageWindowDivisor(intent) {
4912
+ if (!(intent === null || intent === void 0 ? void 0 : intent.averageOverWindow)) {
4913
+ return 1;
4914
+ }
4915
+ var amount = Math.max((0, common_1.round)(intent.windowAmount || 0), 1);
4916
+ if (intent.windowUnit === intent.timeGrain) {
4917
+ return amount;
4918
+ }
4919
+ return convertAssistantGenericWindowAmount(amount, intent.windowUnit, intent.timeGrain);
4920
+ }
4921
+ function buildAssistantIfNullExpr(values, fallbackValue) {
4922
+ var cleanValues = Array.isArray(values)
4923
+ ? values.filter(function (value) { return value !== null && value !== undefined; })
4924
+ : [];
4925
+ if (!cleanValues.length) {
4926
+ return fallbackValue;
4927
+ }
4928
+ var expr = fallbackValue;
4929
+ for (var i = cleanValues.length - 1; i >= 0; i -= 1) {
4930
+ expr = { $ifNull: [cleanValues[i], expr] };
4931
+ }
4932
+ return expr;
4933
+ }
4934
+ function normalizeAssistantSchemaQueryPath(field) {
4935
+ return normalizeLookupPath(field);
4936
+ }
4937
+ function resolveAssistantSchemaDateFields(schemaFields) {
4938
+ var seen = new Set();
4939
+ var fields = [];
4940
+ (schemaFields || []).forEach(function (field) {
4941
+ var normalized = normalizeAssistantSchemaQueryPath(field);
4942
+ if (!normalized || seen.has(normalized)) {
4943
+ return;
4944
+ }
4945
+ var lower = normalized.toLowerCase();
4946
+ if (lower === 'date'
4947
+ || lower.startsWith('date_')
4948
+ || lower.endsWith('_date')
4949
+ || lower.endsWith('_at')
4950
+ || lower === 'createdat'
4951
+ || lower === 'updatedat') {
4952
+ seen.add(normalized);
4953
+ fields.push(normalized);
4954
+ }
4955
+ });
4956
+ var preferredOrder = [
4957
+ 'date',
4958
+ 'date_created',
4959
+ 'createdAt',
4960
+ 'date_invoice',
4961
+ 'date_invoiced',
4962
+ 'date_paid',
4963
+ 'date_completed',
4964
+ 'updatedAt'
4965
+ ];
4966
+ return fields.sort(function (a, b) {
4967
+ var aIndex = preferredOrder.indexOf(a);
4968
+ var bIndex = preferredOrder.indexOf(b);
4969
+ if (aIndex !== -1 || bIndex !== -1) {
4970
+ return (aIndex === -1 ? 999 : aIndex) - (bIndex === -1 ? 999 : bIndex);
4971
+ }
4972
+ return a.localeCompare(b);
4973
+ });
4974
+ }
4975
+ function resolveAssistantSchemaHourMetricFields(schemaFields) {
4976
+ var seen = new Set();
4977
+ var scored = [];
4978
+ (schemaFields || []).forEach(function (field) {
4979
+ var normalized = normalizeAssistantSchemaQueryPath(field);
4980
+ if (!normalized || seen.has(normalized) || isAssistantIdField(normalized)) {
4981
+ return;
4982
+ }
4983
+ var tokens = tokenizeFieldKey(normalized);
4984
+ if (!tokens.length) {
4985
+ return;
4986
+ }
4987
+ var hasHours = tokens.includes('hour') || tokens.includes('hours');
4988
+ var hasBill = tokens.includes('billable') || tokens.includes('billed') || tokens.includes('billing');
4989
+ var hasTime = tokens.includes('time') || tokens.includes('labor') || tokens.includes('duration');
4990
+ if (!hasHours && !hasBill && !hasTime) {
4991
+ return;
4992
+ }
4993
+ var score = 0;
4994
+ if (hasHours) {
4995
+ score += 3;
4996
+ }
4997
+ if (hasBill) {
4998
+ score += 3;
4999
+ }
5000
+ if (hasTime) {
5001
+ score += 1;
5002
+ }
5003
+ if (tokens.includes('estimated') || tokens.includes('estimate')) {
5004
+ score -= 2;
5005
+ }
5006
+ if (score <= 0) {
5007
+ return;
5008
+ }
5009
+ seen.add(normalized);
5010
+ scored.push({ field: normalized, score: score });
5011
+ });
5012
+ return scored
5013
+ .sort(function (a, b) {
5014
+ if (a.score !== b.score) {
5015
+ return b.score - a.score;
5016
+ }
5017
+ return a.field.localeCompare(b.field);
5018
+ })
5019
+ .slice(0, 6)
5020
+ .map(function (entry) { return entry.field; });
5021
+ }
5022
+ function resolveAssistantSchemaActorNameFields(schemaFields) {
5023
+ var scored = [];
5024
+ var seen = new Set();
5025
+ (schemaFields || []).forEach(function (field) {
5026
+ var normalized = normalizeAssistantSchemaQueryPath(field);
5027
+ if (!normalized || seen.has(normalized) || isAssistantIdField(normalized)) {
5028
+ return;
5029
+ }
5030
+ var tokens = tokenizeFieldKey(normalized);
5031
+ if (!tokens.length) {
5032
+ return;
5033
+ }
5034
+ var hasName = tokens.includes('name') || tokens.includes('fullname') || tokens.includes('display');
5035
+ var hasActor = tokens.includes('user')
5036
+ || tokens.includes('employee')
5037
+ || tokens.includes('assignee')
5038
+ || tokens.includes('assigned')
5039
+ || tokens.includes('owner')
5040
+ || tokens.includes('creator')
5041
+ || tokens.includes('created')
5042
+ || tokens.includes('technician');
5043
+ if (!hasName && !hasActor) {
5044
+ return;
5045
+ }
5046
+ var score = 0;
5047
+ if (hasName) {
5048
+ score += 2;
5049
+ }
5050
+ if (hasActor) {
5051
+ score += 2;
5052
+ }
5053
+ if (normalized.includes('client')) {
5054
+ score -= 1;
5055
+ }
5056
+ if (score <= 0) {
5057
+ return;
5058
+ }
5059
+ seen.add(normalized);
5060
+ scored.push({ field: normalized, score: score });
5061
+ });
5062
+ return scored
5063
+ .sort(function (a, b) {
5064
+ if (a.score !== b.score) {
5065
+ return b.score - a.score;
5066
+ }
5067
+ return a.field.localeCompare(b.field);
5068
+ })
5069
+ .slice(0, 8)
5070
+ .map(function (entry) { return entry.field; });
5071
+ }
5072
+ function resolveAssistantSchemaActorIdFields(schemaFields) {
5073
+ var seen = new Set();
5074
+ var fields = [];
5075
+ (schemaFields || []).forEach(function (field) {
5076
+ var normalized = normalizeAssistantSchemaQueryPath(field);
5077
+ if (!normalized || seen.has(normalized)) {
5078
+ return;
5079
+ }
5080
+ var tokens = tokenizeFieldKey(normalized);
5081
+ if (!tokens.length || !tokens.includes('id')) {
5082
+ return;
5083
+ }
5084
+ var hasActor = tokens.includes('user')
5085
+ || tokens.includes('employee')
5086
+ || tokens.includes('assignee')
5087
+ || tokens.includes('assigned')
5088
+ || tokens.includes('owner')
5089
+ || tokens.includes('creator')
5090
+ || tokens.includes('technician');
5091
+ if (!hasActor) {
5092
+ return;
5093
+ }
5094
+ seen.add(normalized);
5095
+ fields.push(normalized);
5096
+ });
5097
+ return fields.slice(0, 6);
5098
+ }
5099
+ function resolveAssistantGenericHoursCollectionCandidates(message, collectionHints) {
5100
+ var reportCollections = listAssistantReportBuilderCollectionsFromManager();
5101
+ if (!reportCollections.length) {
5102
+ return mergeAssistantHintValues(collectionHints, resolveAssistantDefaultCollectionHints(message));
5103
+ }
5104
+ var expanded = expandAssistantTermSynonyms(message).expanded || message;
5105
+ var tokens = tokenizeCollectionText(expanded);
5106
+ var ranked = resolveCollectionHintsFromTokens(tokens, reportCollections, 24);
5107
+ return mergeAssistantHintValues(collectionHints, resolveAssistantDefaultCollectionHints(message), ranked, reportCollections).slice(0, 80);
5108
+ }
5109
+ function scoreAssistantGenericHoursCollection(params) {
5110
+ var baseScore = scoreCollectionMatch(params.messageTokens, params.collection);
5111
+ var metricScore = Math.min(params.metricFields.length, 3) * 14;
5112
+ var dateScore = Math.min(params.dateFields.length, 2) * 8;
5113
+ var actorScore = params.actorNameFields.length
5114
+ ? Math.min(params.actorNameFields.length, 2) * 10
5115
+ : (params.actorIdFields.length ? 5 : 0);
5116
+ var personPenalty = params.personName && !params.actorNameFields.length && !params.actorIdFields.length
5117
+ ? -20
5118
+ : 0;
5119
+ var versionPenalty = isVersionCollectionName(params.collection) ? -20 : 0;
5120
+ return baseScore + metricScore + dateScore + actorScore + personPenalty + versionPenalty;
5121
+ }
5122
+ function buildAssistantGenericHoursDateWindowExpr(intent) {
5123
+ var amount = Math.max((0, common_1.round)(intent.windowAmount || 0), 1);
5124
+ if (intent.fullCalendarPeriods && (intent.windowUnit === 'month' || intent.windowUnit === 'year')) {
5125
+ var monthAmount = intent.windowUnit === 'year' ? amount * 12 : amount;
5126
+ var currentMonthStart = { $dateTrunc: { date: '$$NOW', unit: 'month' } };
5635
5127
  return {
5636
- type: 'aggregate',
5637
- payload: {
5638
- collection: 'work-order-dynamics',
5639
- permissionView: '/work-order-dynamic/list',
5640
- pipeline: [
5641
- {
5642
- $match: {
5643
- status: { $in: ['Completed', 'Closed'] }
5644
- }
5645
- },
5646
- { $sort: { date_completed: -1, date_created: -1, _id: -1 } },
5647
- { $limit: 20 },
5648
- { $unwind: { path: '$chemicals', preserveNullAndEmptyArrays: true } },
5649
- {
5650
- $project: {
5651
- _id: 0,
5652
- work_order: { $ifNull: ['$wo_string', '$wo_number'] },
5653
- customer: 1,
5654
- product: '$chemicals.chemical',
5655
- volume: {
5656
- $add: [
5657
- { $ifNull: ['$chemicals.delivered.quantity', 0] },
5658
- { $ifNull: ['$chemicals.returned.quantity', 0] }
5659
- ]
5660
- },
5661
- destination: { $ifNull: ['$location.name', '$location'] },
5662
- date: { $ifNull: ['$date_completed', '$date_created'] }
5663
- }
5664
- }
5665
- ]
5666
- },
5667
- cleaned: '',
5668
- rawLine: 'HEURISTIC_AGG(last-deliveries)'
5128
+ $gte: { $dateSubtract: { startDate: currentMonthStart, unit: 'month', amount: monthAmount } },
5129
+ $lt: currentMonthStart
5669
5130
  };
5670
5131
  }
5671
- if (/\bjobs?\b/.test(text)
5672
- && /(\bhighest\b|\btop\b)/.test(text)
5673
- && /\btreatment\s+volume\b/.test(text)
5674
- && /\b(last|past)\s+90\s+days?\b/.test(text)) {
5132
+ return {
5133
+ $gte: { $dateSubtract: { startDate: '$$NOW', unit: intent.windowUnit, amount: amount } },
5134
+ $lt: '$$NOW'
5135
+ };
5136
+ }
5137
+ function buildAssistantGenericHoursDirective(message, collectionHints) {
5138
+ var _a, _b, _c, _d;
5139
+ var intent = analyzeAssistantGenericHoursIntent(message);
5140
+ if (!intent) {
5141
+ return null;
5142
+ }
5143
+ var normalizedMessage = normalizeOptionalString(message);
5144
+ var expandedMessage = expandAssistantTermSynonyms(normalizedMessage).expanded || normalizedMessage;
5145
+ var messageTokens = tokenizeCollectionText(expandedMessage);
5146
+ var candidates = resolveAssistantGenericHoursCollectionCandidates(message, collectionHints);
5147
+ if (!candidates.length) {
5148
+ return null;
5149
+ }
5150
+ var rankedCandidates = candidates
5151
+ .map(function (collection) {
5152
+ var schemaFields = getCollectionSchemaFieldNames(collection);
5153
+ var dateFields = resolveAssistantSchemaDateFields(schemaFields);
5154
+ var metricFields = resolveAssistantSchemaHourMetricFields(schemaFields);
5155
+ var actorNameFields = resolveAssistantSchemaActorNameFields(schemaFields);
5156
+ var actorIdFields = resolveAssistantSchemaActorIdFields(schemaFields);
5675
5157
  return {
5676
- type: 'aggregate',
5677
- payload: {
5678
- collection: 'work-order-dynamics',
5679
- permissionView: '/work-order-dynamic/list',
5680
- pipeline: [
5681
- {
5682
- $addFields: {
5683
- effective_date: { $ifNull: ['$date_completed', { $ifNull: ['$date_created', '$createdAt'] }] },
5684
- treatment_volume_value: {
5685
- $ifNull: [
5686
- '$treatment_volume',
5687
- {
5688
- $ifNull: [
5689
- '$total_treatment_volume',
5690
- {
5691
- $reduce: {
5692
- input: { $ifNull: ['$chemicals', []] },
5693
- initialValue: 0,
5694
- in: {
5695
- $add: [
5696
- '$$value',
5697
- {
5698
- $ifNull: [
5699
- '$$this.quantity',
5700
- {
5701
- $ifNull: [
5702
- '$$this.volume',
5703
- { $ifNull: ['$$this.delivered.quantity', 0] }
5704
- ]
5705
- }
5706
- ]
5707
- }
5708
- ]
5709
- }
5710
- }
5711
- }
5712
- ]
5713
- }
5714
- ]
5715
- }
5716
- }
5717
- },
5718
- {
5719
- $match: {
5720
- effective_date: {
5721
- $gte: { $dateSubtract: { startDate: '$$NOW', unit: 'day', amount: 90 } },
5722
- $lt: '$$NOW'
5723
- }
5724
- }
5725
- },
5726
- {
5727
- $group: {
5728
- _id: {
5729
- $ifNull: [
5730
- '$job.name',
5731
- {
5732
- $ifNull: [
5733
- '$job_name',
5734
- { $ifNull: ['$job', { $ifNull: ['$job_number', 'Unknown Job'] }] }
5735
- ]
5736
- }
5737
- ]
5738
- },
5739
- total_treatment_volume: {
5740
- $sum: {
5741
- $convert: {
5742
- input: '$treatment_volume_value',
5743
- to: 'double',
5744
- onError: 0,
5745
- onNull: 0
5746
- }
5747
- }
5748
- },
5749
- work_order_count: { $sum: 1 }
5750
- }
5751
- },
5752
- { $sort: { total_treatment_volume: -1, work_order_count: -1, _id: 1 } },
5753
- { $limit: 20 },
5754
- {
5755
- $project: {
5756
- _id: 0,
5757
- job: '$_id',
5758
- total_treatment_volume: 1,
5759
- work_order_count: 1
5760
- }
5761
- }
5762
- ],
5763
- options: {
5764
- allowDiskUse: true,
5765
- export: true,
5766
- limit: 20
5767
- }
5768
- },
5769
- cleaned: '',
5770
- rawLine: 'HEURISTIC_AGG(work-order-jobs-top-volume)'
5158
+ collection: collection,
5159
+ dateFields: dateFields,
5160
+ metricFields: metricFields,
5161
+ actorNameFields: actorNameFields,
5162
+ actorIdFields: actorIdFields,
5163
+ score: scoreAssistantGenericHoursCollection({
5164
+ collection: collection,
5165
+ messageTokens: messageTokens,
5166
+ metricFields: metricFields,
5167
+ actorNameFields: actorNameFields,
5168
+ actorIdFields: actorIdFields,
5169
+ dateFields: dateFields,
5170
+ personName: intent.personName
5171
+ })
5771
5172
  };
5772
- }
5773
- var hintCollection = mergeAssistantHintValues(collectionHints, resolveAssistantDefaultCollectionHints(message))[0] || '';
5774
- if (!hintCollection) {
5173
+ })
5174
+ .filter(function (entry) { return entry.dateFields.length && entry.metricFields.length && entry.score > 20; })
5175
+ .sort(function (a, b) { return b.score - a.score; });
5176
+ var selected = rankedCandidates[0];
5177
+ if (!selected) {
5775
5178
  return null;
5776
5179
  }
5180
+ var dateWindow = buildAssistantGenericHoursDateWindowExpr(intent);
5181
+ var addFieldsStage = {
5182
+ $addFields: {
5183
+ effective_date: buildAssistantIfNullExpr(selected.dateFields.map(function (field) { return "$".concat(field); }), null),
5184
+ metric_value: {
5185
+ $convert: {
5186
+ input: buildAssistantIfNullExpr(selected.metricFields.map(function (field) { return "$".concat(field); }), 0),
5187
+ to: 'double',
5188
+ onError: 0,
5189
+ onNull: 0
5190
+ }
5191
+ }
5192
+ }
5193
+ };
5194
+ var matchClauses = [
5195
+ {
5196
+ effective_date: dateWindow
5197
+ },
5198
+ {
5199
+ metric_value: { $gt: 0 }
5200
+ }
5201
+ ];
5202
+ if (intent.personName) {
5203
+ var personRegex_1 = { $regex: escapeRegexValue(intent.personName), $options: 'i' };
5204
+ var actorNameMatches = selected.actorNameFields.map(function (field) {
5205
+ var _a;
5206
+ return (_a = {}, _a[field] = personRegex_1, _a);
5207
+ });
5208
+ var actorIdMatches = selected.actorIdFields.map(function (field) {
5209
+ var _a;
5210
+ return (_a = {}, _a[field] = personRegex_1, _a);
5211
+ });
5212
+ var actorMatches = __spreadArray(__spreadArray([], __read(actorNameMatches), false), __read(actorIdMatches), false).slice(0, 12);
5213
+ if (actorMatches.length) {
5214
+ matchClauses.push({ $or: actorMatches });
5215
+ }
5216
+ }
5217
+ var grain = intent.timeGrain;
5218
+ var divisor = Math.max(resolveAssistantAverageWindowDivisor(intent), 1);
5219
+ var bucketExpr = grain === 'week'
5220
+ ? { $dateTrunc: { date: '$effective_date', unit: 'week', startOfWeek: 'monday' } }
5221
+ : { $dateTrunc: { date: '$effective_date', unit: grain } };
5222
+ var totalMetricKey = 'total_hours';
5223
+ var pipeline = [
5224
+ addFieldsStage,
5225
+ {
5226
+ $match: {
5227
+ $and: matchClauses
5228
+ }
5229
+ },
5230
+ {
5231
+ $group: (_a = {
5232
+ _id: bucketExpr
5233
+ },
5234
+ _a[totalMetricKey] = { $sum: '$metric_value' },
5235
+ _a)
5236
+ }
5237
+ ];
5238
+ if (intent.averageOverWindow) {
5239
+ var avgColumnName = grain === 'month' ? 'avg_monthly_hours' : "avg_".concat(grain, "_hours");
5240
+ pipeline.push({
5241
+ $group: {
5242
+ _id: null,
5243
+ total_hours: { $sum: "$".concat(totalMetricKey) }
5244
+ }
5245
+ }, {
5246
+ $project: (_b = {
5247
+ _id: 0
5248
+ },
5249
+ _b[avgColumnName] = { $divide: ['$total_hours', divisor] },
5250
+ _b)
5251
+ });
5252
+ }
5253
+ else {
5254
+ var dateFormat = grain === 'day' || grain === 'week'
5255
+ ? '%Y-%m-%d'
5256
+ : grain === 'year'
5257
+ ? '%Y'
5258
+ : '%Y-%m';
5259
+ pipeline.push({
5260
+ $project: (_c = {
5261
+ _id: 0
5262
+ },
5263
+ _c[grain] = {
5264
+ $dateToString: {
5265
+ format: dateFormat,
5266
+ date: '$_id'
5267
+ }
5268
+ },
5269
+ _c[totalMetricKey] = 1,
5270
+ _c)
5271
+ }, {
5272
+ $sort: (_d = {},
5273
+ _d[grain] = 1,
5274
+ _d)
5275
+ });
5276
+ }
5777
5277
  return {
5778
- type: 'read',
5278
+ type: 'aggregate',
5779
5279
  payload: {
5780
- collection: hintCollection,
5781
- permissionView: resolveDefaultAssistantPermissionView(hintCollection),
5782
- query: {},
5280
+ collection: selected.collection,
5281
+ permissionView: resolveDefaultAssistantPermissionView(selected.collection),
5282
+ pipeline: pipeline,
5783
5283
  options: {
5784
- sort: { updatedAt: -1, createdAt: -1, _id: -1 },
5785
- limit: 20
5284
+ allowDiskUse: true,
5285
+ limit: intent.averageOverWindow ? 20 : 400
5786
5286
  }
5787
5287
  },
5788
5288
  cleaned: '',
5789
- rawLine: 'HEURISTIC_READ(default)'
5289
+ rawLine: 'HEURISTIC_AGG(schema-hours-user-time)'
5790
5290
  };
5791
5291
  }
5292
+ function isAssistantSchemaHoursHeuristicDirective(directive) {
5293
+ var rawLine = normalizeOptionalString(directive === null || directive === void 0 ? void 0 : directive.rawLine).toLowerCase();
5294
+ return rawLine.includes('heuristic_agg(schema-hours-user-time)');
5295
+ }
5296
+ function isAssistantDeterministicHeuristicDirective(directive) {
5297
+ return isAssistantSchemaHoursHeuristicDirective(directive);
5298
+ }
5299
+ function buildAssistantHeuristicDirective(message, collectionHints) {
5300
+ if (!normalizeOptionalString(message)) {
5301
+ return null;
5302
+ }
5303
+ var schemaHoursDirective = buildAssistantGenericHoursDirective(message, collectionHints);
5304
+ if (schemaHoursDirective) {
5305
+ return schemaHoursDirective;
5306
+ }
5307
+ return null;
5308
+ }
5792
5309
  function resolveDefaultAssistantPermissionView(collection) {
5793
5310
  var normalizedCollection = normalizeOptionalString(collection).toLowerCase();
5794
5311
  if (!normalizedCollection) {
@@ -5904,7 +5421,7 @@ function ensureAssistantDisplayColumns(display, requestedColumns) {
5904
5421
  return __assign(__assign({}, display), { columns: columns, rows: rows });
5905
5422
  }
5906
5423
  function resolveAssistantPipelineTimeGrain(pipeline) {
5907
- var e_3, _a;
5424
+ var e_5, _a;
5908
5425
  if (!Array.isArray(pipeline) || !pipeline.length) {
5909
5426
  return null;
5910
5427
  }
@@ -5966,12 +5483,12 @@ function resolveAssistantPipelineTimeGrain(pipeline) {
5966
5483
  }
5967
5484
  }
5968
5485
  }
5969
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
5486
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
5970
5487
  finally {
5971
5488
  try {
5972
5489
  if (priority_1_1 && !priority_1_1.done && (_a = priority_1.return)) _a.call(priority_1);
5973
5490
  }
5974
- finally { if (e_3) throw e_3.error; }
5491
+ finally { if (e_5) throw e_5.error; }
5975
5492
  }
5976
5493
  return null;
5977
5494
  }
@@ -6674,7 +6191,7 @@ function applyAssistantDatedReportWindow(value, toolResult) {
6674
6191
  return "".concat(line, "\n\n").concat(content).trim();
6675
6192
  }
6676
6193
  function resolveAssistantDatedReportWindow(toolResult) {
6677
- var e_4, _a;
6194
+ var e_6, _a;
6678
6195
  var _b, _c, _d, _e, _f, _g, _h, _j;
6679
6196
  var verificationWindow = (_d = (_c = (_b = toolResult === null || toolResult === void 0 ? void 0 : toolResult.output) === null || _b === void 0 ? void 0 : _b.verification) === null || _c === void 0 ? void 0 : _c.metrics) === null || _d === void 0 ? void 0 : _d.window;
6680
6197
  var verificationStart = normalizeOptionalString(verificationWindow === null || verificationWindow === void 0 ? void 0 : verificationWindow.startDate);
@@ -6740,17 +6257,17 @@ function resolveAssistantDatedReportWindow(toolResult) {
6740
6257
  };
6741
6258
  }
6742
6259
  }
6743
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
6260
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
6744
6261
  finally {
6745
6262
  try {
6746
6263
  if (pipelineCandidates_1_1 && !pipelineCandidates_1_1.done && (_a = pipelineCandidates_1.return)) _a.call(pipelineCandidates_1);
6747
6264
  }
6748
- finally { if (e_4) throw e_4.error; }
6265
+ finally { if (e_6) throw e_6.error; }
6749
6266
  }
6750
6267
  return null;
6751
6268
  }
6752
6269
  function buildAssistantDebugPayload(params) {
6753
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7;
6270
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9;
6754
6271
  var notes = [];
6755
6272
  notes.push("Request classification: ".concat(params.requestType, " (").concat(params.requestTypeSource, ")."));
6756
6273
  if (params.dataQuestion) {
@@ -6891,14 +6408,28 @@ function buildAssistantDebugPayload(params) {
6891
6408
  else if (((_y = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.collectionRetry) === null || _y === void 0 ? void 0 : _y.attempted) && Array.isArray(fallbackInfo.collectionRetry.tried) && fallbackInfo.collectionRetry.tried.length) {
6892
6409
  notes.push("Cross-collection retry attempted: ".concat(fallbackInfo.collectionRetry.tried.join(', '), "."));
6893
6410
  }
6894
- if ((_z = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idLookup) === null || _z === void 0 ? void 0 : _z.used) {
6411
+ if ((_z = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.relationshipRetry) === null || _z === void 0 ? void 0 : _z.used) {
6412
+ var from = fallbackInfo.relationshipRetry.from || 'unknown';
6413
+ var to = fallbackInfo.relationshipRetry.to || 'unknown';
6414
+ var prefix = fallbackInfo.relationshipRetry.prefix ? " via ".concat(fallbackInfo.relationshipRetry.prefix) : '';
6415
+ notes.push("Relationship retry: ".concat(from, " -> ").concat(to).concat(prefix, "."));
6416
+ }
6417
+ else if (((_0 = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.relationshipRetry) === null || _0 === void 0 ? void 0 : _0.attempted) && Array.isArray(fallbackInfo.relationshipRetry.candidates) && fallbackInfo.relationshipRetry.candidates.length) {
6418
+ var targets = fallbackInfo.relationshipRetry.candidates
6419
+ .map(function (entry) { return normalizeOptionalString(entry === null || entry === void 0 ? void 0 : entry.collection); })
6420
+ .filter(Boolean);
6421
+ if (targets.length) {
6422
+ notes.push("Relationship retry attempted: ".concat(targets.join(', '), "."));
6423
+ }
6424
+ }
6425
+ if ((_1 = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idLookup) === null || _1 === void 0 ? void 0 : _1.used) {
6895
6426
  var field = fallbackInfo.idLookup.field || 'id';
6896
6427
  var strategy = fallbackInfo.idLookup.strategy || 'lookup';
6897
6428
  var collection = fallbackInfo.idLookup.collection ? " in ".concat(fallbackInfo.idLookup.collection) : '';
6898
6429
  var detail = fallbackInfo.idLookup.nameField ? " via ".concat(fallbackInfo.idLookup.nameField) : '';
6899
6430
  notes.push("Resolved ".concat(field, " by ").concat(strategy).concat(collection).concat(detail, "."));
6900
6431
  }
6901
- if ((_0 = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idDisplayLookup) === null || _0 === void 0 ? void 0 : _0.used) {
6432
+ if ((_2 = fallbackInfo === null || fallbackInfo === void 0 ? void 0 : fallbackInfo.idDisplayLookup) === null || _2 === void 0 ? void 0 : _2.used) {
6902
6433
  var lookups = Array.isArray(fallbackInfo.idDisplayLookup.lookups)
6903
6434
  ? fallbackInfo.idDisplayLookup.lookups
6904
6435
  : [];
@@ -6909,7 +6440,7 @@ function buildAssistantDebugPayload(params) {
6909
6440
  notes.push(summary ? "Resolved id lookups for display: ".concat(summary, ".") : 'Resolved id lookups for display.');
6910
6441
  }
6911
6442
  if (params.toolError) {
6912
- var errorMessage = ((_1 = params.toolError) === null || _1 === void 0 ? void 0 : _1.message) || String(params.toolError || '');
6443
+ var errorMessage = ((_3 = params.toolError) === null || _3 === void 0 ? void 0 : _3.message) || String(params.toolError || '');
6913
6444
  if (errorMessage) {
6914
6445
  notes.push("Tool error: ".concat(errorMessage));
6915
6446
  }
@@ -6943,13 +6474,13 @@ function buildAssistantDebugPayload(params) {
6943
6474
  collectionResolved: resolvedCollection || undefined,
6944
6475
  collectionMatched: matchedCollection,
6945
6476
  collectionCandidates: candidateCollections.length ? candidateCollections : undefined,
6946
- collectionScore: typeof ((_2 = params.toolResponseDebug) === null || _2 === void 0 ? void 0 : _2.collectionScore) === 'number'
6477
+ collectionScore: typeof ((_4 = params.toolResponseDebug) === null || _4 === void 0 ? void 0 : _4.collectionScore) === 'number'
6947
6478
  ? params.toolResponseDebug.collectionScore
6948
6479
  : undefined,
6949
- query: ((_3 = params.toolResponseDebug) === null || _3 === void 0 ? void 0 : _3.query) || undefined,
6950
- pipeline: ((_4 = params.toolResponseDebug) === null || _4 === void 0 ? void 0 : _4.executedPipeline) || ((_5 = params.toolResponseDebug) === null || _5 === void 0 ? void 0 : _5.originalPipeline) || undefined,
6951
- options: ((_6 = params.toolResponseDebug) === null || _6 === void 0 ? void 0 : _6.options) || undefined,
6952
- fallbacks: ((_7 = params.toolResponseDebug) === null || _7 === void 0 ? void 0 : _7.fallbacks) || undefined,
6480
+ query: ((_5 = params.toolResponseDebug) === null || _5 === void 0 ? void 0 : _5.query) || undefined,
6481
+ pipeline: ((_6 = params.toolResponseDebug) === null || _6 === void 0 ? void 0 : _6.executedPipeline) || ((_7 = params.toolResponseDebug) === null || _7 === void 0 ? void 0 : _7.originalPipeline) || undefined,
6482
+ options: ((_8 = params.toolResponseDebug) === null || _8 === void 0 ? void 0 : _8.options) || undefined,
6483
+ fallbacks: ((_9 = params.toolResponseDebug) === null || _9 === void 0 ? void 0 : _9.fallbacks) || undefined,
6953
6484
  notes: notes
6954
6485
  };
6955
6486
  if (params.trace && typeof params.trace === 'object') {
@@ -7352,7 +6883,7 @@ function getValueAtPath(obj, path) {
7352
6883
  return walk(obj, 0);
7353
6884
  }
7354
6885
  function hasArrayValueAtPath(docs, path) {
7355
- var e_5, _a;
6886
+ var e_7, _a;
7356
6887
  if (!Array.isArray(docs) || !docs.length || !path) {
7357
6888
  return false;
7358
6889
  }
@@ -7365,17 +6896,17 @@ function hasArrayValueAtPath(docs, path) {
7365
6896
  }
7366
6897
  }
7367
6898
  }
7368
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
6899
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
7369
6900
  finally {
7370
6901
  try {
7371
6902
  if (docs_1_1 && !docs_1_1.done && (_a = docs_1.return)) _a.call(docs_1);
7372
6903
  }
7373
- finally { if (e_5) throw e_5.error; }
6904
+ finally { if (e_7) throw e_7.error; }
7374
6905
  }
7375
6906
  return false;
7376
6907
  }
7377
6908
  function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
7378
- var e_6, _a, e_7, _b;
6909
+ var e_8, _a, e_9, _b;
7379
6910
  if (!Array.isArray(docs) || !fieldPath) {
7380
6911
  return 'unknown';
7381
6912
  }
@@ -7388,7 +6919,7 @@ function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
7388
6919
  : doc === null || doc === void 0 ? void 0 : doc[fieldPath];
7389
6920
  var queue = Array.isArray(value) ? value : [value];
7390
6921
  try {
7391
- for (var queue_1 = (e_7 = void 0, __values(queue)), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {
6922
+ for (var queue_1 = (e_9 = void 0, __values(queue)), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {
7392
6923
  var entry = queue_1_1.value;
7393
6924
  if (entry === null || entry === undefined) {
7394
6925
  continue;
@@ -7401,21 +6932,21 @@ function inferIdFieldStorageTypeFromDocs(docs, fieldPath) {
7401
6932
  }
7402
6933
  }
7403
6934
  }
7404
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
6935
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
7405
6936
  finally {
7406
6937
  try {
7407
6938
  if (queue_1_1 && !queue_1_1.done && (_b = queue_1.return)) _b.call(queue_1);
7408
6939
  }
7409
- finally { if (e_7) throw e_7.error; }
6940
+ finally { if (e_9) throw e_9.error; }
7410
6941
  }
7411
6942
  }
7412
6943
  }
7413
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
6944
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
7414
6945
  finally {
7415
6946
  try {
7416
6947
  if (docs_2_1 && !docs_2_1.done && (_a = docs_2.return)) _a.call(docs_2);
7417
6948
  }
7418
- finally { if (e_6) throw e_6.error; }
6949
+ finally { if (e_8) throw e_8.error; }
7419
6950
  }
7420
6951
  return sawString ? 'string' : 'unknown';
7421
6952
  }
@@ -7510,7 +7041,7 @@ function normalizeLookupKeyValue(value) {
7510
7041
  return '';
7511
7042
  }
7512
7043
  function collectTopLevelIdFieldValues(docs, options) {
7513
- var e_8, _a, e_9, _b;
7044
+ var e_10, _a, e_11, _b;
7514
7045
  if (!Array.isArray(docs) || !docs.length) {
7515
7046
  return [];
7516
7047
  }
@@ -7558,26 +7089,26 @@ function collectTopLevelIdFieldValues(docs, options) {
7558
7089
  });
7559
7090
  };
7560
7091
  try {
7561
- for (var keys_1 = (e_9 = void 0, __values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
7092
+ for (var keys_1 = (e_11 = void 0, __values(keys)), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
7562
7093
  var key = keys_1_1.value;
7563
7094
  _loop_3(key);
7564
7095
  }
7565
7096
  }
7566
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
7097
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
7567
7098
  finally {
7568
7099
  try {
7569
7100
  if (keys_1_1 && !keys_1_1.done && (_b = keys_1.return)) _b.call(keys_1);
7570
7101
  }
7571
- finally { if (e_9) throw e_9.error; }
7102
+ finally { if (e_11) throw e_11.error; }
7572
7103
  }
7573
7104
  }
7574
7105
  }
7575
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
7106
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
7576
7107
  finally {
7577
7108
  try {
7578
7109
  if (docs_3_1 && !docs_3_1.done && (_a = docs_3.return)) _a.call(docs_3);
7579
7110
  }
7580
- finally { if (e_8) throw e_8.error; }
7111
+ finally { if (e_10) throw e_10.error; }
7581
7112
  }
7582
7113
  return Array.from(fieldMap.entries()).map(function (_a) {
7583
7114
  var _b = __read(_a, 2), field = _b[0], values = _b[1];
@@ -7588,7 +7119,7 @@ function collectTopLevelIdFieldValues(docs, options) {
7588
7119
  });
7589
7120
  }
7590
7121
  function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
7591
- var e_10, _a, e_11, _b;
7122
+ var e_12, _a, e_13, _b;
7592
7123
  var normalizedBase = normalizeOptionalString(baseToken);
7593
7124
  if (!normalizedBase) {
7594
7125
  return null;
@@ -7606,12 +7137,12 @@ function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
7606
7137
  }
7607
7138
  }
7608
7139
  }
7609
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
7140
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
7610
7141
  finally {
7611
7142
  try {
7612
7143
  if (schemaCandidates_1_1 && !schemaCandidates_1_1.done && (_a = schemaCandidates_1.return)) _a.call(schemaCandidates_1);
7613
7144
  }
7614
- finally { if (e_10) throw e_10.error; }
7145
+ finally { if (e_12) throw e_12.error; }
7615
7146
  }
7616
7147
  return schemaCandidates[0];
7617
7148
  }
@@ -7624,12 +7155,12 @@ function resolveLookupDisplayField(baseToken, probeDocs, schemaFields) {
7624
7155
  }
7625
7156
  }
7626
7157
  }
7627
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
7158
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
7628
7159
  finally {
7629
7160
  try {
7630
7161
  if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return)) _b.call(candidates_1);
7631
7162
  }
7632
- finally { if (e_11) throw e_11.error; }
7163
+ finally { if (e_13) throw e_13.error; }
7633
7164
  }
7634
7165
  return candidates.length ? candidates[0] : null;
7635
7166
  }
@@ -7642,8 +7173,8 @@ function resolveLookupMappingsForField(field, mappings) {
7642
7173
  }
7643
7174
  function applyIdLookupDisplayEnrichment(params) {
7644
7175
  return __awaiter(this, void 0, void 0, function () {
7645
- var docs, collection, db, dbName, idClient, idCustomer, isSuperAdmin, idFields, lookupMappings, allCollections, collectionProbeCache, collectionSchemaCache, lookupMeta, enrichedDocs, _loop_4, idFields_1, idFields_1_1, fieldEntry, e_12_1;
7646
- var e_12, _a;
7176
+ var docs, collection, db, dbName, idClient, idCustomer, isSuperAdmin, idFields, lookupMappings, allCollections, collectionProbeCache, collectionSchemaCache, lookupMeta, enrichedDocs, _loop_4, idFields_1, idFields_1_1, fieldEntry, e_14_1;
7177
+ var e_14, _a;
7647
7178
  return __generator(this, function (_b) {
7648
7179
  switch (_b.label) {
7649
7180
  case 0:
@@ -7667,8 +7198,8 @@ function applyIdLookupDisplayEnrichment(params) {
7667
7198
  lookupMeta = [];
7668
7199
  enrichedDocs = docs.map(function (doc) { return (__assign({}, doc)); });
7669
7200
  _loop_4 = function (fieldEntry) {
7670
- var values, baseToken, mappingMatches, candidateCollections, filteredCandidates, _loop_5, filteredCandidates_1, filteredCandidates_1_1, candidate, state_3, e_13_1;
7671
- var e_13, _c;
7201
+ var values, baseToken, mappingMatches, candidateCollections, filteredCandidates, _loop_5, filteredCandidates_1, filteredCandidates_1_1, candidate, state_3, e_15_1;
7202
+ var e_15, _c;
7672
7203
  return __generator(this, function (_d) {
7673
7204
  switch (_d.label) {
7674
7205
  case 0:
@@ -7817,7 +7348,7 @@ function applyIdLookupDisplayEnrichment(params) {
7817
7348
  _d.label = 1;
7818
7349
  case 1:
7819
7350
  _d.trys.push([1, 6, 7, 8]);
7820
- filteredCandidates_1 = (e_13 = void 0, __values(filteredCandidates)), filteredCandidates_1_1 = filteredCandidates_1.next();
7351
+ filteredCandidates_1 = (e_15 = void 0, __values(filteredCandidates)), filteredCandidates_1_1 = filteredCandidates_1.next();
7821
7352
  _d.label = 2;
7822
7353
  case 2:
7823
7354
  if (!!filteredCandidates_1_1.done) return [3 /*break*/, 5];
@@ -7833,14 +7364,14 @@ function applyIdLookupDisplayEnrichment(params) {
7833
7364
  return [3 /*break*/, 2];
7834
7365
  case 5: return [3 /*break*/, 8];
7835
7366
  case 6:
7836
- e_13_1 = _d.sent();
7837
- e_13 = { error: e_13_1 };
7367
+ e_15_1 = _d.sent();
7368
+ e_15 = { error: e_15_1 };
7838
7369
  return [3 /*break*/, 8];
7839
7370
  case 7:
7840
7371
  try {
7841
7372
  if (filteredCandidates_1_1 && !filteredCandidates_1_1.done && (_c = filteredCandidates_1.return)) _c.call(filteredCandidates_1);
7842
7373
  }
7843
- finally { if (e_13) throw e_13.error; }
7374
+ finally { if (e_15) throw e_15.error; }
7844
7375
  return [7 /*endfinally*/];
7845
7376
  case 8: return [2 /*return*/];
7846
7377
  }
@@ -7863,14 +7394,14 @@ function applyIdLookupDisplayEnrichment(params) {
7863
7394
  return [3 /*break*/, 3];
7864
7395
  case 6: return [3 /*break*/, 9];
7865
7396
  case 7:
7866
- e_12_1 = _b.sent();
7867
- e_12 = { error: e_12_1 };
7397
+ e_14_1 = _b.sent();
7398
+ e_14 = { error: e_14_1 };
7868
7399
  return [3 /*break*/, 9];
7869
7400
  case 8:
7870
7401
  try {
7871
7402
  if (idFields_1_1 && !idFields_1_1.done && (_a = idFields_1.return)) _a.call(idFields_1);
7872
7403
  }
7873
- finally { if (e_12) throw e_12.error; }
7404
+ finally { if (e_14) throw e_14.error; }
7874
7405
  return [7 /*endfinally*/];
7875
7406
  case 9:
7876
7407
  if (!lookupMeta.length) {
@@ -7889,7 +7420,7 @@ function applyIdLookupDisplayEnrichment(params) {
7889
7420
  });
7890
7421
  }
7891
7422
  function hasNonEmptyValue(docs, fieldPath, options) {
7892
- var e_14, _a;
7423
+ var e_16, _a;
7893
7424
  if (!Array.isArray(docs) || !fieldPath) {
7894
7425
  return false;
7895
7426
  }
@@ -7906,12 +7437,12 @@ function hasNonEmptyValue(docs, fieldPath, options) {
7906
7437
  }
7907
7438
  }
7908
7439
  }
7909
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
7440
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
7910
7441
  finally {
7911
7442
  try {
7912
7443
  if (docs_4_1 && !docs_4_1.done && (_a = docs_4.return)) _a.call(docs_4);
7913
7444
  }
7914
- finally { if (e_14) throw e_14.error; }
7445
+ finally { if (e_16) throw e_16.error; }
7915
7446
  }
7916
7447
  return false;
7917
7448
  }
@@ -10045,7 +9576,7 @@ function flattenAssistantExprClauses(expr) {
10045
9576
  return [expr];
10046
9577
  }
10047
9578
  function detectAssistantMonthWindowInExpr(expr, allowedDateFields) {
10048
- var e_15, _a;
9579
+ var e_17, _a;
10049
9580
  var clauses = flattenAssistantExprClauses(expr);
10050
9581
  if (!clauses.length) {
10051
9582
  return null;
@@ -10119,12 +9650,12 @@ function detectAssistantMonthWindowInExpr(expr, allowedDateFields) {
10119
9650
  return state_4.value;
10120
9651
  }
10121
9652
  }
10122
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
9653
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
10123
9654
  finally {
10124
9655
  try {
10125
9656
  if (lowerClauses_1_1 && !lowerClauses_1_1.done && (_a = lowerClauses_1.return)) _a.call(lowerClauses_1);
10126
9657
  }
10127
- finally { if (e_15) throw e_15.error; }
9658
+ finally { if (e_17) throw e_17.error; }
10128
9659
  }
10129
9660
  return null;
10130
9661
  }
@@ -10187,7 +9718,7 @@ function resolveAssistantMonthlyGroupDateFields(pipeline) {
10187
9718
  return fields;
10188
9719
  }
10189
9720
  function detectAssistantMonthWindowFromPipeline(pipeline) {
10190
- var e_16, _a;
9721
+ var e_18, _a;
10191
9722
  var _b;
10192
9723
  var monthlyFields = resolveAssistantMonthlyGroupDateFields(pipeline);
10193
9724
  var scanMatch = function (match) {
@@ -10215,12 +9746,12 @@ function detectAssistantMonthWindowFromPipeline(pipeline) {
10215
9746
  }
10216
9747
  }
10217
9748
  }
10218
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
9749
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
10219
9750
  finally {
10220
9751
  try {
10221
9752
  if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
10222
9753
  }
10223
- finally { if (e_16) throw e_16.error; }
9754
+ finally { if (e_18) throw e_18.error; }
10224
9755
  }
10225
9756
  return null;
10226
9757
  }
@@ -10480,7 +10011,7 @@ function matchContainsField(value, field) {
10480
10011
  });
10481
10012
  }
10482
10013
  function resolveAggregateCompletionFallback(pipeline) {
10483
- var e_17, _a;
10014
+ var e_19, _a;
10484
10015
  if (!Array.isArray(pipeline)) {
10485
10016
  return null;
10486
10017
  }
@@ -10493,7 +10024,7 @@ function resolveAggregateCompletionFallback(pipeline) {
10493
10024
  }
10494
10025
  var addFields = stage.$addFields;
10495
10026
  try {
10496
- for (var _b = (e_17 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
10027
+ for (var _b = (e_19 = void 0, __values(Object.keys(addFields))), _c = _b.next(); !_c.done; _c = _b.next()) {
10497
10028
  var key = _c.value;
10498
10029
  if (!isCompletionFieldName(key)) {
10499
10030
  continue;
@@ -10507,12 +10038,12 @@ function resolveAggregateCompletionFallback(pipeline) {
10507
10038
  }
10508
10039
  }
10509
10040
  }
10510
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
10041
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
10511
10042
  finally {
10512
10043
  try {
10513
10044
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
10514
10045
  }
10515
- finally { if (e_17) throw e_17.error; }
10046
+ finally { if (e_19) throw e_19.error; }
10516
10047
  }
10517
10048
  if (candidateField) {
10518
10049
  break;
@@ -10668,7 +10199,7 @@ function buildCompletionFallbackSources(field) {
10668
10199
  ]);
10669
10200
  }
10670
10201
  function resolveAggregateCompletionExprFallback(pipeline) {
10671
- var e_18, _a;
10202
+ var e_20, _a;
10672
10203
  if (!Array.isArray(pipeline)) {
10673
10204
  return null;
10674
10205
  }
@@ -10688,7 +10219,7 @@ function resolveAggregateCompletionExprFallback(pipeline) {
10688
10219
  }
10689
10220
  if (!candidateField) {
10690
10221
  try {
10691
- for (var _b = (e_18 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
10222
+ for (var _b = (e_20 = void 0, __values(Object.keys(matchStage))), _c = _b.next(); !_c.done; _c = _b.next()) {
10692
10223
  var key = _c.value;
10693
10224
  if (key.startsWith('$')) {
10694
10225
  continue;
@@ -10703,12 +10234,12 @@ function resolveAggregateCompletionExprFallback(pipeline) {
10703
10234
  }
10704
10235
  }
10705
10236
  }
10706
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
10237
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
10707
10238
  finally {
10708
10239
  try {
10709
10240
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
10710
10241
  }
10711
- finally { if (e_18) throw e_18.error; }
10242
+ finally { if (e_20) throw e_20.error; }
10712
10243
  }
10713
10244
  }
10714
10245
  if (!candidateField) {
@@ -10848,7 +10379,7 @@ function hasAssistantDateGroupingOperator(value) {
10848
10379
  return Object.keys(value).some(function (key) { return hasAssistantDateGroupingOperator(value[key]); });
10849
10380
  }
10850
10381
  function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths) {
10851
- var e_19, _a, e_20, _b;
10382
+ var e_21, _a, e_22, _b;
10852
10383
  if (!Array.isArray(pipeline) || groupIndex <= 0 || !groupPaths.length) {
10853
10384
  return false;
10854
10385
  }
@@ -10874,14 +10405,14 @@ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths)
10874
10405
  continue;
10875
10406
  }
10876
10407
  try {
10877
- for (var stageKeys_1 = (e_19 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
10408
+ for (var stageKeys_1 = (e_21 = void 0, __values(stageKeys)), stageKeys_1_1 = stageKeys_1.next(); !stageKeys_1_1.done; stageKeys_1_1 = stageKeys_1.next()) {
10878
10409
  var stageKey = stageKeys_1_1.value;
10879
10410
  var payload = stage[stageKey];
10880
10411
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
10881
10412
  continue;
10882
10413
  }
10883
10414
  try {
10884
- for (var groupFields_1 = (e_20 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
10415
+ for (var groupFields_1 = (e_22 = void 0, __values(groupFields)), groupFields_1_1 = groupFields_1.next(); !groupFields_1_1.done; groupFields_1_1 = groupFields_1.next()) {
10885
10416
  var groupField = groupFields_1_1.value;
10886
10417
  if (!Object.prototype.hasOwnProperty.call(payload, groupField)) {
10887
10418
  continue;
@@ -10891,21 +10422,21 @@ function isGroupFieldDerivedFromDateExpression(pipeline, groupIndex, groupPaths)
10891
10422
  }
10892
10423
  }
10893
10424
  }
10894
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
10425
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
10895
10426
  finally {
10896
10427
  try {
10897
10428
  if (groupFields_1_1 && !groupFields_1_1.done && (_b = groupFields_1.return)) _b.call(groupFields_1);
10898
10429
  }
10899
- finally { if (e_20) throw e_20.error; }
10430
+ finally { if (e_22) throw e_22.error; }
10900
10431
  }
10901
10432
  }
10902
10433
  }
10903
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
10434
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
10904
10435
  finally {
10905
10436
  try {
10906
10437
  if (stageKeys_1_1 && !stageKeys_1_1.done && (_a = stageKeys_1.return)) _a.call(stageKeys_1);
10907
10438
  }
10908
- finally { if (e_19) throw e_19.error; }
10439
+ finally { if (e_21) throw e_21.error; }
10909
10440
  }
10910
10441
  }
10911
10442
  return false;
@@ -11012,7 +10543,7 @@ function isRegexMatchCondition(value) {
11012
10543
  return false;
11013
10544
  }
11014
10545
  function findRegexMatchInMatchObject(match, prefix) {
11015
- var e_21, _a, e_22, _b;
10546
+ var e_23, _a, e_24, _b;
11016
10547
  if (prefix === void 0) { prefix = ''; }
11017
10548
  if (Array.isArray(match)) {
11018
10549
  try {
@@ -11024,12 +10555,12 @@ function findRegexMatchInMatchObject(match, prefix) {
11024
10555
  }
11025
10556
  }
11026
10557
  }
11027
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
10558
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
11028
10559
  finally {
11029
10560
  try {
11030
10561
  if (match_1_1 && !match_1_1.done && (_a = match_1.return)) _a.call(match_1);
11031
10562
  }
11032
- finally { if (e_21) throw e_21.error; }
10563
+ finally { if (e_23) throw e_23.error; }
11033
10564
  }
11034
10565
  return null;
11035
10566
  }
@@ -11060,12 +10591,12 @@ function findRegexMatchInMatchObject(match, prefix) {
11060
10591
  }
11061
10592
  }
11062
10593
  }
11063
- catch (e_22_1) { e_22 = { error: e_22_1 }; }
10594
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
11064
10595
  finally {
11065
10596
  try {
11066
10597
  if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2);
11067
10598
  }
11068
- finally { if (e_22) throw e_22.error; }
10599
+ finally { if (e_24) throw e_24.error; }
11069
10600
  }
11070
10601
  return null;
11071
10602
  }
@@ -11289,7 +10820,7 @@ function collectMatchFieldsByCondition(match, predicate, prefix) {
11289
10820
  return results;
11290
10821
  }
11291
10822
  function findMatchConditionForField(match, targetField, prefix) {
11292
- var e_23, _a, e_24, _b;
10823
+ var e_25, _a, e_26, _b;
11293
10824
  if (prefix === void 0) { prefix = ''; }
11294
10825
  if (!match || typeof match !== 'object') {
11295
10826
  return undefined;
@@ -11304,12 +10835,12 @@ function findMatchConditionForField(match, targetField, prefix) {
11304
10835
  }
11305
10836
  }
11306
10837
  }
11307
- catch (e_23_1) { e_23 = { error: e_23_1 }; }
10838
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
11308
10839
  finally {
11309
10840
  try {
11310
10841
  if (match_2_1 && !match_2_1.done && (_a = match_2.return)) _a.call(match_2);
11311
10842
  }
11312
- finally { if (e_23) throw e_23.error; }
10843
+ finally { if (e_25) throw e_25.error; }
11313
10844
  }
11314
10845
  return undefined;
11315
10846
  }
@@ -11336,12 +10867,12 @@ function findMatchConditionForField(match, targetField, prefix) {
11336
10867
  }
11337
10868
  }
11338
10869
  }
11339
- catch (e_24_1) { e_24 = { error: e_24_1 }; }
10870
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
11340
10871
  finally {
11341
10872
  try {
11342
10873
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
11343
10874
  }
11344
- finally { if (e_24) throw e_24.error; }
10875
+ finally { if (e_26) throw e_26.error; }
11345
10876
  }
11346
10877
  return undefined;
11347
10878
  }
@@ -11445,7 +10976,7 @@ function detectIdLikeValue(value) {
11445
10976
  return false;
11446
10977
  }
11447
10978
  function detectChemicalIdFromProbe(probeDocs, fields) {
11448
- var e_25, _a, e_26, _b;
10979
+ var e_27, _a, e_28, _b;
11449
10980
  if (!Array.isArray(probeDocs) || !probeDocs.length) {
11450
10981
  return false;
11451
10982
  }
@@ -11457,7 +10988,7 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
11457
10988
  for (var probeDocs_1 = __values(probeDocs), probeDocs_1_1 = probeDocs_1.next(); !probeDocs_1_1.done; probeDocs_1_1 = probeDocs_1.next()) {
11458
10989
  var doc = probeDocs_1_1.value;
11459
10990
  try {
11460
- for (var targets_1 = (e_26 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
10991
+ for (var targets_1 = (e_28 = void 0, __values(targets)), targets_1_1 = targets_1.next(); !targets_1_1.done; targets_1_1 = targets_1.next()) {
11461
10992
  var field = targets_1_1.value;
11462
10993
  var value = getValueAtPath(doc, field);
11463
10994
  if (Array.isArray(value)) {
@@ -11470,21 +11001,21 @@ function detectChemicalIdFromProbe(probeDocs, fields) {
11470
11001
  }
11471
11002
  }
11472
11003
  }
11473
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
11004
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
11474
11005
  finally {
11475
11006
  try {
11476
11007
  if (targets_1_1 && !targets_1_1.done && (_b = targets_1.return)) _b.call(targets_1);
11477
11008
  }
11478
- finally { if (e_26) throw e_26.error; }
11009
+ finally { if (e_28) throw e_28.error; }
11479
11010
  }
11480
11011
  }
11481
11012
  }
11482
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
11013
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
11483
11014
  finally {
11484
11015
  try {
11485
11016
  if (probeDocs_1_1 && !probeDocs_1_1.done && (_a = probeDocs_1.return)) _a.call(probeDocs_1);
11486
11017
  }
11487
- finally { if (e_25) throw e_25.error; }
11018
+ finally { if (e_27) throw e_27.error; }
11488
11019
  }
11489
11020
  return false;
11490
11021
  }
@@ -11705,8 +11236,8 @@ function buildChemicalIdFieldCandidates(field) {
11705
11236
  }
11706
11237
  function applyChemicalNameLookupFallbackToQuery(params) {
11707
11238
  return __awaiter(this, void 0, void 0, function () {
11708
- var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, chemicalFields, targetField, condition, regex, sampleDocs, collectionNames, candidates, _loop_7, candidates_2, candidates_2_1, candidate, state_5, e_27_1;
11709
- var e_27, _a;
11239
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, chemicalFields, targetField, condition, regex, sampleDocs, collectionNames, candidates, _loop_7, candidates_2, candidates_2_1, candidate, state_5, e_29_1;
11240
+ var e_29, _a;
11710
11241
  var _b;
11711
11242
  return __generator(this, function (_c) {
11712
11243
  switch (_c.label) {
@@ -11819,14 +11350,14 @@ function applyChemicalNameLookupFallbackToQuery(params) {
11819
11350
  return [3 /*break*/, 3];
11820
11351
  case 6: return [3 /*break*/, 9];
11821
11352
  case 7:
11822
- e_27_1 = _c.sent();
11823
- e_27 = { error: e_27_1 };
11353
+ e_29_1 = _c.sent();
11354
+ e_29 = { error: e_29_1 };
11824
11355
  return [3 /*break*/, 9];
11825
11356
  case 8:
11826
11357
  try {
11827
11358
  if (candidates_2_1 && !candidates_2_1.done && (_a = candidates_2.return)) _a.call(candidates_2);
11828
11359
  }
11829
- finally { if (e_27) throw e_27.error; }
11360
+ finally { if (e_29) throw e_29.error; }
11830
11361
  return [7 /*endfinally*/];
11831
11362
  case 9: return [2 /*return*/, null];
11832
11363
  }
@@ -11920,8 +11451,8 @@ function lookupIdsForNameMatch(params) {
11920
11451
  }
11921
11452
  function applyIdLookupFallbackToQuery(params) {
11922
11453
  return __awaiter(this, void 0, void 0, function () {
11923
- var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, conditions, collectionNames, _a, conditions_1, conditions_1_1, condition, regex, baseToken, targetFieldType, nextValue, localNameField, candidates, candidates_3, candidates_3_1, candidate, candidateHasClientScope, _b, candidateProbe, lookup, targetFieldType, normalizedIds, idsForQuery, e_28_1, e_29_1;
11924
- var e_29, _c, e_28, _d;
11454
+ var query, db, dbName, idClient, idCustomer, isSuperAdmin, probeDocs, conditions, collectionNames, _a, conditions_1, conditions_1_1, condition, regex, baseToken, targetFieldType, nextValue, localNameField, candidates, candidates_3, candidates_3_1, candidate, candidateHasClientScope, _b, candidateProbe, lookup, targetFieldType, normalizedIds, idsForQuery, e_30_1, e_31_1;
11455
+ var e_31, _c, e_30, _d;
11925
11456
  var _e;
11926
11457
  return __generator(this, function (_f) {
11927
11458
  switch (_f.label) {
@@ -11991,7 +11522,7 @@ function applyIdLookupFallbackToQuery(params) {
11991
11522
  _f.label = 5;
11992
11523
  case 5:
11993
11524
  _f.trys.push([5, 14, 15, 16]);
11994
- candidates_3 = (e_28 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
11525
+ candidates_3 = (e_30 = void 0, __values(candidates)), candidates_3_1 = candidates_3.next();
11995
11526
  _f.label = 6;
11996
11527
  case 6:
11997
11528
  if (!!candidates_3_1.done) return [3 /*break*/, 13];
@@ -12058,28 +11589,28 @@ function applyIdLookupFallbackToQuery(params) {
12058
11589
  return [3 /*break*/, 6];
12059
11590
  case 13: return [3 /*break*/, 16];
12060
11591
  case 14:
12061
- e_28_1 = _f.sent();
12062
- e_28 = { error: e_28_1 };
11592
+ e_30_1 = _f.sent();
11593
+ e_30 = { error: e_30_1 };
12063
11594
  return [3 /*break*/, 16];
12064
11595
  case 15:
12065
11596
  try {
12066
11597
  if (candidates_3_1 && !candidates_3_1.done && (_d = candidates_3.return)) _d.call(candidates_3);
12067
11598
  }
12068
- finally { if (e_28) throw e_28.error; }
11599
+ finally { if (e_30) throw e_30.error; }
12069
11600
  return [7 /*endfinally*/];
12070
11601
  case 16:
12071
11602
  conditions_1_1 = conditions_1.next();
12072
11603
  return [3 /*break*/, 4];
12073
11604
  case 17: return [3 /*break*/, 20];
12074
11605
  case 18:
12075
- e_29_1 = _f.sent();
12076
- e_29 = { error: e_29_1 };
11606
+ e_31_1 = _f.sent();
11607
+ e_31 = { error: e_31_1 };
12077
11608
  return [3 /*break*/, 20];
12078
11609
  case 19:
12079
11610
  try {
12080
11611
  if (conditions_1_1 && !conditions_1_1.done && (_c = conditions_1.return)) _c.call(conditions_1);
12081
11612
  }
12082
- finally { if (e_29) throw e_29.error; }
11613
+ finally { if (e_31) throw e_31.error; }
12083
11614
  return [7 /*endfinally*/];
12084
11615
  case 20: return [2 /*return*/, null];
12085
11616
  }
@@ -12670,29 +12201,12 @@ function resolveAssistantDefaultCollectionHints(message) {
12670
12201
  hints.push(value);
12671
12202
  }
12672
12203
  };
12673
- if (/\bwork[\s-]*orders?\b/.test(text) || /\bwo\b/.test(text) || /\bdeliver(?:y|ies)\b/.test(text)) {
12674
- push('work-order-dynamics');
12675
- }
12676
- if (/\bblend(?:s|ing)?\b/.test(text) || /\bblend[\s-]*tickets?\b/.test(text)) {
12677
- push('chemical-blends');
12678
- }
12679
- if (/\binvoice|revenue|billing|sales\b/.test(text)) {
12680
- push('invoices');
12681
- }
12682
- if (/\bjobs?\b/.test(text)) {
12683
- push('jobs');
12684
- push('work-order-dynamics');
12685
- }
12686
- if (/\bcustomers?\b/.test(text)) {
12687
- push('customers');
12688
- }
12689
- if (/\bclients?\b/.test(text)) {
12690
- push('customers');
12691
- push('clients');
12692
- }
12693
12204
  if (/\bsupport[\s-]*tickets?\b/.test(text) || /\btickets?\b/.test(text)) {
12694
12205
  push('support-tickets');
12695
12206
  }
12207
+ if (/\busers?\b/.test(text)) {
12208
+ push('users');
12209
+ }
12696
12210
  return hints;
12697
12211
  }
12698
12212
  function buildCollectionRankingDebugFromTokens(tokens, collectionNames, max) {
@@ -12985,111 +12499,18 @@ function resolveAssistantCollectionName(db, dbName, requested) {
12985
12499
  });
12986
12500
  }
12987
12501
  var AI_ASSISTANT_BRIDGE_COLLECTION_ALIASES = {
12988
- workorder: 'work-order-dynamics',
12989
- workorders: 'work-order-dynamics',
12990
- workorderdynamic: 'work-order-dynamics',
12991
- workorderdynamics: 'work-order-dynamics',
12992
- workordersdynamic: 'work-order-dynamics',
12993
- workordersdynamics: 'work-order-dynamics',
12994
- trucktreatingdelivery: 'jobs',
12995
- trucktreatingdeliveries: 'jobs',
12996
- trucktreatingjob: 'jobs',
12997
- trucktreatingjobs: 'jobs',
12998
- trucktreatingroute: 'jobs',
12999
- trucktreatingroutes: 'jobs',
13000
- trucktreatingrouteevent: 'jobs',
13001
- trucktreatingrouteevents: 'jobs',
13002
- delivery: 'work-order-dynamics',
13003
- deliveries: 'work-order-dynamics',
13004
- blendticket: 'chemical-blends',
13005
- blendtickets: 'chemical-blends',
13006
- reportchemicalblends: 'chemical-blends',
13007
- blend: 'chemical-blends',
13008
- blends: 'chemical-blends',
12502
+ user: 'users',
13009
12503
  supportticket: 'support-tickets',
13010
12504
  supporttickets: 'support-tickets',
13011
12505
  ticket: 'support-tickets',
13012
- tickets: 'support-tickets',
13013
- timeentry: 'time_entries',
13014
- timeentries: 'time_entries',
13015
- timeentrylog: 'time_entries',
13016
- timeentrylogs: 'time_entries',
13017
- timeentryrecord: 'time_entries',
13018
- timeentryrecords: 'time_entries',
13019
- timesheet: 'timesheets',
13020
- timesheets: 'timesheets',
13021
- payrollentry: 'payroll_entries',
13022
- payrollentries: 'payroll_entries',
13023
- invoice: 'invoices',
13024
- client: 'customers',
13025
- clients: 'customers',
13026
- customer: 'customers'
12506
+ tickets: 'support-tickets'
13027
12507
  };
13028
- var AI_ASSISTANT_DIRECT_COLLECTION_FALLBACK_ALLOWLIST = new Set([
13029
- 'work-order-dynamics',
13030
- 'invoices',
13031
- 'chemical-blends',
13032
- 'report-chemical-blends',
13033
- 'jobs',
13034
- 'production-deliveries',
13035
- 'truck-treating-deliveries',
13036
- 'duplicate-deliveries',
13037
- 'third-party-drivers',
13038
- 'customers',
13039
- 'support-tickets',
13040
- 'time_entries',
13041
- 'time-entries',
13042
- 'timeentries',
13043
- 'timesheets',
13044
- 'timesheet-entries',
13045
- 'employee-time',
13046
- 'employee_time',
13047
- 'employee-time-entries',
13048
- 'employee_time_entries',
13049
- 'payroll_entries',
13050
- 'payroll-entries',
13051
- 'billing_entries',
13052
- 'billing-entries'
13053
- ]);
13054
- var AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS = [
13055
- 'work-order-dynamics',
13056
- 'maintenance-orders',
13057
- 'orders',
13058
- 'repair-orders',
13059
- 'reoccurring-orders'
13060
- ];
13061
- var AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS = [
13062
- 'customers',
13063
- 'clients',
13064
- 'api-customers',
13065
- 'ibp-customers',
13066
- 'qb-customers'
13067
- ];
12508
+ var AI_ASSISTANT_DIRECT_COLLECTION_FALLBACK_ALLOWLIST = new Set([]);
13068
12509
  var AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS = [
13069
12510
  'support-tickets',
13070
12511
  'supporttickets',
13071
12512
  'support-ticket'
13072
12513
  ];
13073
- var AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS = [
13074
- 'invoices',
13075
- 'billings',
13076
- 'sales-taxes'
13077
- ];
13078
- var AI_ASSISTANT_TIME_COLLECTION_FALLBACKS = [
13079
- 'time_entries',
13080
- 'time-entries',
13081
- 'timeentries',
13082
- 'timesheets',
13083
- 'timesheet-entries',
13084
- 'employee-time',
13085
- 'employee_time',
13086
- 'employee-time-entries',
13087
- 'employee_time_entries',
13088
- 'payroll_entries',
13089
- 'payroll-entries',
13090
- 'billing_entries',
13091
- 'billing-entries'
13092
- ];
13093
12514
  function normalizeAssistantCollectionFamilyName(value) {
13094
12515
  var normalized = normalizeOptionalString(value).toLowerCase();
13095
12516
  if (!normalized) {
@@ -13142,81 +12563,303 @@ function resolveAssistantCrossCollectionFallbackCandidates(collection) {
13142
12563
  if (!normalized) {
13143
12564
  return [];
13144
12565
  }
13145
- var candidates = [];
13146
- if (AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('order')) {
13147
- candidates = AI_ASSISTANT_ORDER_COLLECTION_FALLBACKS;
12566
+ var candidates = new Set();
12567
+ var addCandidate = function (value) {
12568
+ var candidate = normalizeOptionalString(value);
12569
+ if (!candidate) {
12570
+ return;
12571
+ }
12572
+ candidates.add(candidate);
12573
+ };
12574
+ var alias = resolveAssistantBridgeCollectionAlias(normalized)
12575
+ || resolveAssistantBridgeCollectionAlias(normalizeCollectionKey(normalized));
12576
+ addCandidate(alias);
12577
+ if (AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS.includes(normalized)
12578
+ || normalized.includes('ticket')
12579
+ || normalized.includes('support')) {
12580
+ AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS.forEach(addCandidate);
12581
+ }
12582
+ return Array.from(candidates);
12583
+ }
12584
+ function resolveAssistantAvailableCrossCollectionFallbacksFromNames(collection, triedCollections, collectionNames) {
12585
+ var candidates = resolveAssistantCrossCollectionFallbackCandidates(collection);
12586
+ var namesByFamily = new Map();
12587
+ (collectionNames || []).forEach(function (name) {
12588
+ var family = normalizeAssistantCollectionFamilyName(name);
12589
+ if (!family) {
12590
+ return;
12591
+ }
12592
+ var existing = namesByFamily.get(family) || [];
12593
+ existing.push(name);
12594
+ namesByFamily.set(family, existing);
12595
+ });
12596
+ var currentFamily = normalizeAssistantCollectionFamilyName(collection);
12597
+ var available = [];
12598
+ var pushPreferredCandidate = function (candidate) {
12599
+ var family = normalizeAssistantCollectionFamilyName(candidate);
12600
+ if (!family || family === currentFamily || hasAssistantCollectionBeenTried(triedCollections, candidate)) {
12601
+ return;
12602
+ }
12603
+ var familyNames = namesByFamily.get(family) || [];
12604
+ var preferred = familyNames.find(function (name) { return !name.startsWith('report-') && !isVersionCollectionName(name); })
12605
+ || familyNames.find(function (name) { return !name.startsWith('report-'); })
12606
+ || familyNames[0]
12607
+ || '';
12608
+ if (!preferred && isAssistantDirectCollectionFallbackAllowed(candidate)) {
12609
+ preferred = candidate;
12610
+ }
12611
+ if (!preferred || hasAssistantCollectionBeenTried(triedCollections, preferred) || available.includes(preferred)) {
12612
+ return;
12613
+ }
12614
+ available.push(preferred);
12615
+ };
12616
+ candidates.forEach(pushPreferredCandidate);
12617
+ var collectionTokenSeed = normalizeAssistantCollectionFamilyName(collection) || normalizeOptionalString(collection);
12618
+ var requestedTokens = tokenizeCollectionText(collectionTokenSeed);
12619
+ if (requestedTokens.length) {
12620
+ (collectionNames || [])
12621
+ .map(function (name) { return ({ name: name, score: scoreCollectionMatch(requestedTokens, name) }); })
12622
+ .filter(function (entry) { return entry.score >= 10; })
12623
+ .sort(function (a, b) { return b.score - a.score; })
12624
+ .slice(0, 8)
12625
+ .forEach(function (entry) { return pushPreferredCandidate(entry.name); });
13148
12626
  }
13149
- else if (AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('customer') || normalized.includes('client')) {
13150
- candidates = AI_ASSISTANT_CUSTOMER_COLLECTION_FALLBACKS;
12627
+ return available;
12628
+ }
12629
+ function resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections) {
12630
+ return __awaiter(this, void 0, void 0, function () {
12631
+ var collectionNames;
12632
+ return __generator(this, function (_a) {
12633
+ switch (_a.label) {
12634
+ case 0: return [4 /*yield*/, listAssistantCollections(db, dbName)];
12635
+ case 1:
12636
+ collectionNames = _a.sent();
12637
+ return [2 /*return*/, resolveAssistantAvailableCrossCollectionFallbacksFromNames(collection, triedCollections, collectionNames)];
12638
+ }
12639
+ });
12640
+ });
12641
+ }
12642
+ function collectAggregateReferencedFieldPaths(pipeline) {
12643
+ var fields = new Set();
12644
+ (pipeline || []).forEach(function (stage) {
12645
+ var _a;
12646
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
12647
+ return;
12648
+ }
12649
+ if (stage.$match && typeof stage.$match === 'object') {
12650
+ extractQueryFieldPaths(stage.$match).forEach(function (field) { return fields.add(field); });
12651
+ }
12652
+ if (((_a = stage.$geoNear) === null || _a === void 0 ? void 0 : _a.query) && typeof stage.$geoNear.query === 'object') {
12653
+ extractQueryFieldPaths(stage.$geoNear.query).forEach(function (field) { return fields.add(field); });
12654
+ }
12655
+ if (stage.$group && typeof stage.$group === 'object') {
12656
+ extractExpressionFieldPaths(stage.$group).forEach(function (field) { return fields.add(field); });
12657
+ }
12658
+ if (stage.$project && typeof stage.$project === 'object') {
12659
+ extractExpressionFieldPaths(stage.$project).forEach(function (field) { return fields.add(field); });
12660
+ }
12661
+ if (stage.$addFields && typeof stage.$addFields === 'object') {
12662
+ extractExpressionFieldPaths(stage.$addFields).forEach(function (field) { return fields.add(field); });
12663
+ }
12664
+ if (stage.$set && typeof stage.$set === 'object') {
12665
+ extractExpressionFieldPaths(stage.$set).forEach(function (field) { return fields.add(field); });
12666
+ }
12667
+ if (stage.$sort && typeof stage.$sort === 'object') {
12668
+ Object.keys(stage.$sort)
12669
+ .filter(function (key) { return !key.startsWith('$'); })
12670
+ .forEach(function (field) { return fields.add(field); });
12671
+ }
12672
+ var unwind = stage.$unwind;
12673
+ if (typeof unwind === 'string' && unwind.startsWith('$')) {
12674
+ fields.add(unwind.slice(1));
12675
+ }
12676
+ if (unwind && typeof unwind === 'object' && typeof unwind.path === 'string' && unwind.path.startsWith('$')) {
12677
+ fields.add(unwind.path.slice(1));
12678
+ }
12679
+ });
12680
+ return Array.from(fields).filter(Boolean);
12681
+ }
12682
+ function resolveAggregateNestedPrefixes(pipeline) {
12683
+ var prefixCounts = new Map();
12684
+ var fields = collectAggregateReferencedFieldPaths(pipeline);
12685
+ fields.forEach(function (field) {
12686
+ var normalized = normalizeOptionalString(field);
12687
+ if (!normalized || !normalized.includes('.')) {
12688
+ return;
12689
+ }
12690
+ var prefix = normalized.split('.')[0];
12691
+ if (!prefix || prefix.startsWith('$') || prefix === '_id') {
12692
+ return;
12693
+ }
12694
+ prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);
12695
+ });
12696
+ return Array.from(prefixCounts.entries())
12697
+ .filter(function (entry) { return entry[1] >= 2; })
12698
+ .sort(function (a, b) { return b[1] - a[1]; })
12699
+ .map(function (entry) { return entry[0]; });
12700
+ }
12701
+ function rewriteAggregatePipelineForNestedPrefix(pipeline, prefix) {
12702
+ var normalizedPrefix = normalizeOptionalString(prefix);
12703
+ if (!normalizedPrefix || !Array.isArray(pipeline) || !pipeline.length) {
12704
+ return { pipeline: pipeline, changed: false, rewrittenFields: [] };
13151
12705
  }
13152
- else if (AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('ticket') || normalized.includes('support')) {
13153
- candidates = AI_ASSISTANT_SUPPORT_COLLECTION_FALLBACKS;
12706
+ var withoutPrefixUnwind = pipeline.filter(function (stage) {
12707
+ if (!stage || typeof stage !== 'object' || !stage.$unwind) {
12708
+ return true;
12709
+ }
12710
+ if (typeof stage.$unwind === 'string') {
12711
+ return stage.$unwind !== "$".concat(normalizedPrefix);
12712
+ }
12713
+ if (stage.$unwind && typeof stage.$unwind === 'object') {
12714
+ return stage.$unwind.path !== "$".concat(normalizedPrefix);
12715
+ }
12716
+ return true;
12717
+ });
12718
+ var rewriteFields = collectAggregateReferencedFieldPaths(withoutPrefixUnwind)
12719
+ .filter(function (field) { return field.startsWith("".concat(normalizedPrefix, ".")); })
12720
+ .sort(function (a, b) { return b.length - a.length; });
12721
+ if (!rewriteFields.length) {
12722
+ return {
12723
+ pipeline: withoutPrefixUnwind,
12724
+ changed: didAssistantValueChange(pipeline, withoutPrefixUnwind),
12725
+ rewrittenFields: []
12726
+ };
13154
12727
  }
13155
- else if (AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS.includes(normalized) || normalized.includes('invoice') || normalized.includes('billing')) {
13156
- candidates = AI_ASSISTANT_INVOICE_COLLECTION_FALLBACKS;
12728
+ var dedupedFields = Array.from(new Set(rewriteFields));
12729
+ var rewritten = withoutPrefixUnwind;
12730
+ dedupedFields.forEach(function (field) {
12731
+ var targetField = field.slice(normalizedPrefix.length + 1);
12732
+ rewritten = replaceFieldPathDeep(rewritten, field, targetField);
12733
+ });
12734
+ return {
12735
+ pipeline: rewritten,
12736
+ changed: didAssistantValueChange(pipeline, rewritten),
12737
+ rewrittenFields: dedupedFields
12738
+ };
12739
+ }
12740
+ function resolveAssistantPreferredCollectionForFamily(candidate, collectionNames) {
12741
+ var normalizedCandidate = normalizeOptionalString(candidate);
12742
+ if (!normalizedCandidate) {
12743
+ return null;
13157
12744
  }
13158
- else if (AI_ASSISTANT_TIME_COLLECTION_FALLBACKS.includes(normalized)
13159
- || normalized.includes('time')
13160
- || normalized.includes('sheet')
13161
- || normalized.includes('hour')
13162
- || normalized.includes('payroll')) {
13163
- candidates = AI_ASSISTANT_TIME_COLLECTION_FALLBACKS;
12745
+ var family = normalizeAssistantCollectionFamilyName(normalizedCandidate);
12746
+ if (!family) {
12747
+ return null;
13164
12748
  }
13165
- var deduped = [];
13166
- candidates.forEach(function (candidate) {
13167
- if (!candidate || deduped.includes(candidate)) {
13168
- return;
13169
- }
13170
- deduped.push(candidate);
13171
- });
13172
- return deduped;
12749
+ var familyNames = (collectionNames || []).filter(function (name) { return normalizeAssistantCollectionFamilyName(name) === family; });
12750
+ var preferred = familyNames.find(function (name) { return !name.startsWith('report-') && !isVersionCollectionName(name); })
12751
+ || familyNames.find(function (name) { return !isVersionCollectionName(name); })
12752
+ || familyNames[0];
12753
+ return preferred || null;
13173
12754
  }
13174
- function resolveAssistantAvailableCrossCollectionFallbacksFromNames(collection, triedCollections, collectionNames) {
13175
- var candidates = resolveAssistantCrossCollectionFallbackCandidates(collection);
13176
- if (!candidates.length) {
12755
+ function resolveAssistantNestedPrefixCollectionCandidates(params) {
12756
+ var normalizedPrefix = normalizeOptionalString(params.prefix);
12757
+ if (!normalizedPrefix) {
13177
12758
  return [];
13178
12759
  }
13179
- var namesByFamily = new Map();
13180
- (collectionNames || []).forEach(function (name) {
13181
- var family = normalizeAssistantCollectionFamilyName(name);
13182
- if (!family) {
12760
+ var currentFamily = normalizeAssistantCollectionFamilyName(params.currentCollection);
12761
+ var candidates = [];
12762
+ var push = function (candidate) {
12763
+ var preferred = resolveAssistantPreferredCollectionForFamily(candidate, params.collectionNames);
12764
+ if (!preferred) {
13183
12765
  return;
13184
12766
  }
13185
- var existing = namesByFamily.get(family) || [];
13186
- existing.push(name);
13187
- namesByFamily.set(family, existing);
13188
- });
13189
- var currentFamily = normalizeAssistantCollectionFamilyName(collection);
13190
- var available = [];
13191
- candidates.forEach(function (candidate) {
13192
- var family = normalizeAssistantCollectionFamilyName(candidate);
13193
- if (!family || family === currentFamily || hasAssistantCollectionBeenTried(triedCollections, candidate)) {
12767
+ var preferredFamily = normalizeAssistantCollectionFamilyName(preferred);
12768
+ if (!preferredFamily || preferredFamily === currentFamily) {
13194
12769
  return;
13195
12770
  }
13196
- var familyNames = namesByFamily.get(family) || [];
13197
- var preferred = familyNames.find(function (name) { return !name.startsWith('report-') && !isVersionCollectionName(name); })
13198
- || familyNames.find(function (name) { return !name.startsWith('report-'); })
13199
- || familyNames[0]
13200
- || '';
13201
- if (!preferred && isAssistantDirectCollectionFallbackAllowed(candidate)) {
13202
- preferred = candidate;
13203
- }
13204
- if (!preferred || hasAssistantCollectionBeenTried(triedCollections, preferred) || available.includes(preferred)) {
12771
+ if (hasAssistantCollectionBeenTried(params.triedCollections, preferred) || candidates.includes(preferred)) {
13205
12772
  return;
13206
12773
  }
13207
- available.push(preferred);
13208
- });
13209
- return available;
12774
+ candidates.push(preferred);
12775
+ };
12776
+ var alias = resolveAssistantBridgeCollectionAlias(normalizedPrefix);
12777
+ if (alias) {
12778
+ push(alias);
12779
+ }
12780
+ push(normalizedPrefix);
12781
+ resolveAssistantAvailableCrossCollectionFallbacksFromNames(normalizedPrefix, params.triedCollections, params.collectionNames).forEach(push);
12782
+ var tokenizedPrefix = tokenizeCollectionText(normalizedPrefix);
12783
+ params.collectionNames
12784
+ .map(function (name) { return ({ name: name, score: scoreCollectionMatch(tokenizedPrefix, name) }); })
12785
+ .filter(function (entry) { return entry.score > 0; })
12786
+ .sort(function (a, b) { return b.score - a.score; })
12787
+ .slice(0, 8)
12788
+ .forEach(function (entry) { return push(entry.name); });
12789
+ return candidates;
13210
12790
  }
13211
- function resolveAssistantAvailableCrossCollectionFallbacks(db, dbName, collection, triedCollections) {
12791
+ function resolveAssistantNestedAggregateFallbacks(params) {
13212
12792
  return __awaiter(this, void 0, void 0, function () {
13213
- var collectionNames;
13214
- return __generator(this, function (_a) {
13215
- switch (_a.label) {
13216
- case 0: return [4 /*yield*/, listAssistantCollections(db, dbName)];
12793
+ var prefixes, collectionNames, fallbacks, seen, prefixes_1, prefixes_1_1, prefix, rewrite, candidates, candidates_4, candidates_4_1, candidate, normalizedPipeline, key;
12794
+ var e_32, _a, e_33, _b;
12795
+ return __generator(this, function (_c) {
12796
+ switch (_c.label) {
12797
+ case 0:
12798
+ prefixes = resolveAggregateNestedPrefixes(params.pipeline || []);
12799
+ if (!prefixes.length) {
12800
+ return [2 /*return*/, []];
12801
+ }
12802
+ return [4 /*yield*/, listAssistantCollections(params.db, params.dbName)];
13217
12803
  case 1:
13218
- collectionNames = _a.sent();
13219
- return [2 /*return*/, resolveAssistantAvailableCrossCollectionFallbacksFromNames(collection, triedCollections, collectionNames)];
12804
+ collectionNames = _c.sent();
12805
+ if (!collectionNames.length) {
12806
+ return [2 /*return*/, []];
12807
+ }
12808
+ fallbacks = [];
12809
+ seen = new Set();
12810
+ try {
12811
+ for (prefixes_1 = __values(prefixes), prefixes_1_1 = prefixes_1.next(); !prefixes_1_1.done; prefixes_1_1 = prefixes_1.next()) {
12812
+ prefix = prefixes_1_1.value;
12813
+ rewrite = rewriteAggregatePipelineForNestedPrefix(params.pipeline || [], prefix);
12814
+ if (!rewrite.changed || !rewrite.rewrittenFields.length) {
12815
+ continue;
12816
+ }
12817
+ candidates = resolveAssistantNestedPrefixCollectionCandidates({
12818
+ prefix: prefix,
12819
+ currentCollection: params.currentCollection,
12820
+ collectionNames: collectionNames,
12821
+ triedCollections: params.triedCollections
12822
+ });
12823
+ try {
12824
+ for (candidates_4 = (e_33 = void 0, __values(candidates)), candidates_4_1 = candidates_4.next(); !candidates_4_1.done; candidates_4_1 = candidates_4.next()) {
12825
+ candidate = candidates_4_1.value;
12826
+ normalizedPipeline = normalizeAssistantAggregatePipeline(rewrite.pipeline, candidate);
12827
+ if (!normalizedPipeline.length || containsForbiddenMongoOperators(normalizedPipeline)) {
12828
+ continue;
12829
+ }
12830
+ key = "".concat(prefix, "|").concat(candidate);
12831
+ if (seen.has(key)) {
12832
+ continue;
12833
+ }
12834
+ seen.add(key);
12835
+ fallbacks.push({
12836
+ collection: candidate,
12837
+ prefix: prefix,
12838
+ pipeline: normalizedPipeline,
12839
+ rewrittenFields: rewrite.rewrittenFields
12840
+ });
12841
+ if (fallbacks.length >= 10) {
12842
+ return [2 /*return*/, fallbacks];
12843
+ }
12844
+ }
12845
+ }
12846
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
12847
+ finally {
12848
+ try {
12849
+ if (candidates_4_1 && !candidates_4_1.done && (_b = candidates_4.return)) _b.call(candidates_4);
12850
+ }
12851
+ finally { if (e_33) throw e_33.error; }
12852
+ }
12853
+ }
12854
+ }
12855
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
12856
+ finally {
12857
+ try {
12858
+ if (prefixes_1_1 && !prefixes_1_1.done && (_a = prefixes_1.return)) _a.call(prefixes_1);
12859
+ }
12860
+ finally { if (e_32) throw e_32.error; }
12861
+ }
12862
+ return [2 /*return*/, fallbacks];
13220
12863
  }
13221
12864
  });
13222
12865
  });
@@ -13260,8 +12903,8 @@ function doesAssistantCollectionExistInDb(db, collection) {
13260
12903
  }
13261
12904
  function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
13262
12905
  return __awaiter(this, arguments, void 0, function (collection, db, dbName) {
13263
- var normalized, alias, manager, hasManager, candidates, pushCandidate, base, reportCandidate, candidates_4, candidates_4_1, candidate, model, resolved, resolvedName, resolvedModel, _a, candidates_5, candidates_5_1, candidate, e_30_1, candidates_6, candidates_6_1, candidate;
13264
- var e_31, _b, e_30, _c, e_32, _d;
12906
+ var normalized, alias, manager, hasManager, candidates, pushCandidate, base, reportCandidate, candidates_5, candidates_5_1, candidate, model, resolved, resolvedName, resolvedModel, _a, candidates_6, candidates_6_1, candidate, e_34_1, candidates_7, candidates_7_1, candidate;
12907
+ var e_35, _b, e_34, _c, e_36, _d;
13265
12908
  var _e;
13266
12909
  if (dbName === void 0) { dbName = ''; }
13267
12910
  return __generator(this, function (_f) {
@@ -13296,20 +12939,20 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
13296
12939
  }
13297
12940
  if (hasManager) {
13298
12941
  try {
13299
- for (candidates_4 = __values(candidates), candidates_4_1 = candidates_4.next(); !candidates_4_1.done; candidates_4_1 = candidates_4.next()) {
13300
- candidate = candidates_4_1.value;
12942
+ for (candidates_5 = __values(candidates), candidates_5_1 = candidates_5.next(); !candidates_5_1.done; candidates_5_1 = candidates_5.next()) {
12943
+ candidate = candidates_5_1.value;
13301
12944
  model = manager.collection(candidate);
13302
12945
  if (model === null || model === void 0 ? void 0 : model.useRB) {
13303
12946
  return [2 /*return*/, __assign({ collection: candidate }, (candidate !== normalized ? { fallbackFrom: normalized } : {}))];
13304
12947
  }
13305
12948
  }
13306
12949
  }
13307
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
12950
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
13308
12951
  finally {
13309
12952
  try {
13310
- if (candidates_4_1 && !candidates_4_1.done && (_b = candidates_4.return)) _b.call(candidates_4);
12953
+ if (candidates_5_1 && !candidates_5_1.done && (_b = candidates_5.return)) _b.call(candidates_5);
13311
12954
  }
13312
- finally { if (e_31) throw e_31.error; }
12955
+ finally { if (e_35) throw e_35.error; }
13313
12956
  }
13314
12957
  }
13315
12958
  if (!(db && dbName)) return [3 /*break*/, 4];
@@ -13336,11 +12979,11 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
13336
12979
  _f.label = 5;
13337
12980
  case 5:
13338
12981
  _f.trys.push([5, 10, 11, 12]);
13339
- candidates_5 = __values(candidates), candidates_5_1 = candidates_5.next();
12982
+ candidates_6 = __values(candidates), candidates_6_1 = candidates_6.next();
13340
12983
  _f.label = 6;
13341
12984
  case 6:
13342
- if (!!candidates_5_1.done) return [3 /*break*/, 9];
13343
- candidate = candidates_5_1.value;
12985
+ if (!!candidates_6_1.done) return [3 /*break*/, 9];
12986
+ candidate = candidates_6_1.value;
13344
12987
  if (AI_ASSISTANT_BLOCKED_COLLECTIONS.has(candidate)) {
13345
12988
  return [3 /*break*/, 8];
13346
12989
  }
@@ -13351,34 +12994,34 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
13351
12994
  }
13352
12995
  _f.label = 8;
13353
12996
  case 8:
13354
- candidates_5_1 = candidates_5.next();
12997
+ candidates_6_1 = candidates_6.next();
13355
12998
  return [3 /*break*/, 6];
13356
12999
  case 9: return [3 /*break*/, 12];
13357
13000
  case 10:
13358
- e_30_1 = _f.sent();
13359
- e_30 = { error: e_30_1 };
13001
+ e_34_1 = _f.sent();
13002
+ e_34 = { error: e_34_1 };
13360
13003
  return [3 /*break*/, 12];
13361
13004
  case 11:
13362
13005
  try {
13363
- if (candidates_5_1 && !candidates_5_1.done && (_c = candidates_5.return)) _c.call(candidates_5);
13006
+ if (candidates_6_1 && !candidates_6_1.done && (_c = candidates_6.return)) _c.call(candidates_6);
13364
13007
  }
13365
- finally { if (e_30) throw e_30.error; }
13008
+ finally { if (e_34) throw e_34.error; }
13366
13009
  return [7 /*endfinally*/];
13367
13010
  case 12:
13368
13011
  try {
13369
- for (candidates_6 = __values(candidates), candidates_6_1 = candidates_6.next(); !candidates_6_1.done; candidates_6_1 = candidates_6.next()) {
13370
- candidate = candidates_6_1.value;
13012
+ for (candidates_7 = __values(candidates), candidates_7_1 = candidates_7.next(); !candidates_7_1.done; candidates_7_1 = candidates_7.next()) {
13013
+ candidate = candidates_7_1.value;
13371
13014
  if (isAssistantDirectCollectionFallbackAllowed(candidate)) {
13372
13015
  return [2 /*return*/, __assign({ collection: candidate }, (candidate !== normalized ? { fallbackFrom: normalized } : {}))];
13373
13016
  }
13374
13017
  }
13375
13018
  }
13376
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
13019
+ catch (e_36_1) { e_36 = { error: e_36_1 }; }
13377
13020
  finally {
13378
13021
  try {
13379
- if (candidates_6_1 && !candidates_6_1.done && (_d = candidates_6.return)) _d.call(candidates_6);
13022
+ if (candidates_7_1 && !candidates_7_1.done && (_d = candidates_7.return)) _d.call(candidates_7);
13380
13023
  }
13381
- finally { if (e_32) throw e_32.error; }
13024
+ finally { if (e_36) throw e_36.error; }
13382
13025
  }
13383
13026
  throw new Error('AI assistant report builder bridge: No queryable collection could be resolved.');
13384
13027
  }
@@ -13386,7 +13029,7 @@ function resolveAssistantReportBuilderBridgeCollection(collection_1, db_1) {
13386
13029
  });
13387
13030
  }
13388
13031
  function findQueryDateField(query) {
13389
- var e_33, _a, e_34, _b;
13032
+ var e_37, _a, e_38, _b;
13390
13033
  if (!query || typeof query !== 'object') {
13391
13034
  return null;
13392
13035
  }
@@ -13400,12 +13043,12 @@ function findQueryDateField(query) {
13400
13043
  }
13401
13044
  }
13402
13045
  }
13403
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
13046
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
13404
13047
  finally {
13405
13048
  try {
13406
13049
  if (query_1_1 && !query_1_1.done && (_a = query_1.return)) _a.call(query_1);
13407
13050
  }
13408
- finally { if (e_33) throw e_33.error; }
13051
+ finally { if (e_37) throw e_37.error; }
13409
13052
  }
13410
13053
  return null;
13411
13054
  }
@@ -13424,12 +13067,12 @@ function findQueryDateField(query) {
13424
13067
  }
13425
13068
  }
13426
13069
  }
13427
- catch (e_34_1) { e_34 = { error: e_34_1 }; }
13070
+ catch (e_38_1) { e_38 = { error: e_38_1 }; }
13428
13071
  finally {
13429
13072
  try {
13430
13073
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
13431
13074
  }
13432
- finally { if (e_34) throw e_34.error; }
13075
+ finally { if (e_38) throw e_38.error; }
13433
13076
  }
13434
13077
  return null;
13435
13078
  }
@@ -13678,7 +13321,7 @@ function resolveQueryDateFieldFallback(query) {
13678
13321
  return { from: dateField, to: fallback };
13679
13322
  }
13680
13323
  function containsForbiddenMongoOperators(value) {
13681
- var e_35, _a;
13324
+ var e_39, _a;
13682
13325
  if (!value || typeof value !== 'object') {
13683
13326
  return false;
13684
13327
  }
@@ -13697,12 +13340,12 @@ function containsForbiddenMongoOperators(value) {
13697
13340
  }
13698
13341
  }
13699
13342
  }
13700
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
13343
+ catch (e_39_1) { e_39 = { error: e_39_1 }; }
13701
13344
  finally {
13702
13345
  try {
13703
13346
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
13704
13347
  }
13705
- finally { if (e_35) throw e_35.error; }
13348
+ finally { if (e_39) throw e_39.error; }
13706
13349
  }
13707
13350
  return false;
13708
13351
  }
@@ -14117,8 +13760,8 @@ function applyCodexStreamStatusHandler(runOptions, streamStatusHandler) {
14117
13760
  }
14118
13761
  function waitForCodexWorkerMessage(worker, streamStatusHandler) {
14119
13762
  return __awaiter(this, void 0, void 0, function () {
14120
- var _a, _b, _c, _d, message, payload, status_1, e_36_1;
14121
- var _e, e_36, _f, _g;
13763
+ var _a, _b, _c, _d, message, payload, status_1, e_40_1;
13764
+ var _e, e_40, _f, _g;
14122
13765
  return __generator(this, function (_h) {
14123
13766
  switch (_h.label) {
14124
13767
  case 0:
@@ -14145,8 +13788,8 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
14145
13788
  return [3 /*break*/, 1];
14146
13789
  case 4: return [3 /*break*/, 11];
14147
13790
  case 5:
14148
- e_36_1 = _h.sent();
14149
- e_36 = { error: e_36_1 };
13791
+ e_40_1 = _h.sent();
13792
+ e_40 = { error: e_40_1 };
14150
13793
  return [3 /*break*/, 11];
14151
13794
  case 6:
14152
13795
  _h.trys.push([6, , 9, 10]);
@@ -14157,7 +13800,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
14157
13800
  _h.label = 8;
14158
13801
  case 8: return [3 /*break*/, 10];
14159
13802
  case 9:
14160
- if (e_36) throw e_36.error;
13803
+ if (e_40) throw e_40.error;
14161
13804
  return [7 /*endfinally*/];
14162
13805
  case 10: return [7 /*endfinally*/];
14163
13806
  case 11: throw new CodexWorkerBootstrapError('Codex worker exited before completing.');
@@ -14167,7 +13810,7 @@ function waitForCodexWorkerMessage(worker, streamStatusHandler) {
14167
13810
  }
14168
13811
  function runCodexInWorkerThread(prompt, runOptions, config, streamStatusHandler) {
14169
13812
  return __awaiter(this, void 0, void 0, function () {
14170
- var streamedOptions, codexClient, workerPath, codexClient, error_7, codexClient;
13813
+ var streamedOptions, codexClient, workerPath, codexClient, error_8, codexClient;
14171
13814
  return __generator(this, function (_a) {
14172
13815
  switch (_a.label) {
14173
13816
  case 0:
@@ -14188,11 +13831,11 @@ function runCodexInWorkerThread(prompt, runOptions, config, streamStatusHandler)
14188
13831
  return [4 /*yield*/, runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config, streamStatusHandler)];
14189
13832
  case 6: return [2 /*return*/, _a.sent()];
14190
13833
  case 7:
14191
- error_7 = _a.sent();
14192
- if (!(error_7 instanceof CodexWorkerBootstrapError)) {
14193
- throw error_7;
13834
+ error_8 = _a.sent();
13835
+ if (!(error_8 instanceof CodexWorkerBootstrapError)) {
13836
+ throw error_8;
14194
13837
  }
14195
- console.error('Codex worker bootstrap failed, falling back to in-process run.', error_7);
13838
+ console.error('Codex worker bootstrap failed, falling back to in-process run.', error_8);
14196
13839
  codexClient = getAssistantCodexClient(config);
14197
13840
  return [4 /*yield*/, codexClient.run(prompt, streamedOptions)];
14198
13841
  case 8: return [2 /*return*/, _a.sent()];
@@ -14230,7 +13873,7 @@ function runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config,
14230
13873
  timeoutMs = ((sanitizedOptions === null || sanitizedOptions === void 0 ? void 0 : sanitizedOptions.timeoutMs) || resolveCodexTimeoutMs()) + 15000;
14231
13874
  timeoutController = new AbortController();
14232
13875
  timeoutPromise = (function () { return __awaiter(_this, void 0, void 0, function () {
14233
- var error_8;
13876
+ var error_9;
14234
13877
  return __generator(this, function (_a) {
14235
13878
  switch (_a.label) {
14236
13879
  case 0:
@@ -14240,11 +13883,11 @@ function runCodexInWorkerThreadInternal(workerPath, prompt, runOptions, config,
14240
13883
  _a.sent();
14241
13884
  return [2 /*return*/, { type: 'timeout' }];
14242
13885
  case 2:
14243
- error_8 = _a.sent();
14244
- if ((error_8 === null || error_8 === void 0 ? void 0 : error_8.name) === 'AbortError') {
13886
+ error_9 = _a.sent();
13887
+ if ((error_9 === null || error_9 === void 0 ? void 0 : error_9.name) === 'AbortError') {
14245
13888
  return [2 /*return*/, { type: 'aborted' }];
14246
13889
  }
14247
- throw error_8;
13890
+ throw error_9;
14248
13891
  case 3: return [2 /*return*/];
14249
13892
  }
14250
13893
  });
@@ -14420,30 +14063,95 @@ function directoryExists(target) {
14420
14063
  });
14421
14064
  });
14422
14065
  }
14066
+ function buildAssistantWorkspaceRootCandidates(params) {
14067
+ var serverConfig = (params === null || params === void 0 ? void 0 : params.serverConfig) || resolveio_server_app_1.ResolveIOServer.getServerConfig() || {};
14068
+ var env = (params === null || params === void 0 ? void 0 : params.env) || process.env || {};
14069
+ var cwdValue = normalizeOptionalString((params === null || params === void 0 ? void 0 : params.cwd) || process.cwd());
14070
+ var dirnameValue = normalizeOptionalString((params === null || params === void 0 ? void 0 : params.dirname) || __dirname);
14071
+ var pathCandidates = [
14072
+ serverConfig['AI_ASSISTANT_WORKSPACE_ROOT'],
14073
+ env['AI_ASSISTANT_WORKSPACE_ROOT'],
14074
+ serverConfig['AI_TERMINAL_WORKSPACE_ROOT'],
14075
+ env['AI_TERMINAL_WORKSPACE_ROOT'],
14076
+ serverConfig['AI_DASHBOARD_WORKSPACE_ROOT'],
14077
+ env['AI_DASHBOARD_WORKSPACE_ROOT'],
14078
+ '/var/app/current',
14079
+ cwdValue,
14080
+ dirnameValue ? path.resolve(dirnameValue, '../../..') : '',
14081
+ dirnameValue ? path.resolve(dirnameValue, '../../../..') : ''
14082
+ ];
14083
+ var seen = new Set();
14084
+ var candidates = [];
14085
+ pathCandidates.forEach(function (value) {
14086
+ var normalized = normalizeOptionalString(value);
14087
+ if (!normalized) {
14088
+ return;
14089
+ }
14090
+ var resolved = path.resolve(normalized);
14091
+ if (!resolved || seen.has(resolved)) {
14092
+ return;
14093
+ }
14094
+ seen.add(resolved);
14095
+ candidates.push(resolved);
14096
+ });
14097
+ return candidates;
14098
+ }
14423
14099
  function resolveAssistantWorkspaceRoot() {
14424
14100
  return __awaiter(this, void 0, void 0, function () {
14425
- var candidate, stat, _a;
14426
- return __generator(this, function (_b) {
14427
- switch (_b.label) {
14101
+ var candidates, firstExisting, candidates_8, candidates_8_1, candidate, _a, gitRoot, e_41_1;
14102
+ var e_41, _b;
14103
+ return __generator(this, function (_c) {
14104
+ switch (_c.label) {
14428
14105
  case 0:
14429
- candidate = '/var/app/current';
14430
- stat = null;
14431
- _b.label = 1;
14106
+ candidates = buildAssistantWorkspaceRootCandidates();
14107
+ firstExisting = '';
14108
+ _c.label = 1;
14432
14109
  case 1:
14433
- _b.trys.push([1, 3, , 4]);
14434
- return [4 /*yield*/, fs_1.promises.stat(candidate)];
14110
+ _c.trys.push([1, 8, 9, 10]);
14111
+ candidates_8 = __values(candidates), candidates_8_1 = candidates_8.next();
14112
+ _c.label = 2;
14435
14113
  case 2:
14436
- stat = _b.sent();
14437
- return [3 /*break*/, 4];
14114
+ if (!!candidates_8_1.done) return [3 /*break*/, 7];
14115
+ candidate = candidates_8_1.value;
14116
+ _a = !candidate;
14117
+ if (_a) return [3 /*break*/, 4];
14118
+ return [4 /*yield*/, directoryExists(candidate)];
14438
14119
  case 3:
14439
- _a = _b.sent();
14440
- stat = null;
14441
- return [3 /*break*/, 4];
14120
+ _a = !(_c.sent());
14121
+ _c.label = 4;
14442
14122
  case 4:
14443
- if (!stat || !stat.isDirectory()) {
14444
- throw new Error('AI assistant workspace root not found.');
14123
+ if (_a) {
14124
+ return [3 /*break*/, 6];
14125
+ }
14126
+ if (!firstExisting) {
14127
+ firstExisting = candidate;
14128
+ }
14129
+ return [4 /*yield*/, resolveAssistantGitRoot(candidate)];
14130
+ case 5:
14131
+ gitRoot = _c.sent();
14132
+ if (gitRoot) {
14133
+ return [2 /*return*/, candidate];
14134
+ }
14135
+ _c.label = 6;
14136
+ case 6:
14137
+ candidates_8_1 = candidates_8.next();
14138
+ return [3 /*break*/, 2];
14139
+ case 7: return [3 /*break*/, 10];
14140
+ case 8:
14141
+ e_41_1 = _c.sent();
14142
+ e_41 = { error: e_41_1 };
14143
+ return [3 /*break*/, 10];
14144
+ case 9:
14145
+ try {
14146
+ if (candidates_8_1 && !candidates_8_1.done && (_b = candidates_8.return)) _b.call(candidates_8);
14445
14147
  }
14446
- return [2 /*return*/, candidate];
14148
+ finally { if (e_41) throw e_41.error; }
14149
+ return [7 /*endfinally*/];
14150
+ case 10:
14151
+ if (firstExisting) {
14152
+ return [2 /*return*/, firstExisting];
14153
+ }
14154
+ throw new Error('AI assistant workspace root not found.');
14447
14155
  }
14448
14156
  });
14449
14157
  });
@@ -14833,7 +14541,7 @@ var AI_ASSISTANT_BREAKDOWN_DIMENSION_STOPWORDS = new Set([
14833
14541
  'by'
14834
14542
  ]);
14835
14543
  function normalizeAssistantBreakdownDimension(value) {
14836
- var e_37, _a;
14544
+ var e_42, _a;
14837
14545
  var normalized = normalizeOptionalString(value)
14838
14546
  .toLowerCase()
14839
14547
  .replace(/[^a-z0-9_\s-]+/g, ' ')
@@ -14865,12 +14573,12 @@ function normalizeAssistantBreakdownDimension(value) {
14865
14573
  }
14866
14574
  }
14867
14575
  }
14868
- catch (e_37_1) { e_37 = { error: e_37_1 }; }
14576
+ catch (e_42_1) { e_42 = { error: e_42_1 }; }
14869
14577
  finally {
14870
14578
  try {
14871
14579
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
14872
14580
  }
14873
- finally { if (e_37) throw e_37.error; }
14581
+ finally { if (e_42) throw e_42.error; }
14874
14582
  }
14875
14583
  if (!kept.length) {
14876
14584
  return '';
@@ -15057,7 +14765,7 @@ function resolveAssistantPlannerEnabled() {
15057
14765
  return raw === undefined ? true : raw === true;
15058
14766
  }
15059
14767
  function resolveAssistantPlannerKnownRoutes() {
15060
- var e_38, _a;
14768
+ var e_43, _a;
15061
14769
  var _b;
15062
14770
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
15063
14771
  var unique = new Set();
@@ -15070,12 +14778,12 @@ function resolveAssistantPlannerKnownRoutes() {
15070
14778
  }
15071
14779
  }
15072
14780
  }
15073
- catch (e_38_1) { e_38 = { error: e_38_1 }; }
14781
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
15074
14782
  finally {
15075
14783
  try {
15076
14784
  if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
15077
14785
  }
15078
- finally { if (e_38) throw e_38.error; }
14786
+ finally { if (e_43) throw e_43.error; }
15079
14787
  }
15080
14788
  return Array.from(unique).slice(0, AI_ASSISTANT_PLANNER_MAX_ROUTES);
15081
14789
  }
@@ -15318,7 +15026,7 @@ function normalizeRouteMatchKey(value) {
15318
15026
  return normalizeRouteKey(value).toLowerCase();
15319
15027
  }
15320
15028
  function buildClientRouteIndex() {
15321
- var e_39, _a;
15029
+ var e_44, _a;
15322
15030
  var _b;
15323
15031
  var routes = ((_b = resolveio_server_app_1.ResolveIOServer.getClientRoutes) === null || _b === void 0 ? void 0 : _b.call(resolveio_server_app_1.ResolveIOServer)) || [];
15324
15032
  var set = new Set();
@@ -15337,12 +15045,12 @@ function buildClientRouteIndex() {
15337
15045
  }
15338
15046
  }
15339
15047
  }
15340
- catch (e_39_1) { e_39 = { error: e_39_1 }; }
15048
+ catch (e_44_1) { e_44 = { error: e_44_1 }; }
15341
15049
  finally {
15342
15050
  try {
15343
15051
  if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
15344
15052
  }
15345
- finally { if (e_39) throw e_39.error; }
15053
+ finally { if (e_44) throw e_44.error; }
15346
15054
  }
15347
15055
  return { set: set, map: map, size: routes.length };
15348
15056
  }
@@ -16099,6 +15807,98 @@ function resolveAssistantGitRoot(startDir) {
16099
15807
  });
16100
15808
  });
16101
15809
  }
15810
+ function resolveAssistantWorkspaceGitRoots(workspaceRoot) {
15811
+ return __awaiter(this, void 0, void 0, function () {
15812
+ var roots, seen, push, _a, entries, _b, skipNames, entries_1, entries_1_1, entry, name_1, candidate, gitPath, _c, e_45_1;
15813
+ var e_45, _d;
15814
+ var _e;
15815
+ return __generator(this, function (_f) {
15816
+ switch (_f.label) {
15817
+ case 0:
15818
+ roots = [];
15819
+ seen = new Set();
15820
+ push = function (value) {
15821
+ var normalized = normalizeOptionalString(value);
15822
+ if (!normalized) {
15823
+ return;
15824
+ }
15825
+ var resolved = path.resolve(normalized);
15826
+ if (!resolved || seen.has(resolved)) {
15827
+ return;
15828
+ }
15829
+ seen.add(resolved);
15830
+ roots.push(resolved);
15831
+ };
15832
+ _a = push;
15833
+ return [4 /*yield*/, resolveAssistantGitRoot(workspaceRoot)];
15834
+ case 1:
15835
+ _a.apply(void 0, [_f.sent()]);
15836
+ entries = [];
15837
+ _f.label = 2;
15838
+ case 2:
15839
+ _f.trys.push([2, 4, , 5]);
15840
+ return [4 /*yield*/, fs_1.promises.readdir(workspaceRoot, { withFileTypes: true })];
15841
+ case 3:
15842
+ entries = _f.sent();
15843
+ return [3 /*break*/, 5];
15844
+ case 4:
15845
+ _b = _f.sent();
15846
+ entries = [];
15847
+ return [3 /*break*/, 5];
15848
+ case 5:
15849
+ skipNames = new Set(['node_modules', 'dist', 'build', 'tmp', 'temp', 'coverage']);
15850
+ _f.label = 6;
15851
+ case 6:
15852
+ _f.trys.push([6, 13, 14, 15]);
15853
+ entries_1 = __values(entries), entries_1_1 = entries_1.next();
15854
+ _f.label = 7;
15855
+ case 7:
15856
+ if (!!entries_1_1.done) return [3 /*break*/, 12];
15857
+ entry = entries_1_1.value;
15858
+ if (roots.length >= 12) {
15859
+ return [3 /*break*/, 12];
15860
+ }
15861
+ if (!((_e = entry === null || entry === void 0 ? void 0 : entry.isDirectory) === null || _e === void 0 ? void 0 : _e.call(entry))) {
15862
+ return [3 /*break*/, 11];
15863
+ }
15864
+ name_1 = normalizeOptionalString(entry.name).toLowerCase();
15865
+ if (!name_1 || name_1.startsWith('.') || skipNames.has(name_1)) {
15866
+ return [3 /*break*/, 11];
15867
+ }
15868
+ candidate = path.join(workspaceRoot, entry.name);
15869
+ gitPath = path.join(candidate, '.git');
15870
+ return [4 /*yield*/, directoryExists(gitPath)];
15871
+ case 8:
15872
+ _c = (_f.sent());
15873
+ if (_c) return [3 /*break*/, 10];
15874
+ return [4 /*yield*/, pathExists(gitPath)];
15875
+ case 9:
15876
+ _c = (_f.sent());
15877
+ _f.label = 10;
15878
+ case 10:
15879
+ if (_c) {
15880
+ push(candidate);
15881
+ }
15882
+ _f.label = 11;
15883
+ case 11:
15884
+ entries_1_1 = entries_1.next();
15885
+ return [3 /*break*/, 7];
15886
+ case 12: return [3 /*break*/, 15];
15887
+ case 13:
15888
+ e_45_1 = _f.sent();
15889
+ e_45 = { error: e_45_1 };
15890
+ return [3 /*break*/, 15];
15891
+ case 14:
15892
+ try {
15893
+ if (entries_1_1 && !entries_1_1.done && (_d = entries_1.return)) _d.call(entries_1);
15894
+ }
15895
+ finally { if (e_45) throw e_45.error; }
15896
+ return [7 /*endfinally*/];
15897
+ case 15: return [2 /*return*/, roots];
15898
+ }
15899
+ });
15900
+ });
15901
+ }
16102
15902
  function runAssistantGitCommand(gitRoot, args) {
16103
15903
  return __awaiter(this, void 0, void 0, function () {
16104
15904
  var result;
@@ -16234,76 +16034,76 @@ function buildAssistantChangeHistorySummaryFromCommits(params) {
16234
16034
  }
16235
16035
  function resolveAssistantChangeHistoryFastPathResponse(params) {
16236
16036
  return __awaiter(this, void 0, void 0, function () {
16237
- var workspaceRoot, _a, gitRoot, _b, branch, _c, _d, limit, historyDepth, rawHistory, commits, _e;
16238
- return __generator(this, function (_f) {
16239
- switch (_f.label) {
16037
+ var workspaceRoot, _a, gitRoots, sawExecutionError, gitRoots_1, gitRoots_1_1, gitRoot, _b, branch, _c, _d, limit, historyDepth, rawHistory, commits, _e, e_46_1;
16038
+ var e_46, _f;
16039
+ return __generator(this, function (_g) {
16040
+ switch (_g.label) {
16240
16041
  case 0:
16241
16042
  if (!shouldUseAssistantChangeHistoryFastPath(params.message, params.hasAttachments)) {
16242
16043
  return [2 /*return*/, null];
16243
16044
  }
16244
16045
  workspaceRoot = '';
16245
- _f.label = 1;
16046
+ _g.label = 1;
16246
16047
  case 1:
16247
- _f.trys.push([1, 3, , 4]);
16048
+ _g.trys.push([1, 3, , 4]);
16248
16049
  return [4 /*yield*/, resolveAssistantWorkspaceRoot()];
16249
16050
  case 2:
16250
- workspaceRoot = _f.sent();
16051
+ workspaceRoot = _g.sent();
16251
16052
  return [3 /*break*/, 4];
16252
16053
  case 3:
16253
- _a = _f.sent();
16054
+ _a = _g.sent();
16254
16055
  workspaceRoot = '';
16255
16056
  return [3 /*break*/, 4];
16256
16057
  case 4:
16257
16058
  if (!workspaceRoot) {
16258
- return [2 /*return*/, {
16259
- response: 'I can only share a high-level summary right now: recent updates included bug fixes, reliability improvements, and maintenance tasks.',
16260
- reason: 'no_repo',
16261
- commitCount: 0,
16262
- generic: true
16263
- }];
16059
+ return [2 /*return*/, null];
16264
16060
  }
16265
- return [4 /*yield*/, resolveAssistantGitRoot(workspaceRoot)];
16061
+ return [4 /*yield*/, resolveAssistantWorkspaceGitRoots(workspaceRoot)];
16266
16062
  case 5:
16267
- gitRoot = _f.sent();
16268
- if (!gitRoot) {
16269
- return [2 /*return*/, {
16270
- response: 'I can only share a high-level summary right now: recent updates included bug fixes, reliability improvements, and maintenance tasks.',
16271
- reason: 'no_repo',
16272
- commitCount: 0,
16273
- generic: true
16274
- }];
16063
+ gitRoots = _g.sent();
16064
+ if (!gitRoots.length) {
16065
+ return [2 /*return*/, null];
16275
16066
  }
16276
- _f.label = 6;
16067
+ sawExecutionError = false;
16068
+ _g.label = 6;
16277
16069
  case 6:
16278
- _f.trys.push([6, 16, , 17]);
16279
- if (!(resolveAssistantChangeHistoryFetchEnabled() && shouldAssistantFetchGitRemote(params.message))) return [3 /*break*/, 10];
16280
- _f.label = 7;
16070
+ _g.trys.push([6, 21, 22, 23]);
16071
+ gitRoots_1 = __values(gitRoots), gitRoots_1_1 = gitRoots_1.next();
16072
+ _g.label = 7;
16281
16073
  case 7:
16282
- _f.trys.push([7, 9, , 10]);
16283
- return [4 /*yield*/, runAssistantGitCommand(gitRoot, ['fetch', '--all', '--prune', '--quiet'])];
16074
+ if (!!gitRoots_1_1.done) return [3 /*break*/, 20];
16075
+ gitRoot = gitRoots_1_1.value;
16076
+ _g.label = 8;
16284
16077
  case 8:
16285
- _f.sent();
16286
- return [3 /*break*/, 10];
16078
+ _g.trys.push([8, 18, , 19]);
16079
+ if (!(resolveAssistantChangeHistoryFetchEnabled() && shouldAssistantFetchGitRemote(params.message))) return [3 /*break*/, 12];
16080
+ _g.label = 9;
16287
16081
  case 9:
16288
- _b = _f.sent();
16289
- return [3 /*break*/, 10];
16082
+ _g.trys.push([9, 11, , 12]);
16083
+ return [4 /*yield*/, runAssistantGitCommand(gitRoot, ['fetch', '--all', '--prune', '--quiet'])];
16290
16084
  case 10:
16291
- branch = '';
16292
- _f.label = 11;
16085
+ _g.sent();
16086
+ return [3 /*break*/, 12];
16293
16087
  case 11:
16294
- _f.trys.push([11, 13, , 14]);
16088
+ _b = _g.sent();
16089
+ return [3 /*break*/, 12];
16090
+ case 12:
16091
+ branch = '';
16092
+ _g.label = 13;
16093
+ case 13:
16094
+ _g.trys.push([13, 15, , 16]);
16295
16095
  _c = normalizeOptionalString;
16296
16096
  return [4 /*yield*/, runAssistantGitCommand(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD'])];
16297
- case 12:
16298
- branch = _c.apply(void 0, [_f.sent()])
16097
+ case 14:
16098
+ branch = _c.apply(void 0, [_g.sent()])
16299
16099
  .split(/\r?\n/g)[0]
16300
16100
  .trim();
16301
- return [3 /*break*/, 14];
16302
- case 13:
16303
- _d = _f.sent();
16101
+ return [3 /*break*/, 16];
16102
+ case 15:
16103
+ _d = _g.sent();
16304
16104
  branch = '';
16305
- return [3 /*break*/, 14];
16306
- case 14:
16105
+ return [3 /*break*/, 16];
16106
+ case 16:
16307
16107
  limit = resolveAssistantChangeHistoryLimit(params.message);
16308
16108
  historyDepth = resolveAssistantChangeHistoryDepth(params.message, limit);
16309
16109
  return [4 /*yield*/, runAssistantGitCommand(gitRoot, [
@@ -16315,11 +16115,11 @@ function resolveAssistantChangeHistoryFastPathResponse(params) {
16315
16115
  '--pretty=format:%x1e%ad%x1f%s',
16316
16116
  '--name-only'
16317
16117
  ])];
16318
- case 15:
16319
- rawHistory = _f.sent();
16118
+ case 17:
16119
+ rawHistory = _g.sent();
16320
16120
  commits = parseAssistantGitLogOutput(rawHistory);
16321
16121
  if (!commits.length) {
16322
- return [2 /*return*/, __assign({ response: 'I can only share a high-level summary right now: recent updates included bug fixes, reliability improvements, and maintenance tasks.', reason: 'no_repo', commitCount: 0, generic: true }, (branch ? { branch: branch } : {}))];
16122
+ return [3 /*break*/, 19];
16323
16123
  }
16324
16124
  return [2 /*return*/, buildAssistantChangeHistorySummaryFromCommits({
16325
16125
  message: params.message,
@@ -16328,15 +16128,29 @@ function resolveAssistantChangeHistoryFastPathResponse(params) {
16328
16128
  commits: commits,
16329
16129
  branch: branch
16330
16130
  })];
16331
- case 16:
16332
- _e = _f.sent();
16333
- return [2 /*return*/, {
16334
- response: 'I can only share a high-level summary right now: recent updates included bug fixes, reliability improvements, and maintenance tasks.',
16335
- reason: 'error',
16336
- commitCount: 0,
16337
- generic: true
16338
- }];
16339
- case 17: return [2 /*return*/];
16131
+ case 18:
16132
+ _e = _g.sent();
16133
+ sawExecutionError = true;
16134
+ return [3 /*break*/, 19];
16135
+ case 19:
16136
+ gitRoots_1_1 = gitRoots_1.next();
16137
+ return [3 /*break*/, 7];
16138
+ case 20: return [3 /*break*/, 23];
16139
+ case 21:
16140
+ e_46_1 = _g.sent();
16141
+ e_46 = { error: e_46_1 };
16142
+ return [3 /*break*/, 23];
16143
+ case 22:
16144
+ try {
16145
+ if (gitRoots_1_1 && !gitRoots_1_1.done && (_f = gitRoots_1.return)) _f.call(gitRoots_1);
16146
+ }
16147
+ finally { if (e_46) throw e_46.error; }
16148
+ return [7 /*endfinally*/];
16149
+ case 23:
16150
+ if (sawExecutionError) {
16151
+ return [2 /*return*/, null];
16152
+ }
16153
+ return [2 /*return*/, null];
16340
16154
  }
16341
16155
  });
16342
16156
  });
@@ -16508,7 +16322,7 @@ function sanitizeAssistantResponse(value) {
16508
16322
  return normalizeAssistantRoutes(normalizedCurrency);
16509
16323
  }
16510
16324
  function evaluateAssistantGuardrails(message) {
16511
- var e_40, _a;
16325
+ var e_47, _a;
16512
16326
  var normalized = String(message || '').toLowerCase();
16513
16327
  var patterns = [
16514
16328
  {
@@ -16543,8 +16357,8 @@ function evaluateAssistantGuardrails(message) {
16543
16357
  }
16544
16358
  ];
16545
16359
  try {
16546
- for (var patterns_1 = __values(patterns), patterns_1_1 = patterns_1.next(); !patterns_1_1.done; patterns_1_1 = patterns_1.next()) {
16547
- var entry = patterns_1_1.value;
16360
+ for (var patterns_2 = __values(patterns), patterns_2_1 = patterns_2.next(); !patterns_2_1.done; patterns_2_1 = patterns_2.next()) {
16361
+ var entry = patterns_2_1.value;
16548
16362
  if (entry.pattern.test(normalized)) {
16549
16363
  return {
16550
16364
  blocked: true,
@@ -16554,12 +16368,12 @@ function evaluateAssistantGuardrails(message) {
16554
16368
  }
16555
16369
  }
16556
16370
  }
16557
- catch (e_40_1) { e_40 = { error: e_40_1 }; }
16371
+ catch (e_47_1) { e_47 = { error: e_47_1 }; }
16558
16372
  finally {
16559
16373
  try {
16560
- if (patterns_1_1 && !patterns_1_1.done && (_a = patterns_1.return)) _a.call(patterns_1);
16374
+ if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
16561
16375
  }
16562
- finally { if (e_40) throw e_40.error; }
16376
+ finally { if (e_47) throw e_47.error; }
16563
16377
  }
16564
16378
  return null;
16565
16379
  }
@@ -16674,7 +16488,7 @@ function tokenizeArithmeticExpression(expression) {
16674
16488
  return tokens;
16675
16489
  }
16676
16490
  function evaluateArithmeticExpression(expression) {
16677
- var e_41, _a, e_42, _b;
16491
+ var e_48, _a, e_49, _b;
16678
16492
  var tokens = tokenizeArithmeticExpression(expression);
16679
16493
  if (!tokens || !tokens.length) {
16680
16494
  return null;
@@ -16731,12 +16545,12 @@ function evaluateArithmeticExpression(expression) {
16731
16545
  prevToken = token;
16732
16546
  }
16733
16547
  }
16734
- catch (e_41_1) { e_41 = { error: e_41_1 }; }
16548
+ catch (e_48_1) { e_48 = { error: e_48_1 }; }
16735
16549
  finally {
16736
16550
  try {
16737
16551
  if (tokens_2_1 && !tokens_2_1.done && (_a = tokens_2.return)) _a.call(tokens_2);
16738
16552
  }
16739
- finally { if (e_41) throw e_41.error; }
16553
+ finally { if (e_48) throw e_48.error; }
16740
16554
  }
16741
16555
  while (ops.length) {
16742
16556
  var op = ops.pop();
@@ -16776,12 +16590,12 @@ function evaluateArithmeticExpression(expression) {
16776
16590
  stack.push(Number(token));
16777
16591
  }
16778
16592
  }
16779
- catch (e_42_1) { e_42 = { error: e_42_1 }; }
16593
+ catch (e_49_1) { e_49 = { error: e_49_1 }; }
16780
16594
  finally {
16781
16595
  try {
16782
16596
  if (output_1_1 && !output_1_1.done && (_b = output_1.return)) _b.call(output_1);
16783
16597
  }
16784
- finally { if (e_42) throw e_42.error; }
16598
+ finally { if (e_49) throw e_49.error; }
16785
16599
  }
16786
16600
  if (stack.length !== 1 || Number.isNaN(stack[0])) {
16787
16601
  return null;
@@ -16965,8 +16779,8 @@ function handleCodexUpload(id_conversation, file_name, content_base64, size, con
16965
16779
  }
16966
16780
  function readAttachmentContents(attachments) {
16967
16781
  return __awaiter(this, void 0, void 0, function () {
16968
- var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_1, type, readable, content, _a, e_43_1;
16969
- var e_43, _b;
16782
+ var limits, totalBytes, totalChars, chunks, cleaned, attachments_1, attachments_1_1, attachment, localPath, safe, stat, ext, name_2, type, readable, content, _a, e_50_1;
16783
+ var e_50, _b;
16970
16784
  return __generator(this, function (_c) {
16971
16785
  switch (_c.label) {
16972
16786
  case 0:
@@ -17008,7 +16822,7 @@ function readAttachmentContents(attachments) {
17008
16822
  return [3 /*break*/, 10];
17009
16823
  }
17010
16824
  ext = path.extname(localPath).toLowerCase();
17011
- name_1 = normalizeOptionalString(attachment.name) || path.basename(localPath);
16825
+ name_2 = normalizeOptionalString(attachment.name) || path.basename(localPath);
17012
16826
  type = normalizeOptionalString(attachment.type);
17013
16827
  readable = isReadableAttachment(type, ext);
17014
16828
  content = '';
@@ -17021,17 +16835,17 @@ function readAttachmentContents(attachments) {
17021
16835
  }
17022
16836
  return [3 /*break*/, 7];
17023
16837
  case 6:
17024
- content = "[".concat(name_1, " attached; binary content omitted]");
16838
+ content = "[".concat(name_2, " attached; binary content omitted]");
17025
16839
  _c.label = 7;
17026
16840
  case 7:
17027
16841
  totalChars += content.length;
17028
16842
  if (totalChars > limits.maxTotalAttachmentChars) {
17029
16843
  return [3 /*break*/, 10];
17030
16844
  }
17031
- chunks.push("File: ".concat(name_1, "\n").concat(content));
16845
+ chunks.push("File: ".concat(name_2, "\n").concat(content));
17032
16846
  cleaned.push({
17033
16847
  id: attachment.id,
17034
- name: name_1,
16848
+ name: name_2,
17035
16849
  type: type,
17036
16850
  size: stat.size,
17037
16851
  local_path: localPath
@@ -17045,14 +16859,14 @@ function readAttachmentContents(attachments) {
17045
16859
  return [3 /*break*/, 2];
17046
16860
  case 10: return [3 /*break*/, 13];
17047
16861
  case 11:
17048
- e_43_1 = _c.sent();
17049
- e_43 = { error: e_43_1 };
16862
+ e_50_1 = _c.sent();
16863
+ e_50 = { error: e_50_1 };
17050
16864
  return [3 /*break*/, 13];
17051
16865
  case 12:
17052
16866
  try {
17053
16867
  if (attachments_1_1 && !attachments_1_1.done && (_b = attachments_1.return)) _b.call(attachments_1);
17054
16868
  }
17055
- finally { if (e_43) throw e_43.error; }
16869
+ finally { if (e_50) throw e_50.error; }
17056
16870
  return [7 /*endfinally*/];
17057
16871
  case 13: return [2 /*return*/, {
17058
16872
  promptText: chunks.length ? "\n\nAttachments:\n".concat(chunks.join('\n\n')) : '',
@@ -17207,7 +17021,7 @@ function resolveAssistantDatabaseNameForSystemCollections() {
17207
17021
  }
17208
17022
  function updateAssistantMessageWithFallback(messageId, setPayload) {
17209
17023
  return __awaiter(this, void 0, void 0, function () {
17210
- var error_9, dbName, _a;
17024
+ var error_10, dbName, _a;
17211
17025
  return __generator(this, function (_b) {
17212
17026
  switch (_b.label) {
17213
17027
  case 0:
@@ -17222,9 +17036,9 @@ function updateAssistantMessageWithFallback(messageId, setPayload) {
17222
17036
  _b.sent();
17223
17037
  return [2 /*return*/];
17224
17038
  case 3:
17225
- error_9 = _b.sent();
17226
- if (!isAssistantTransactionCommittedError(error_9)) {
17227
- throw error_9;
17039
+ error_10 = _b.sent();
17040
+ if (!isAssistantTransactionCommittedError(error_10)) {
17041
+ throw error_10;
17228
17042
  }
17229
17043
  dbName = resolveAssistantDatabaseNameForSystemCollections();
17230
17044
  _b.label = 4;
@@ -17254,7 +17068,7 @@ function updateAssistantMessageWithFallback(messageId, setPayload) {
17254
17068
  }
17255
17069
  function touchConversation(idConversation, timestamp, lastMessageId) {
17256
17070
  return __awaiter(this, void 0, void 0, function () {
17257
- var update, error_10, dbName;
17071
+ var update, error_11, dbName;
17258
17072
  return __generator(this, function (_a) {
17259
17073
  switch (_a.label) {
17260
17074
  case 0:
@@ -17273,9 +17087,9 @@ function touchConversation(idConversation, timestamp, lastMessageId) {
17273
17087
  _a.sent();
17274
17088
  return [2 /*return*/];
17275
17089
  case 3:
17276
- error_10 = _a.sent();
17277
- if (!isAssistantTransactionCommittedError(error_10)) {
17278
- throw error_10;
17090
+ error_11 = _a.sent();
17091
+ if (!isAssistantTransactionCommittedError(error_11)) {
17092
+ throw error_11;
17279
17093
  }
17280
17094
  dbName = resolveAssistantDatabaseNameForSystemCollections();
17281
17095
  return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMongoConnection()
@@ -17376,7 +17190,7 @@ function estimateUsage(messages, responseText, model) {
17376
17190
  };
17377
17191
  }
17378
17192
  function evaluateGuardrails(message) {
17379
- var e_44, _a;
17193
+ var e_51, _a;
17380
17194
  var normalized = String(message || '').toLowerCase();
17381
17195
  var patterns = [
17382
17196
  { pattern: /\b(source\s*code|full\s*code|entire\s*code|repo\s*dump|repository|git\s*clone)\b/i, reason: 'Code access is restricted.' },
@@ -17387,8 +17201,8 @@ function evaluateGuardrails(message) {
17387
17201
  { pattern: /\b(exploit|bypass|malware|phishing|ransomware|ddos)\b/i, reason: 'Security abuse is restricted.' }
17388
17202
  ];
17389
17203
  try {
17390
- for (var patterns_2 = __values(patterns), patterns_2_1 = patterns_2.next(); !patterns_2_1.done; patterns_2_1 = patterns_2.next()) {
17391
- var entry = patterns_2_1.value;
17204
+ for (var patterns_3 = __values(patterns), patterns_3_1 = patterns_3.next(); !patterns_3_1.done; patterns_3_1 = patterns_3.next()) {
17205
+ var entry = patterns_3_1.value;
17392
17206
  if (entry.pattern.test(normalized)) {
17393
17207
  return {
17394
17208
  blocked: true,
@@ -17398,12 +17212,12 @@ function evaluateGuardrails(message) {
17398
17212
  }
17399
17213
  }
17400
17214
  }
17401
- catch (e_44_1) { e_44 = { error: e_44_1 }; }
17215
+ catch (e_51_1) { e_51 = { error: e_51_1 }; }
17402
17216
  finally {
17403
17217
  try {
17404
- if (patterns_2_1 && !patterns_2_1.done && (_a = patterns_2.return)) _a.call(patterns_2);
17218
+ if (patterns_3_1 && !patterns_3_1.done && (_a = patterns_3.return)) _a.call(patterns_3);
17405
17219
  }
17406
- finally { if (e_44) throw e_44.error; }
17220
+ finally { if (e_51) throw e_51.error; }
17407
17221
  }
17408
17222
  return null;
17409
17223
  }