@resolveio/server-lib 22.2.56 → 22.2.57

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.
@@ -188,6 +188,7 @@ export declare function buildDisplayTable(docs: any[], options?: {
188
188
  includeGroupFromId?: boolean;
189
189
  }): AiAssistantDisplayTable;
190
190
  export declare function formatDisplayTableMarkdown(display: AiAssistantDisplayTable): string;
191
+ export declare function applyAssistantDisplayTableToResponseForTesting(value: string, display: AiAssistantDisplayTable | null | undefined): string;
191
192
  export declare function resolveAssistantReadDisplayMaxRows(limit: number | undefined, rowCount: number): number;
192
193
  export declare function normalizeAssistantNowExprPlaceholders(value: any): any;
193
194
  export declare function repairAssistantPositionalPathSegmentsInPipeline(pipeline: Array<Record<string, any>>): {
@@ -121,6 +121,7 @@ exports.serializeMongoValue = serializeMongoValue;
121
121
  exports.flattenForTable = flattenForTable;
122
122
  exports.buildDisplayTable = buildDisplayTable;
123
123
  exports.formatDisplayTableMarkdown = formatDisplayTableMarkdown;
124
+ exports.applyAssistantDisplayTableToResponseForTesting = applyAssistantDisplayTableToResponseForTesting;
124
125
  exports.resolveAssistantReadDisplayMaxRows = resolveAssistantReadDisplayMaxRows;
125
126
  exports.normalizeAssistantNowExprPlaceholders = normalizeAssistantNowExprPlaceholders;
126
127
  exports.repairAssistantPositionalPathSegmentsInPipeline = repairAssistantPositionalPathSegmentsInPipeline;
@@ -615,6 +616,7 @@ function buildAssistantSystemPromptText(platformPrompt) {
615
616
  '- If a report-* collection is unavailable, keep using REPORT_BUILDER_READ/REPORT_BUILDER_AGG with the best-matched collection family; the bridge can safely fall back to direct collection access.',
616
617
  '- Map user wording to internal collections/fields yourself. Do not ask for property names unless required to run a query.',
617
618
  '- Use app heuristics and context hints as weak signals only. Verify collection and field guesses before relying on them.',
619
+ '- Distinguish the root business object from related measured details. Example: if the user asks for jobs and chemicals sent, jobs/work orders are the root and chemicals are joined detail, not necessarily the root collection.',
618
620
  '- Do not guess or invent collections/fields. If unsure, verify in the codebase or run a small REPORT_BUILDER_READ probe (limit 1-5) to learn the shape.',
619
621
  '- Prefer running a small REPORT_BUILDER_READ probe over asking multiple questions.',
620
622
  '- Form a concrete hypothesis about collection/field/date mapping, then verify it with codebase context or a tiny probe before answering.',
@@ -684,6 +686,7 @@ function buildAssistantSystemPromptText(platformPrompt) {
684
686
  '- For performance, keep pipelines minimal: avoid $push arrays or large fields unless the user explicitly asks for them.',
685
687
  '- For completion metrics (ex: "completed per day"), filter by completed status when applicable and use completion date fields; if completion dates are missing, fall back to createdAt/date_created and note the fallback.',
686
688
  '- Before issuing REPORT_BUILDER_READ or REPORT_BUILDER_AGG, verify the collection name and key fields by checking collection/model definitions in the current app (look for "collectionName:" and date fields like date_created/date_completed/createdAt). Do not invent collection names.',
689
+ '- When a request names multiple business concepts, root the query in the concept being counted/listed/summarized, then use $lookup/$unwind for related detail concepts.',
687
690
  '- For creation-date questions when both date_created and createdAt exist, match both with $or so results are not missed.',
688
691
  '- When grouping by fields that can be arrays (drivers, deliveries, routes, chemicals), $unwind first and group by both id and name when available.',
689
692
  '- Use REPORT_BUILDER_READ/REPORT_BUILDER_AGG only to produce summaries/snapshots/health checks (not raw dumps) when permitted.',
@@ -1897,7 +1900,7 @@ function executeAiAssistantCodexRun(payload, context) {
1897
1900
  insertResult = _d.sent();
1898
1901
  assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
1899
1902
  enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
1900
- var runStart, fastModeEnabled, alwaysAllowProbeEnabled, plannerEnabled, runBudgetMs, assistantMongoMaxTimeMs, assistantSystemPrompt, runDeadlineMs, steps, recordStep, progressTracker, streamProgress, remainingRunBudgetMs, hasRunBudget, applyCodexStageBudget, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, heuristicDirectivePrecomputed, usedDeterministicHeuristicFastPath, requestedTimeGrain, requestedBreakdownDimensions, enforceDatedDirective, enforceGroupedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, toolTelemetry, termHints, collectionHints, fieldHints, schemaHints, methodHints, publicationHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerUsed, plannerSkipReason, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, surfaceHints, _a, allowedRoutes, rankedAllowedRoutes, routeHints, appCollectionHints, rankedCollectionHints, rankedCollections, hintCollections, schemaHintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, plannerRunOptions, shouldRunPlanner, plannerBudgetAvailable, plannerPrompt, plannerStart, _b, preferListDirective, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, heuristicDirectiveFastPath, directivePrompt, directiveStart, forcedDirective, _c, initialStart, extractedDirective, error_2, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, groupedDirectivePrompt, groupedStart, groupedDirectiveText, groupedDirective, _g, heuristicDirective, requestedCollection, allowCollectionOverride, cleanedResponseText, deniedModuleByIntent, permissionLabel, effectiveDirective, rankedCollections_1, directiveHintsBase_1, buildToolRequestForDirective, executionDirective, probeFieldHints, probeEnabled, probeBudgetAllowed, probeDirective, probeRequest, probeStart, probeResponse, _h, probeDurationMs, probeRowCount, probeRewrite, probeError_1, probeDurationMs, probeErrorMessage, toolRequest, requestedToolCollection, toolStart, toolResponse, _j, toolDurationMs, toolPayload, resolvedToolCollection, zeroRowResult, followupCodexEnabled, skipFollowupCodex, followupPrompt, followupStart, followupText, _k, error_3, errorMessage, existingFinal, error_4, runBudgetExceeded, includeToolExecutionTelemetry, toolExecutionTelemetry, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload, finalizeError_1, failedAt, fallbackContent, failureMetadata, persistError_1, _l;
1903
+ var runStart, fastModeEnabled, alwaysAllowProbeEnabled, plannerEnabled, runBudgetMs, assistantMongoMaxTimeMs, assistantSystemPrompt, runDeadlineMs, steps, recordStep, progressTracker, streamProgress, remainingRunBudgetMs, hasRunBudget, applyCodexStageBudget, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, heuristicDirectivePrecomputed, usedDeterministicHeuristicFastPath, requestedTimeGrain, requestedBreakdownDimensions, enforceDatedDirective, enforceGroupedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, toolTelemetry, termHints, collectionHints, fieldHints, schemaHints, methodHints, publicationHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerUsed, plannerSkipReason, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, surfaceHints, _a, allowedRoutes, rankedAllowedRoutes, routeHints, appCollectionHints, rankedCollectionHints, rankedCollections, hintCollections, schemaHintCollections, assistantContext, hasDeterministicHeuristicFastPath, prompt_1, workspaceRoot, codexConfig, runOptions, plannerRunOptions, shouldRunPlanner, plannerBudgetAvailable, plannerPrompt, plannerStart, _b, preferListDirective, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, heuristicDirectiveFastPath, directivePrompt, directiveStart, forcedDirective, _c, initialStart, extractedDirective, error_2, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, groupedDirectivePrompt, groupedStart, groupedDirectiveText, groupedDirective, _g, heuristicDirective, requestedCollection, allowCollectionOverride, cleanedResponseText, deniedModuleByIntent, permissionLabel, effectiveDirective, rankedCollections_1, directiveHintsBase_1, buildToolRequestForDirective, executionDirective, probeFieldHints, aggregateProbeDisabled, probeEnabled, probeBudgetAllowed, probeDirective, probeRequest, probeStart, probeResponse, _h, probeDurationMs, probeRowCount, probeRewrite, probeError_1, probeDurationMs, probeErrorMessage, toolRequest, requestedToolCollection, toolStart, toolResponse, _j, toolDurationMs, toolPayload, resolvedToolCollection, zeroRowResult, followupCodexEnabled, skipFollowupCodex, followupPrompt, followupStart, followupText, _k, error_3, errorMessage, existingFinal, error_4, runBudgetExceeded, includeToolExecutionTelemetry, toolExecutionTelemetry, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload, finalizeError_1, failedAt, fallbackContent, failureMetadata, persistError_1, _l;
1901
1904
  var _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21;
1902
1905
  return __generator(this, function (_22) {
1903
1906
  switch (_22.label) {
@@ -2644,7 +2647,8 @@ function executeAiAssistantCodexRun(payload, context) {
2644
2647
  };
2645
2648
  return [3 /*break*/, 63];
2646
2649
  case 40:
2647
- probeEnabled = AI_ASSISTANT_TOOL_MAX_STEPS > 1;
2650
+ aggregateProbeDisabled = executionDirective.type === 'aggregate' && !alwaysAllowProbeEnabled;
2651
+ probeEnabled = AI_ASSISTANT_TOOL_MAX_STEPS > 1 && !aggregateProbeDisabled;
2648
2652
  probeBudgetAllowed = alwaysAllowProbeEnabled
2649
2653
  || hasRunBudget('Grabbing Data: probe', AI_ASSISTANT_MONGO_MIN_STAGE_BUDGET_MS);
2650
2654
  if (!(probeEnabled && probeBudgetAllowed)) return [3 /*break*/, 50];
@@ -2731,6 +2735,12 @@ function executeAiAssistantCodexRun(payload, context) {
2731
2735
  skippedReason: 'run_budget_exhausted'
2732
2736
  };
2733
2737
  }
2738
+ else if (aggregateProbeDisabled) {
2739
+ toolTelemetry.probe = {
2740
+ attempted: false,
2741
+ skippedReason: 'aggregate_probe_disabled'
2742
+ };
2743
+ }
2734
2744
  _22.label = 51;
2735
2745
  case 51:
2736
2746
  if (!(!alwaysAllowProbeEnabled && !hasRunBudget('Grabbing Data: final', AI_ASSISTANT_MONGO_MIN_STAGE_BUDGET_MS))) return [3 /*break*/, 52];
@@ -6644,10 +6654,10 @@ function isAssistantDeterministicHeuristicDirective(directive) {
6644
6654
  }
6645
6655
  function buildAssistantHeuristicDirective(message, collectionHints, collectionNames, appId) {
6646
6656
  if (collectionNames === void 0) { collectionNames = []; }
6647
- void collectionNames;
6648
6657
  if (!normalizeOptionalString(message)) {
6649
6658
  return null;
6650
6659
  }
6660
+ void collectionNames;
6651
6661
  var schemaHoursDirective = resolveAssistantDeterministicHeuristicEnabled(AI_ASSISTANT_HEURISTIC_ID_SCHEMA_HOURS_USER_TIME, appId)
6652
6662
  ? buildAssistantGenericHoursDirective(message, collectionHints, appId)
6653
6663
  : null;
@@ -6695,6 +6705,9 @@ function resolveDefaultAssistantPermissionView(collection) {
6695
6705
  if (base.startsWith('employee')) {
6696
6706
  return '/employee/list';
6697
6707
  }
6708
+ if (base === 'jobs' || base === 'job' || base.startsWith('job-') || base.startsWith('jobs-')) {
6709
+ return '/job/list';
6710
+ }
6698
6711
  if (/work[-_/ ]?orders?|maintenance[-_/ ]?orders?|repair[-_/ ]?orders?/.test(base)) {
6699
6712
  return '/order/list';
6700
6713
  }
@@ -10082,30 +10095,7 @@ function applyAssistantDisplayColumnHints(value, display) {
10082
10095
  }
10083
10096
  return renameAssistantDisplayColumn(display, display.columns[0], labelHint);
10084
10097
  }
10085
- function resolveAssistantEmptyDisplayColumns(value) {
10086
- var labelHint = resolveAssistantDisplayTemporalLabelHint(value);
10087
- if (labelHint) {
10088
- if (labelHint === 'Customer') {
10089
- var requestedMonths = resolveAssistantRequestedMonthBucketsFromMessage(value);
10090
- if (requestedMonths.length >= 3) {
10091
- return __spreadArray([labelHint], __read(requestedMonths), false);
10092
- }
10093
- var looseMonthMatch = value.match(/\b(?:last|past|previous|over\s+the\s+last)\s+(\d+)\s+(?:full\s+calendar\s+|calendar\s+|full\s+)?months?\b/i);
10094
- var looseMonthCount = (looseMonthMatch === null || looseMonthMatch === void 0 ? void 0 : looseMonthMatch[1]) ? Number(looseMonthMatch[1]) : Number.NaN;
10095
- if (Number.isFinite(looseMonthCount) && looseMonthCount > 0) {
10096
- var inferred = buildAssistantExpectedMonthBuckets((0, common_1.round)(looseMonthCount), 'full_month');
10097
- if (inferred.length >= 3) {
10098
- return __spreadArray([labelHint], __read(inferred), false);
10099
- }
10100
- }
10101
- return [labelHint, 'Details'];
10102
- }
10103
- return [labelHint, 'Total Revenue'];
10104
- }
10105
- return ['Result', 'Details'];
10106
- }
10107
10098
  function applyAssistantDisplayTableToResponse(value, display) {
10108
- var _a;
10109
10099
  if (!display || !Array.isArray(display.rows)) {
10110
10100
  return value;
10111
10101
  }
@@ -10115,26 +10105,6 @@ function applyAssistantDisplayTableToResponse(value, display) {
10115
10105
  var rowCount = typeof normalizedDisplay.rowCount === 'number' && normalizedDisplay.rowCount > 0
10116
10106
  ? normalizedDisplay.rowCount
10117
10107
  : 0;
10118
- var fallbackColumns = Array.isArray(normalizedDisplay.columns) && normalizedDisplay.columns.length
10119
- ? normalizedDisplay.columns
10120
- : resolveAssistantEmptyDisplayColumns(cleaned_1 || value);
10121
- var normalizedColumns = fallbackColumns.length === 1
10122
- ? __spreadArray(__spreadArray([], __read(fallbackColumns), false), ['Value'], false) : fallbackColumns;
10123
- var rowSummary = [(_a = {},
10124
- _a[normalizedColumns[0]] = rowCount > 0 ? 'Rows matched' : 'No rows matched',
10125
- _a[normalizedColumns[1]] = rowCount,
10126
- _a)];
10127
- var tableDisplay = {
10128
- columns: normalizedColumns,
10129
- rows: rowSummary,
10130
- rowCount: rowCount,
10131
- truncated: false,
10132
- includeIds: false
10133
- };
10134
- var emptyTable = formatDisplayTableMarkdown(tableDisplay);
10135
- if (!emptyTable) {
10136
- return cleaned_1 || value;
10137
- }
10138
10108
  var noRowsNote = rowCount > 0 ? '' : 'No rows matched your request.';
10139
10109
  var alreadyExplainsNoRows = /\bno (?:matching )?rows?(?: matched| were returned)?\b/i.test(cleaned_1);
10140
10110
  var base = cleaned_1
@@ -10142,13 +10112,7 @@ function applyAssistantDisplayTableToResponse(value, display) {
10142
10112
  ? "".concat(cleaned_1.trim(), "\n\n").concat(noRowsNote).trim()
10143
10113
  : cleaned_1.trim())
10144
10114
  : noRowsNote;
10145
- if (!cleaned_1) {
10146
- if (!base) {
10147
- return emptyTable;
10148
- }
10149
- return "".concat(base, "\n\n").concat(emptyTable).trim();
10150
- }
10151
- return "".concat(base, "\n\n").concat(emptyTable).trim();
10115
+ return base || value;
10152
10116
  }
10153
10117
  var table = formatDisplayTableMarkdown(normalizedDisplay);
10154
10118
  if (!table) {
@@ -10160,6 +10124,9 @@ function applyAssistantDisplayTableToResponse(value, display) {
10160
10124
  }
10161
10125
  return "".concat(cleaned.trim(), "\n\n").concat(table).trim();
10162
10126
  }
10127
+ function applyAssistantDisplayTableToResponseForTesting(value, display) {
10128
+ return applyAssistantDisplayTableToResponse(value, display);
10129
+ }
10163
10130
  function escapeMarkdownCell(value) {
10164
10131
  var raw = value === null || value === undefined ? '' : String(value);
10165
10132
  return raw.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').trim();
@@ -15949,6 +15916,32 @@ function resolveCollectionOverrideWithContext(params) {
15949
15916
  }
15950
15917
  }
15951
15918
  var primaryCollectionHint = collectionHints[0] || '';
15919
+ var requestedMatchesPermissionRoute = !!(requested
15920
+ && permissionView
15921
+ && (isAssistantCollectionInHintFamilies(requested, routeHintCollections)
15922
+ || doesAssistantPermissionRouteMatchCollection(permissionView, requested)));
15923
+ var primaryHintMatchesPermissionRoute = !!(primaryCollectionHint
15924
+ && permissionView
15925
+ && (isAssistantCollectionInHintFamilies(primaryCollectionHint, routeHintCollections)
15926
+ || doesAssistantPermissionRouteMatchCollection(permissionView, primaryCollectionHint)));
15927
+ if (requestedMatchesPermissionRoute && !primaryHintMatchesPermissionRoute) {
15928
+ return null;
15929
+ }
15930
+ var requestedHintIndex = requested
15931
+ ? collectionHints.findIndex(function (collection) { return isAssistantCollectionInHintFamilies(requested, [collection]); })
15932
+ : -1;
15933
+ if (requestedHintIndex > 0
15934
+ && primaryCollectionHint
15935
+ && !primaryHintMatchesPermissionRoute) {
15936
+ var requestedScore = resolveAssistantCollectionScore(params.collectionRanking, requested);
15937
+ var primaryScore = resolveAssistantCollectionScore(params.collectionRanking, primaryCollectionHint);
15938
+ var scoreGap = primaryScore - requestedScore;
15939
+ if (requestedScore >= AI_ASSISTANT_COLLECTION_OVERRIDE_MIN_SCORE
15940
+ && primaryScore >= AI_ASSISTANT_COLLECTION_OVERRIDE_MIN_SCORE
15941
+ && scoreGap <= AI_ASSISTANT_COLLECTION_OVERRIDE_SCORE_GAP) {
15942
+ return null;
15943
+ }
15944
+ }
15952
15945
  if (primaryCollectionHint
15953
15946
  && requested
15954
15947
  && !isAssistantCollectionInHintFamilies(requested, [primaryCollectionHint])
@@ -19566,7 +19559,7 @@ function buildAssistantContext(input, userContext) {
19566
19559
  : [];
19567
19560
  if (collectionHints.length) {
19568
19561
  lines.push("Collection hints: ".concat(collectionHints.join(', ')));
19569
- lines.push('Collection hints are ordered by relevance; prefer the first hint when it directly matches the user wording and verified schema.');
19562
+ lines.push('Collection hints are candidate roots and related collections; the first hint can be a measured/detail collection. Choose the root collection that owns the primary business object in the request, then join related collections for details/metrics.');
19570
19563
  }
19571
19564
  var termHints = Array.isArray(userContext === null || userContext === void 0 ? void 0 : userContext.termHints)
19572
19565
  ? userContext === null || userContext === void 0 ? void 0 : userContext.termHints.filter(Boolean)