@resolveio/server-lib 22.0.22 → 22.0.23
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.
package/methods/ai-terminal.js
CHANGED
|
@@ -1479,7 +1479,7 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1479
1479
|
insertResult = _d.sent();
|
|
1480
1480
|
assistantMessageId = (insertResult === null || insertResult === void 0 ? void 0 : insertResult._id) || (insertResult === null || insertResult === void 0 ? void 0 : insertResult.insertedId);
|
|
1481
1481
|
enqueueAssistantCodexRun(function () { return __awaiter(_this, void 0, void 0, function () {
|
|
1482
|
-
var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, requestedTimeGrain, enforceDatedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, plannerPrompt, plannerStart, _b, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, directivePrompt, directiveStart, forcedDirective, _c, initialStart, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _g, toolPayload, followupPrompt, followupStart, followupText, _h, error_2, error_3, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
|
|
1482
|
+
var runStart, steps, recordStep, progressTracker, streamProgress, assistantContent, toolResult, assistantDebug, directiveSource, requestClassification, dataQuestion, lastDirective, requestedTimeGrain, enforceDatedDirective, datedDirectiveRetryUsed, datedDirectiveResolved, toolResponseDebug, toolError, termHints, collectionHints, fieldHints, collectionTokenization, collectionRanking, collectionSelection, collectionOverride, collectionNames, plannerEnabled, plannerOutput, plannerRaw, timingBreakdown, codexUsage, accumulateCodexUsage, contextRoute, contextMode, hintSeed, termExpansion, hintText, baseTokens, expandedTokens, baseWeights, expandedWeights, dbName, db, _a, routeHints, rankedCollections, hintCollections, assistantContext, prompt_1, workspaceRoot, codexConfig, runOptions, plannerPrompt, plannerStart, _b, preferListDirective, directiveStyleHint, directivePromptMode, responseText, directiveText, directive, directivePrompt, directiveStart, forcedDirective, _c, initialStart, directivePrompt, forcedStart, forcedDirective, _d, strictDirectivePrompt, strictStart, strictDirectiveText, strictDirective, strictDirectiveIsDated, shouldUseStrictDirective, _e, guardDirectivePrompt, guardStart, guardDirectiveText, guardDirective, _f, requestedCollection, cleanedResponseText, effectiveDirective, toolRequest, toolStart, toolResponse, _g, toolPayload, followupPrompt, followupStart, followupText, _h, error_2, error_3, finishedAt, finalNow, finishedAt, codexMs, draftingMs, finalMetadata, finalUsage, usageClientId, usageError_1, finalAssistantDoc, setPayload;
|
|
1483
1483
|
var _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2;
|
|
1484
1484
|
return __generator(this, function (_3) {
|
|
1485
1485
|
switch (_3.label) {
|
|
@@ -1688,10 +1688,12 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1688
1688
|
requestClassification = classifyAssistantRequestType(message, plannerOutput || undefined);
|
|
1689
1689
|
dataQuestion = requestClassification.dataQuestion;
|
|
1690
1690
|
requestedTimeGrain = resolveAssistantRequestedTimeGrain(message, plannerOutput || undefined);
|
|
1691
|
+
preferListDirective = shouldPreferAssistantListDirective(message, plannerOutput || undefined, requestClassification);
|
|
1691
1692
|
enforceDatedDirective = shouldEnforceAssistantDatedDirective(message, plannerOutput || undefined, requestClassification);
|
|
1692
1693
|
directiveStyleHint = buildAssistantDirectiveStyleHint({
|
|
1693
1694
|
enforceDated: enforceDatedDirective,
|
|
1694
|
-
requestedTimeGrain: requestedTimeGrain
|
|
1695
|
+
requestedTimeGrain: requestedTimeGrain,
|
|
1696
|
+
preferList: preferListDirective
|
|
1695
1697
|
});
|
|
1696
1698
|
directivePromptMode = enforceDatedDirective ? 'aggregate_only' : 'any';
|
|
1697
1699
|
datedDirectiveRetryUsed = false;
|
|
@@ -1974,6 +1976,7 @@ function executeAiAssistantCodexRun(payload, context) {
|
|
|
1974
1976
|
}
|
|
1975
1977
|
assistantContent = applyAssistantVerificationNotes(assistantContent, toolResult);
|
|
1976
1978
|
assistantContent = applyAssistantDatedReportWindow(assistantContent, toolResult);
|
|
1979
|
+
assistantContent = applyAssistantLotNumberResponseGuard(assistantContent, message, toolResult);
|
|
1977
1980
|
assistantContent = normalizeAssistantCurrencyText(assistantContent);
|
|
1978
1981
|
if (aiWorkerDebug) {
|
|
1979
1982
|
finishedAt = Date.now();
|
|
@@ -3236,7 +3239,10 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
3236
3239
|
? documents
|
|
3237
3240
|
: documents.map(function (doc) { return redactSensitiveFields((0, common_1.deepCopy)(doc)); });
|
|
3238
3241
|
includeIds = ((_p = input.options) === null || _p === void 0 ? void 0 : _p.includeIds) === true;
|
|
3239
|
-
displayDocs = sanitizedDocuments
|
|
3242
|
+
displayDocs = sanitizedDocuments.map(function (doc) { return flattenForTable(doc, {
|
|
3243
|
+
includeGroupFromId: true,
|
|
3244
|
+
includeIds: true
|
|
3245
|
+
}); });
|
|
3240
3246
|
return [4 /*yield*/, applyIdLookupDisplayEnrichment({
|
|
3241
3247
|
docs: displayDocs,
|
|
3242
3248
|
collection: collection,
|
|
@@ -3258,7 +3264,7 @@ function executeAiAssistantMongoAggregate(payload, context) {
|
|
|
3258
3264
|
includeIds: includeIds,
|
|
3259
3265
|
maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
|
|
3260
3266
|
maxRows: normalizedOptions.limit || sanitizedDocuments.length,
|
|
3261
|
-
includeGroupFromId:
|
|
3267
|
+
includeGroupFromId: false
|
|
3262
3268
|
});
|
|
3263
3269
|
return [2 /*return*/, __assign(__assign({ documents: sanitizedDocuments, display: display }, (verification ? { verification: verification } : {})), (isSuperAdmin ? {
|
|
3264
3270
|
debug: __assign(__assign({ collection: collection, collectionRequested: rawCollection, collectionResolved: collection, collectionMatched: collectionResolution.matched, collectionCandidates: collectionResolution.candidates, collectionScore: collectionResolution.score, bridge: 'report-builder', database: dbName, query: scopedQuery, options: normalizedOptions.aggregateOptions, originalPipeline: limitedPipeline, executedPipeline: executedPipeline }, (verification ? { verification: verification } : {})), { fallbacks: fallbackMeta })
|
|
@@ -3972,12 +3978,260 @@ function normalizeAssistantPermissionView(permissionView, collection) {
|
|
|
3972
3978
|
}
|
|
3973
3979
|
return normalizedPermission;
|
|
3974
3980
|
}
|
|
3981
|
+
function extractAssistantProjectedColumnsFromDirectivePayload(directivePayload) {
|
|
3982
|
+
var pipeline = Array.isArray(directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.pipeline) ? directivePayload.pipeline : [];
|
|
3983
|
+
var projected = [];
|
|
3984
|
+
pipeline.forEach(function (stage) {
|
|
3985
|
+
if (!stage || typeof stage !== 'object' || Array.isArray(stage) || !stage.$project || typeof stage.$project !== 'object') {
|
|
3986
|
+
return;
|
|
3987
|
+
}
|
|
3988
|
+
Object.keys(stage.$project).forEach(function (key) {
|
|
3989
|
+
if (key === '_id') {
|
|
3990
|
+
return;
|
|
3991
|
+
}
|
|
3992
|
+
var value = stage.$project[key];
|
|
3993
|
+
if (value === 0 || value === false) {
|
|
3994
|
+
return;
|
|
3995
|
+
}
|
|
3996
|
+
var label = formatDisplayColumnName(key) || key;
|
|
3997
|
+
if (label) {
|
|
3998
|
+
projected.push(label);
|
|
3999
|
+
}
|
|
4000
|
+
});
|
|
4001
|
+
});
|
|
4002
|
+
return projected;
|
|
4003
|
+
}
|
|
4004
|
+
function ensureAssistantDisplayColumns(display, requestedColumns) {
|
|
4005
|
+
if (!display || !Array.isArray(display.columns) || !Array.isArray(display.rows)) {
|
|
4006
|
+
return display;
|
|
4007
|
+
}
|
|
4008
|
+
var normalizedRequested = (Array.isArray(requestedColumns) ? requestedColumns : [])
|
|
4009
|
+
.map(function (column) { return normalizeOptionalString(column); })
|
|
4010
|
+
.filter(Boolean);
|
|
4011
|
+
if (!normalizedRequested.length) {
|
|
4012
|
+
return display;
|
|
4013
|
+
}
|
|
4014
|
+
var existing = new Set(display.columns.map(function (column) { return normalizeFieldMatchKey(column); }));
|
|
4015
|
+
var missing = normalizedRequested.filter(function (column) { return !existing.has(normalizeFieldMatchKey(column)); });
|
|
4016
|
+
if (!missing.length) {
|
|
4017
|
+
return display;
|
|
4018
|
+
}
|
|
4019
|
+
var columns = __spreadArray(__spreadArray([], __read(display.columns), false), __read(missing), false);
|
|
4020
|
+
var rows = display.rows.map(function (row) {
|
|
4021
|
+
var next = __assign({}, (row || {}));
|
|
4022
|
+
missing.forEach(function (column) {
|
|
4023
|
+
if (!Object.prototype.hasOwnProperty.call(next, column)) {
|
|
4024
|
+
next[column] = '';
|
|
4025
|
+
}
|
|
4026
|
+
});
|
|
4027
|
+
return next;
|
|
4028
|
+
});
|
|
4029
|
+
return __assign(__assign({}, display), { columns: columns, rows: rows });
|
|
4030
|
+
}
|
|
4031
|
+
function transformAssistantDisplayForDirective(directive, display) {
|
|
4032
|
+
if (!display || !Array.isArray(display.columns) || !Array.isArray(display.rows)) {
|
|
4033
|
+
return display;
|
|
4034
|
+
}
|
|
4035
|
+
if (!isAssistantDirectiveDated(directive)) {
|
|
4036
|
+
return display;
|
|
4037
|
+
}
|
|
4038
|
+
var pivoted = buildAssistantDatedPivotDisplay(display);
|
|
4039
|
+
return pivoted || display;
|
|
4040
|
+
}
|
|
4041
|
+
function buildAssistantDatedPivotDisplay(display) {
|
|
4042
|
+
var columns = Array.isArray(display === null || display === void 0 ? void 0 : display.columns) ? display.columns : [];
|
|
4043
|
+
var rows = Array.isArray(display === null || display === void 0 ? void 0 : display.rows) ? display.rows : [];
|
|
4044
|
+
if (!columns.length || !rows.length) {
|
|
4045
|
+
return null;
|
|
4046
|
+
}
|
|
4047
|
+
var monthColumn = resolveAssistantPivotMonthColumn(columns, rows);
|
|
4048
|
+
if (!monthColumn) {
|
|
4049
|
+
return null;
|
|
4050
|
+
}
|
|
4051
|
+
var valueColumn = resolveAssistantPivotValueColumn(columns, rows, monthColumn);
|
|
4052
|
+
if (!valueColumn) {
|
|
4053
|
+
return null;
|
|
4054
|
+
}
|
|
4055
|
+
var dimensionColumn = resolveAssistantPivotDimensionColumn(columns, rows, monthColumn, valueColumn);
|
|
4056
|
+
if (!dimensionColumn) {
|
|
4057
|
+
return null;
|
|
4058
|
+
}
|
|
4059
|
+
var monthSet = new Set();
|
|
4060
|
+
var grouped = new Map();
|
|
4061
|
+
rows.forEach(function (row) {
|
|
4062
|
+
var month = normalizeAssistantMonthBucket(row === null || row === void 0 ? void 0 : row[monthColumn]);
|
|
4063
|
+
if (!month) {
|
|
4064
|
+
return;
|
|
4065
|
+
}
|
|
4066
|
+
var dimension = normalizeAssistantPivotDimensionLabel(row === null || row === void 0 ? void 0 : row[dimensionColumn]);
|
|
4067
|
+
var numericValue = resolveAssistantNumericValue(row === null || row === void 0 ? void 0 : row[valueColumn]);
|
|
4068
|
+
if (numericValue === null) {
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
monthSet.add(month);
|
|
4072
|
+
var monthMap = grouped.get(dimension) || new Map();
|
|
4073
|
+
monthMap.set(month, (monthMap.get(month) || 0) + numericValue);
|
|
4074
|
+
grouped.set(dimension, monthMap);
|
|
4075
|
+
});
|
|
4076
|
+
var months = Array.from(monthSet).sort(function (a, b) { return a.localeCompare(b); });
|
|
4077
|
+
if (!months.length || !grouped.size) {
|
|
4078
|
+
return null;
|
|
4079
|
+
}
|
|
4080
|
+
var metricIsCurrency = isAssistantCurrencyColumn(valueColumn);
|
|
4081
|
+
var dimensionValues = Array.from(grouped.keys()).sort(function (a, b) { return a.localeCompare(b); });
|
|
4082
|
+
var pivotRows = dimensionValues.map(function (dimension) {
|
|
4083
|
+
var _a;
|
|
4084
|
+
var nextRow = (_a = {},
|
|
4085
|
+
_a[dimensionColumn] = dimension,
|
|
4086
|
+
_a);
|
|
4087
|
+
var monthMap = grouped.get(dimension) || new Map();
|
|
4088
|
+
months.forEach(function (month) {
|
|
4089
|
+
var value = monthMap.get(month);
|
|
4090
|
+
if (value === undefined) {
|
|
4091
|
+
nextRow[month] = '';
|
|
4092
|
+
return;
|
|
4093
|
+
}
|
|
4094
|
+
if (metricIsCurrency) {
|
|
4095
|
+
nextRow[month] = getAssistantCurrencyFormatter().format(value);
|
|
4096
|
+
return;
|
|
4097
|
+
}
|
|
4098
|
+
nextRow[month] = (0, common_1.round)(value, 2);
|
|
4099
|
+
});
|
|
4100
|
+
return nextRow;
|
|
4101
|
+
});
|
|
4102
|
+
return {
|
|
4103
|
+
columns: __spreadArray([dimensionColumn], __read(months), false),
|
|
4104
|
+
rows: pivotRows,
|
|
4105
|
+
rowCount: pivotRows.length,
|
|
4106
|
+
truncated: display.truncated,
|
|
4107
|
+
includeIds: display.includeIds
|
|
4108
|
+
};
|
|
4109
|
+
}
|
|
4110
|
+
function resolveAssistantPivotMonthColumn(columns, rows) {
|
|
4111
|
+
var loweredColumns = columns.map(function (column) { return normalizeOptionalString(column).toLowerCase(); });
|
|
4112
|
+
var explicitMonthIndex = loweredColumns.findIndex(function (column) { return column.includes('month'); });
|
|
4113
|
+
if (explicitMonthIndex !== -1) {
|
|
4114
|
+
return columns[explicitMonthIndex];
|
|
4115
|
+
}
|
|
4116
|
+
var bestColumn = '';
|
|
4117
|
+
var bestScore = 0;
|
|
4118
|
+
columns.forEach(function (column) {
|
|
4119
|
+
var monthMatches = 0;
|
|
4120
|
+
var nonEmpty = 0;
|
|
4121
|
+
rows.forEach(function (row) {
|
|
4122
|
+
var value = row === null || row === void 0 ? void 0 : row[column];
|
|
4123
|
+
if (value === null || value === undefined || value === '') {
|
|
4124
|
+
return;
|
|
4125
|
+
}
|
|
4126
|
+
nonEmpty += 1;
|
|
4127
|
+
if (normalizeAssistantMonthBucket(value)) {
|
|
4128
|
+
monthMatches += 1;
|
|
4129
|
+
}
|
|
4130
|
+
});
|
|
4131
|
+
if (!nonEmpty) {
|
|
4132
|
+
return;
|
|
4133
|
+
}
|
|
4134
|
+
var score = monthMatches / nonEmpty;
|
|
4135
|
+
if (score > bestScore) {
|
|
4136
|
+
bestScore = score;
|
|
4137
|
+
bestColumn = column;
|
|
4138
|
+
}
|
|
4139
|
+
});
|
|
4140
|
+
return bestScore >= 0.8 ? bestColumn : '';
|
|
4141
|
+
}
|
|
4142
|
+
function resolveAssistantPivotValueColumn(columns, rows, monthColumn) {
|
|
4143
|
+
var bestColumn = '';
|
|
4144
|
+
var bestScore = 0;
|
|
4145
|
+
columns.forEach(function (column) {
|
|
4146
|
+
if (column === monthColumn) {
|
|
4147
|
+
return;
|
|
4148
|
+
}
|
|
4149
|
+
var numericCount = 0;
|
|
4150
|
+
var nonEmptyCount = 0;
|
|
4151
|
+
rows.forEach(function (row) {
|
|
4152
|
+
var value = row === null || row === void 0 ? void 0 : row[column];
|
|
4153
|
+
if (value === null || value === undefined || value === '') {
|
|
4154
|
+
return;
|
|
4155
|
+
}
|
|
4156
|
+
nonEmptyCount += 1;
|
|
4157
|
+
if (resolveAssistantNumericValue(value) !== null) {
|
|
4158
|
+
numericCount += 1;
|
|
4159
|
+
}
|
|
4160
|
+
});
|
|
4161
|
+
if (!nonEmptyCount || !numericCount) {
|
|
4162
|
+
return;
|
|
4163
|
+
}
|
|
4164
|
+
var numericRatio = numericCount / nonEmptyCount;
|
|
4165
|
+
if (numericRatio < 0.8) {
|
|
4166
|
+
return;
|
|
4167
|
+
}
|
|
4168
|
+
var lower = normalizeOptionalString(column).toLowerCase();
|
|
4169
|
+
var semanticBoost = /(revenue|amount|total|sales|billing|paid|grand|cost|fee|charge|profit|count|qty|quantity)/i.test(lower)
|
|
4170
|
+
? 0.2
|
|
4171
|
+
: 0;
|
|
4172
|
+
var currencyBoost = isAssistantCurrencyColumn(lower) ? 0.1 : 0;
|
|
4173
|
+
var score = numericRatio + semanticBoost + currencyBoost;
|
|
4174
|
+
if (score > bestScore) {
|
|
4175
|
+
bestScore = score;
|
|
4176
|
+
bestColumn = column;
|
|
4177
|
+
}
|
|
4178
|
+
});
|
|
4179
|
+
return bestColumn;
|
|
4180
|
+
}
|
|
4181
|
+
function resolveAssistantPivotDimensionColumn(columns, rows, monthColumn, valueColumn) {
|
|
4182
|
+
var candidates = columns.filter(function (column) { return column !== monthColumn && column !== valueColumn; });
|
|
4183
|
+
if (!candidates.length) {
|
|
4184
|
+
return '';
|
|
4185
|
+
}
|
|
4186
|
+
var bestColumn = '';
|
|
4187
|
+
var bestScore = -1;
|
|
4188
|
+
candidates.forEach(function (column) {
|
|
4189
|
+
var lower = normalizeOptionalString(column).toLowerCase();
|
|
4190
|
+
var nonEmpty = 0;
|
|
4191
|
+
var unique = new Set();
|
|
4192
|
+
var numericCount = 0;
|
|
4193
|
+
rows.forEach(function (row) {
|
|
4194
|
+
var value = row === null || row === void 0 ? void 0 : row[column];
|
|
4195
|
+
if (value === null || value === undefined || value === '') {
|
|
4196
|
+
return;
|
|
4197
|
+
}
|
|
4198
|
+
nonEmpty += 1;
|
|
4199
|
+
if (resolveAssistantNumericValue(value) !== null) {
|
|
4200
|
+
numericCount += 1;
|
|
4201
|
+
}
|
|
4202
|
+
unique.add(normalizeAssistantPivotDimensionLabel(value));
|
|
4203
|
+
});
|
|
4204
|
+
if (!nonEmpty || unique.size <= 1) {
|
|
4205
|
+
return;
|
|
4206
|
+
}
|
|
4207
|
+
var numericRatio = numericCount / nonEmpty;
|
|
4208
|
+
if (numericRatio >= 0.5) {
|
|
4209
|
+
return;
|
|
4210
|
+
}
|
|
4211
|
+
var score = unique.size;
|
|
4212
|
+
if (/(customer|client|account|name|company|group|category|type|segment)/i.test(lower)) {
|
|
4213
|
+
score += 1000;
|
|
4214
|
+
}
|
|
4215
|
+
if (lower.includes('id')) {
|
|
4216
|
+
score -= 100;
|
|
4217
|
+
}
|
|
4218
|
+
if (score > bestScore) {
|
|
4219
|
+
bestScore = score;
|
|
4220
|
+
bestColumn = column;
|
|
4221
|
+
}
|
|
4222
|
+
});
|
|
4223
|
+
return bestColumn;
|
|
4224
|
+
}
|
|
4225
|
+
function normalizeAssistantPivotDimensionLabel(value) {
|
|
4226
|
+
var normalized = normalizeOptionalString(value);
|
|
4227
|
+
return normalized || 'Unknown';
|
|
4228
|
+
}
|
|
3975
4229
|
function buildAssistantToolResultPayload(directive, toolResponse) {
|
|
3976
4230
|
var _a, _b, _c;
|
|
3977
4231
|
var directivePayload = directive.payload || {};
|
|
3978
4232
|
var documents = Array.isArray(toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.documents) ? toolResponse.documents : [];
|
|
3979
4233
|
var includeIds = ((_a = directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.options) === null || _a === void 0 ? void 0 : _a.includeIds) === true;
|
|
3980
|
-
var
|
|
4234
|
+
var rawDisplay = (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.display) && typeof toolResponse.display === 'object'
|
|
3981
4235
|
? toolResponse.display
|
|
3982
4236
|
: buildDisplayTable(documents, {
|
|
3983
4237
|
includeIds: includeIds,
|
|
@@ -3985,12 +4239,20 @@ function buildAssistantToolResultPayload(directive, toolResponse) {
|
|
|
3985
4239
|
maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS,
|
|
3986
4240
|
includeGroupFromId: directive.type === 'aggregate'
|
|
3987
4241
|
});
|
|
3988
|
-
var
|
|
4242
|
+
var projectedColumns = extractAssistantProjectedColumnsFromDirectivePayload(directivePayload);
|
|
4243
|
+
var display = ensureAssistantDisplayColumns(rawDisplay, projectedColumns);
|
|
4244
|
+
var transformedDisplay = transformAssistantDisplayForDirective(directive, display);
|
|
4245
|
+
var promptDisplay = trimDisplayTable(transformedDisplay, {
|
|
3989
4246
|
maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
|
|
3990
4247
|
maxRows: AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS
|
|
3991
4248
|
});
|
|
4249
|
+
var responseDisplayMaxRows = resolveAssistantToolResultResponseMaxRows(directive, directivePayload, transformedDisplay.rowCount);
|
|
4250
|
+
var responseDisplay = trimDisplayTable(transformedDisplay, {
|
|
4251
|
+
maxColumns: AI_ASSISTANT_DISPLAY_MAX_COLUMNS,
|
|
4252
|
+
maxRows: responseDisplayMaxRows
|
|
4253
|
+
});
|
|
3992
4254
|
var total = typeof (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.total) === 'number' ? toolResponse.total : null;
|
|
3993
|
-
var rowCount = documents.length ||
|
|
4255
|
+
var rowCount = documents.length || display.rowCount || responseDisplay.rowCount;
|
|
3994
4256
|
var requestedCollection = normalizeOptionalString(directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.collection);
|
|
3995
4257
|
var resolvedCollection = normalizeOptionalString((_b = toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) === null || _b === void 0 ? void 0 : _b.collectionResolved)
|
|
3996
4258
|
|| normalizeOptionalString((_c = toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) === null || _c === void 0 ? void 0 : _c.collection)
|
|
@@ -4003,23 +4265,39 @@ function buildAssistantToolResultPayload(directive, toolResponse) {
|
|
|
4003
4265
|
type: directive.type === 'aggregate' ? 'mongo_agg' : 'mongo_read',
|
|
4004
4266
|
input: directivePayload,
|
|
4005
4267
|
output: {
|
|
4006
|
-
display:
|
|
4268
|
+
display: responseDisplay,
|
|
4007
4269
|
total: total !== null ? total : undefined,
|
|
4008
4270
|
collection: resolvedCollection || undefined,
|
|
4009
4271
|
rowCount: rowCount,
|
|
4010
|
-
columns:
|
|
4011
|
-
truncated:
|
|
4272
|
+
columns: responseDisplay.columns,
|
|
4273
|
+
truncated: responseDisplay.truncated,
|
|
4012
4274
|
verification: verification,
|
|
4013
4275
|
debug: (toolResponse === null || toolResponse === void 0 ? void 0 : toolResponse.debug) && typeof toolResponse.debug === 'object' ? toolResponse.debug : undefined
|
|
4014
4276
|
}
|
|
4015
4277
|
};
|
|
4016
4278
|
return {
|
|
4017
4279
|
result: result,
|
|
4018
|
-
prompt: buildAssistantToolResultPrompt(result)
|
|
4280
|
+
prompt: buildAssistantToolResultPrompt(result, promptDisplay)
|
|
4019
4281
|
};
|
|
4020
4282
|
}
|
|
4021
|
-
function
|
|
4022
|
-
var _a
|
|
4283
|
+
function resolveAssistantToolResultResponseMaxRows(directive, directivePayload, rowCount) {
|
|
4284
|
+
var _a;
|
|
4285
|
+
if (directive.type !== 'aggregate') {
|
|
4286
|
+
return AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS;
|
|
4287
|
+
}
|
|
4288
|
+
var requestedLimit = typeof ((_a = directivePayload === null || directivePayload === void 0 ? void 0 : directivePayload.options) === null || _a === void 0 ? void 0 : _a.limit) === 'number'
|
|
4289
|
+
? Math.min(Math.max((0, common_1.round)(directivePayload.options.limit), 0), AI_ASSISTANT_MONGO_MAX_LIMIT)
|
|
4290
|
+
: 0;
|
|
4291
|
+
if (requestedLimit > 0) {
|
|
4292
|
+
return requestedLimit;
|
|
4293
|
+
}
|
|
4294
|
+
if (typeof rowCount === 'number' && rowCount > 0) {
|
|
4295
|
+
return Math.min(rowCount, AI_ASSISTANT_MONGO_MAX_LIMIT);
|
|
4296
|
+
}
|
|
4297
|
+
return AI_ASSISTANT_DISPLAY_PREVIEW_MAX_ROWS;
|
|
4298
|
+
}
|
|
4299
|
+
function buildAssistantToolResultPrompt(result, displayPreview) {
|
|
4300
|
+
var _a;
|
|
4023
4301
|
var lines = ['Tool Result:'];
|
|
4024
4302
|
lines.push("Type: ".concat(result.type));
|
|
4025
4303
|
if (result.output.collection) {
|
|
@@ -4032,9 +4310,9 @@ function buildAssistantToolResultPrompt(result) {
|
|
|
4032
4310
|
if (Array.isArray(result.output.columns) && result.output.columns.length) {
|
|
4033
4311
|
lines.push("Columns: ".concat(result.output.columns.join(', ')));
|
|
4034
4312
|
}
|
|
4035
|
-
if ((
|
|
4313
|
+
if ((_a = displayPreview === null || displayPreview === void 0 ? void 0 : displayPreview.rows) === null || _a === void 0 ? void 0 : _a.length) {
|
|
4036
4314
|
lines.push('Preview:');
|
|
4037
|
-
lines.push(formatDisplayTableMarkdown(
|
|
4315
|
+
lines.push(formatDisplayTableMarkdown(displayPreview));
|
|
4038
4316
|
}
|
|
4039
4317
|
else {
|
|
4040
4318
|
lines.push('Preview: (no rows)');
|
|
@@ -4086,6 +4364,45 @@ function buildAssistantToolFallbackResponse(result) {
|
|
|
4086
4364
|
}
|
|
4087
4365
|
return lines.join('\n').trim();
|
|
4088
4366
|
}
|
|
4367
|
+
function didAssistantRequestLotOrBatch(message) {
|
|
4368
|
+
var normalized = normalizeOptionalString(message).toLowerCase();
|
|
4369
|
+
if (!normalized) {
|
|
4370
|
+
return false;
|
|
4371
|
+
}
|
|
4372
|
+
return /\b(lot|lots|batch|batches)\b/i.test(normalized);
|
|
4373
|
+
}
|
|
4374
|
+
function didAssistantQueryLotFields(toolResult) {
|
|
4375
|
+
if (!(toolResult === null || toolResult === void 0 ? void 0 : toolResult.input) || typeof toolResult.input !== 'object') {
|
|
4376
|
+
return false;
|
|
4377
|
+
}
|
|
4378
|
+
var serialized = '';
|
|
4379
|
+
try {
|
|
4380
|
+
serialized = JSON.stringify(toolResult.input).toLowerCase();
|
|
4381
|
+
}
|
|
4382
|
+
catch (_a) {
|
|
4383
|
+
serialized = '';
|
|
4384
|
+
}
|
|
4385
|
+
if (!serialized) {
|
|
4386
|
+
return false;
|
|
4387
|
+
}
|
|
4388
|
+
return /(lot[_\s-]?number|containers?\.lot|\.lot\b)/i.test(serialized);
|
|
4389
|
+
}
|
|
4390
|
+
function applyAssistantLotNumberResponseGuard(value, requestMessage, toolResult) {
|
|
4391
|
+
var content = normalizeOptionalString(value);
|
|
4392
|
+
if (!content) {
|
|
4393
|
+
return value || '';
|
|
4394
|
+
}
|
|
4395
|
+
if (!didAssistantRequestLotOrBatch(requestMessage) || !didAssistantQueryLotFields(toolResult)) {
|
|
4396
|
+
return content;
|
|
4397
|
+
}
|
|
4398
|
+
var before = content;
|
|
4399
|
+
var next = content;
|
|
4400
|
+
next = next.replace(/^\s*-\s*If you need lot[^.\n]*re-?run[^\n]*$/gim, '');
|
|
4401
|
+
next = next.replace(/^\s*-\s*.*re-?run[^\n]*lot[^\n]*$/gim, '');
|
|
4402
|
+
next = next.replace(/\bI can re-?run[^.\n]*lot[^.\n]*\.?/gi, '');
|
|
4403
|
+
next = next.replace(/\n{3,}/g, '\n\n').trim();
|
|
4404
|
+
return next || before;
|
|
4405
|
+
}
|
|
4089
4406
|
function applyAssistantVerificationNotes(value, toolResult) {
|
|
4090
4407
|
var _a, _b, _c, _d;
|
|
4091
4408
|
var content = normalizeOptionalString(value);
|
|
@@ -11254,16 +11571,72 @@ function hasAssistantDatedLanguage(message) {
|
|
|
11254
11571
|
];
|
|
11255
11572
|
return patterns.some(function (pattern) { return pattern.test(text); });
|
|
11256
11573
|
}
|
|
11574
|
+
function hasAssistantGroupedLanguage(message) {
|
|
11575
|
+
var text = normalizeOptionalString(message).toLowerCase();
|
|
11576
|
+
if (!text) {
|
|
11577
|
+
return false;
|
|
11578
|
+
}
|
|
11579
|
+
var patterns = [
|
|
11580
|
+
/\bbreakdown\b/i,
|
|
11581
|
+
/\bgroup(?:ed)?\s+by\b/i,
|
|
11582
|
+
/\bby\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
|
|
11583
|
+
/\bper\s+(day|week|month|quarter|year|status|customer|location|type)\b/i,
|
|
11584
|
+
/\bover\s+time\b/i,
|
|
11585
|
+
/\btime\s*series\b/i,
|
|
11586
|
+
/\btrend(?:ing|s)?\b/i,
|
|
11587
|
+
/\bmonth\s+over\s+month\b/i,
|
|
11588
|
+
/\bquarter\s+over\s+quarter\b/i,
|
|
11589
|
+
/\byear\s+over\s+year\b/i
|
|
11590
|
+
];
|
|
11591
|
+
return patterns.some(function (pattern) { return pattern.test(text); });
|
|
11592
|
+
}
|
|
11593
|
+
function shouldPreferAssistantListDirective(message, plannerOutput, requestClassification) {
|
|
11594
|
+
var _a, _b, _c, _d, _e;
|
|
11595
|
+
if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
|
|
11596
|
+
return false;
|
|
11597
|
+
}
|
|
11598
|
+
var text = normalizeOptionalString(message).toLowerCase();
|
|
11599
|
+
if (!text) {
|
|
11600
|
+
return false;
|
|
11601
|
+
}
|
|
11602
|
+
if (hasAssistantGroupedLanguage(text)) {
|
|
11603
|
+
return false;
|
|
11604
|
+
}
|
|
11605
|
+
var plannerGroupBy = normalizeOptionalString((_b = (_a = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _a === void 0 ? void 0 : _a.queryPlan) === null || _b === void 0 ? void 0 : _b.groupBy).toLowerCase();
|
|
11606
|
+
if (plannerGroupBy && plannerGroupBy !== 'none' && plannerGroupBy !== 'null') {
|
|
11607
|
+
return false;
|
|
11608
|
+
}
|
|
11609
|
+
var plannerMetric = normalizeOptionalString((_c = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _c === void 0 ? void 0 : _c.metric).toLowerCase();
|
|
11610
|
+
var plannerLimit = normalizeOptionalNumber((_e = (_d = plannerOutput === null || plannerOutput === void 0 ? void 0 : plannerOutput.dataPlan) === null || _d === void 0 ? void 0 : _d.queryPlan) === null || _e === void 0 ? void 0 : _e.limit) || 0;
|
|
11611
|
+
var hasListVerb = /\b(show|list|display|give|get)\b/i.test(text);
|
|
11612
|
+
var hasLimitCue = /\b(last|latest|recent|top)\s+\d+\b/i.test(text) || plannerLimit > 0;
|
|
11613
|
+
var hasWindowCue = /\b(this\s+(day|week|month|quarter|year)|last\s+\d+\s+(day|days|week|weeks|month|months)|past\s+\d+\s+(day|days|week|weeks|month|months))\b/i.test(text);
|
|
11614
|
+
if (plannerMetric.startsWith('last_') && plannerGroupBy !== 'none') {
|
|
11615
|
+
return true;
|
|
11616
|
+
}
|
|
11617
|
+
return hasListVerb && (hasLimitCue || hasWindowCue);
|
|
11618
|
+
}
|
|
11257
11619
|
function shouldEnforceAssistantDatedDirective(message, plannerOutput, requestClassification) {
|
|
11258
11620
|
if (!(requestClassification === null || requestClassification === void 0 ? void 0 : requestClassification.dataQuestion)) {
|
|
11259
11621
|
return false;
|
|
11260
11622
|
}
|
|
11623
|
+
if (shouldPreferAssistantListDirective(message, plannerOutput, requestClassification)) {
|
|
11624
|
+
return false;
|
|
11625
|
+
}
|
|
11261
11626
|
if (resolveAssistantRequestedTimeGrain(message, plannerOutput)) {
|
|
11262
11627
|
return true;
|
|
11263
11628
|
}
|
|
11264
11629
|
return hasAssistantDatedLanguage(message);
|
|
11265
11630
|
}
|
|
11266
11631
|
function buildAssistantDirectiveStyleHint(params) {
|
|
11632
|
+
if (params.preferList && !params.enforceDated) {
|
|
11633
|
+
return [
|
|
11634
|
+
'Report style intent: List.',
|
|
11635
|
+
'- Prefer REPORT_BUILDER_READ for record-level results (not grouped counts).',
|
|
11636
|
+
'- Apply date window filters and sort by the primary date field descending.',
|
|
11637
|
+
'- If user asks for location, include location name fields (location/location_name) and id_location for lookup fallback; do not return only location_type unless explicitly requested.'
|
|
11638
|
+
].join('\n');
|
|
11639
|
+
}
|
|
11267
11640
|
if (!params.enforceDated) {
|
|
11268
11641
|
return '';
|
|
11269
11642
|
}
|