ARCH: восстановить память discovery-ответов в living chat

This commit is contained in:
2026-04-21 08:56:38 +03:00
parent cd3315e06d
commit b542b65b81
9 changed files with 719 additions and 24 deletions
@@ -1,8 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readAssistantMcpDiscoveryPilotScope = readAssistantMcpDiscoveryPilotScope;
exports.formatIsoDateForReply = formatIsoDateForReply;
exports.readAddressDebugFilters = readAddressDebugFilters;
exports.readAddressDebugItem = readAddressDebugItem;
exports.readAddressDebugCounterparty = readAddressDebugCounterparty;
exports.readAddressDebugOrganization = readAddressDebugOrganization;
exports.readAddressDebugScopedDate = readAddressDebugScopedDate;
exports.readAddressDebugTemporalScope = readAddressDebugTemporalScope;
@@ -41,6 +43,48 @@ function toRecordObject(value) {
}
return value;
}
function readAssistantMcpDiscoveryEntry(debug) {
const entry = toRecordObject(debug?.assistant_mcp_discovery_entry_point_v1);
return fallbackToNonEmptyString(entry?.schema_version) === "assistant_mcp_discovery_runtime_entry_point_v1"
? entry
: null;
}
function readAssistantMcpDiscoveryTurnMeaning(debug) {
const entry = readAssistantMcpDiscoveryEntry(debug);
const turnInput = toRecordObject(entry?.turn_input);
return toRecordObject(turnInput?.turn_meaning_ref);
}
function readAssistantMcpDiscoveryBridge(debug) {
return toRecordObject(readAssistantMcpDiscoveryEntry(debug)?.bridge);
}
function readAssistantMcpDiscoveryPilotScope(debug, toNonEmptyString = fallbackToNonEmptyString) {
const bridge = readAssistantMcpDiscoveryBridge(debug);
const pilot = toRecordObject(bridge?.pilot);
return toNonEmptyString(pilot?.pilot_scope);
}
function formatDiscoveryDateScopeForReply(value) {
const text = fallbackToNonEmptyString(value);
if (!text) {
return null;
}
return formatIsoDateForReply(text) ?? text;
}
function hasGroundedDiscoveryBusinessAnswer(debug, toNonEmptyString = fallbackToNonEmptyString) {
if (!debug || debug.mcp_discovery_response_applied !== true) {
return false;
}
const entry = readAssistantMcpDiscoveryEntry(debug);
const bridge = readAssistantMcpDiscoveryBridge(debug);
const bridgeStatus = toNonEmptyString(bridge?.bridge_status);
const answerDraft = toRecordObject(bridge?.answer_draft);
const answerMode = toNonEmptyString(answerDraft?.answer_mode);
return Boolean(entry &&
toNonEmptyString(entry.entry_status) === "bridge_executed" &&
bridgeStatus === "answer_draft_ready" &&
(bridge?.business_fact_answer_allowed === true ||
answerMode === "confirmed_with_bounded_inference" ||
answerMode === "bounded_inference_only"));
}
function mergeKnownOrganizationsDefault(values) {
return (0, assistantOrganizationMatcher_1.mergeKnownOrganizations)(values);
}
@@ -65,17 +109,43 @@ function readAddressDebugItem(debug, toNonEmptyString = fallbackToNonEmptyString
? toNonEmptyString(debug?.anchor_value_resolved) ?? toNonEmptyString(debug?.anchor_value_raw)
: null));
}
function readAddressDebugCounterparty(debug, toNonEmptyString = fallbackToNonEmptyString) {
const extractedFilters = readAddressDebugFilters(debug);
if (toNonEmptyString(extractedFilters?.counterparty)) {
return toNonEmptyString(extractedFilters?.counterparty);
}
if (String(debug?.anchor_type ?? "") === "counterparty") {
return toNonEmptyString(debug?.anchor_value_resolved) ?? toNonEmptyString(debug?.anchor_value_raw);
}
const discoveryMeaning = readAssistantMcpDiscoveryTurnMeaning(debug);
const explicitEntities = Array.isArray(discoveryMeaning?.explicit_entity_candidates)
? discoveryMeaning?.explicit_entity_candidates
: [];
for (const entity of explicitEntities) {
const text = toNonEmptyString(entity);
if (text) {
return text;
}
}
return null;
}
function readAddressDebugOrganization(debug, toNonEmptyString = fallbackToNonEmptyString) {
const extractedFilters = readAddressDebugFilters(debug);
const rootFrameContext = toRecordObject(debug?.address_root_frame_context);
return toNonEmptyString(extractedFilters?.organization) ?? toNonEmptyString(rootFrameContext?.organization);
const discoveryMeaning = readAssistantMcpDiscoveryTurnMeaning(debug);
return (toNonEmptyString(extractedFilters?.organization) ??
toNonEmptyString(rootFrameContext?.organization) ??
toNonEmptyString(discoveryMeaning?.explicit_organization_scope) ??
toNonEmptyString(debug?.assistant_active_organization) ??
toNonEmptyString(debug?.living_chat_selected_organization));
}
function readAddressDebugScopedDate(debug) {
const extractedFilters = readAddressDebugFilters(debug);
const rootFrameContext = toRecordObject(debug?.address_root_frame_context);
return (formatIsoDateForReply(extractedFilters?.as_of_date) ??
formatIsoDateForReply(rootFrameContext?.as_of_date) ??
formatIsoDateForReply(extractedFilters?.period_to));
formatIsoDateForReply(extractedFilters?.period_to) ??
formatDiscoveryDateScopeForReply(readAssistantMcpDiscoveryTurnMeaning(debug)?.explicit_date_scope));
}
function readAddressDebugTemporalScope(debug, toNonEmptyString = fallbackToNonEmptyString) {
const extractedFilters = readAddressDebugFilters(debug);
@@ -110,6 +180,13 @@ function resolveAddressDebugAnchorContext(debug, toNonEmptyString = fallbackToNo
anchorValue: counterparty
};
}
const discoveryCounterparty = readAddressDebugCounterparty(debug, toNonEmptyString);
if (discoveryCounterparty) {
return {
anchorType: "counterparty",
anchorValue: discoveryCounterparty
};
}
const account = toNonEmptyString(extractedFilters?.account);
if (account) {
return {
@@ -149,6 +226,7 @@ function resolveNavigationSessionContextState(addressNavigationState, toNonEmpty
function resolveAddressDebugContextFacts(debug, toNonEmptyString = fallbackToNonEmptyString) {
return {
item: readAddressDebugItem(debug, toNonEmptyString),
counterparty: readAddressDebugCounterparty(debug, toNonEmptyString),
organization: readAddressDebugOrganization(debug, toNonEmptyString),
scopedDate: readAddressDebugScopedDate(debug)
};
@@ -538,13 +616,12 @@ function isGroundedAddressDebug(debug, toNonEmptyString = fallbackToNonEmptyStri
if (!debug || typeof debug !== "object") {
return false;
}
const executionLane = toNonEmptyString(debug.execution_lane);
if (executionLane !== "address_query") {
return false;
}
const answerGroundingCheck = toRecordObject(debug.answer_grounding_check);
const groundingStatus = toNonEmptyString(answerGroundingCheck?.status);
return groundingStatus === "grounded";
if (groundingStatus === "grounded" && toNonEmptyString(debug.execution_lane) === "address_query") {
return true;
}
return hasGroundedDiscoveryBusinessAnswer(debug, toNonEmptyString);
}
function isGroundedInventoryContextDebug(debug, toNonEmptyString) {
if (!isGroundedAddressDebug(debug, toNonEmptyString)) {
@@ -14,6 +14,62 @@ function toNonEmptyString(value) {
const text = String(value).trim();
return text.length > 0 ? text : null;
}
function toRecordObject(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
return value;
}
function periodPartForRecap(scopedDate) {
if (!scopedDate) {
return "";
}
return /^\d{2}\.\d{2}\.\d{4}$/.test(scopedDate) ? ` на ${scopedDate}` : ` за период ${scopedDate}`;
}
function buildDiscoveryRecapFactLine(input) {
if (!input.debug || !input.counterparty) {
return null;
}
const pilotScope = (0, assistantContinuityPolicy_1.readAssistantMcpDiscoveryPilotScope)(input.debug, toNonEmptyString);
const discoveryEntry = toRecordObject(input.debug.assistant_mcp_discovery_entry_point_v1);
const bridge = toRecordObject(discoveryEntry?.bridge);
const pilot = toRecordObject(bridge?.pilot);
const periodPart = periodPartForRecap(input.scopedDate);
if (pilotScope === "counterparty_lifecycle_query_documents_v1") {
const activityPeriod = toRecordObject(pilot?.derived_activity_period);
const duration = toNonEmptyString(activityPeriod?.duration_human_ru);
return duration
? `смотрели подтвержденную активность по контрагенту «${input.counterparty}»${periodPart} и оценили период взаимодействия примерно как ${duration}`
: `смотрели подтвержденную активность по контрагенту «${input.counterparty}»${periodPart}`;
}
if (pilotScope === "counterparty_supplier_payout_query_movements_v1") {
const flow = toRecordObject(pilot?.derived_value_flow);
const amount = toNonEmptyString(flow?.total_amount_human_ru);
return amount
? `считали исходящие платежи/списания по контрагенту «${input.counterparty}»${periodPart}: ${amount}`
: `считали исходящие платежи/списания по контрагенту «${input.counterparty}»${periodPart}`;
}
if (pilotScope === "counterparty_value_flow_query_movements_v1") {
const flow = toRecordObject(pilot?.derived_value_flow);
const amount = toNonEmptyString(flow?.total_amount_human_ru);
return amount
? `смотрели денежный поток по контрагенту «${input.counterparty}»${periodPart}: ${amount}`
: `смотрели денежный поток по контрагенту «${input.counterparty}»${periodPart}`;
}
if (pilotScope === "counterparty_bidirectional_value_flow_query_movements_v1") {
const flow = toRecordObject(pilot?.derived_bidirectional_value_flow);
const incoming = toRecordObject(flow?.incoming_customer_revenue);
const outgoing = toRecordObject(flow?.outgoing_supplier_payout);
const incomingAmount = toNonEmptyString(incoming?.total_amount_human_ru);
const outgoingAmount = toNonEmptyString(outgoing?.total_amount_human_ru);
const netAmount = toNonEmptyString(flow?.net_amount_human_ru);
if (incomingAmount && outgoingAmount && netAmount) {
return `считали нетто по деньгам с контрагентом «${input.counterparty}»${periodPart}: получили ${incomingAmount}, заплатили ${outgoingAmount}, расчетное нетто ${netAmount}`;
}
return `считали нетто по деньгам с контрагентом «${input.counterparty}»${periodPart}`;
}
return null;
}
function collectMessageSamples(input) {
const values = [
input.rawUserMessage,
@@ -60,7 +116,16 @@ function normalizeRecapIdentity(value) {
function buildRecapFactLine(input) {
const detectedIntent = String(input.debug?.detected_intent ?? "");
const scopedDate = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.debug).scopedDate;
const discoveryFact = buildDiscoveryRecapFactLine({
debug: input.debug,
counterparty: input.counterparty,
scopedDate
});
if (discoveryFact) {
return discoveryFact;
}
const itemPart = input.item ? `по позиции «${input.item}»` : null;
const counterpartyPart = input.counterparty ? `по контрагенту «${input.counterparty}»` : null;
const organizationPart = input.organization ? `по компании «${input.organization}»` : null;
const datePart = scopedDate ? ` на ${scopedDate}` : "";
if (detectedIntent === "inventory_on_hand_as_of_date") {
@@ -87,6 +152,9 @@ function buildRecapFactLine(input) {
if (detectedIntent === "counterparty_activity_lifecycle" && organizationPart) {
return `смотрели активность в базе 1С ${organizationPart}`.trim();
}
if (detectedIntent === "list_documents_by_counterparty" && counterpartyPart) {
return `поднимали документы ${counterpartyPart}${datePart}`.trim();
}
if (detectedIntent === "list_documents_by_counterparty" && organizationPart) {
return `поднимали документы ${organizationPart}${datePart}`.trim();
}
@@ -125,6 +193,7 @@ function collectRecentRecapFacts(input) {
const fact = buildRecapFactLine({
debug: item.debug,
item: debugItem,
counterparty: debugContext.counterparty,
organization: debugOrganization
});
if (!fact || seen.has(fact)) {
@@ -141,6 +210,7 @@ function collectRecentRecapFacts(input) {
function buildAddressMemoryRecapReply(input) {
const contextFacts = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.addressDebug, input.toNonEmptyString);
const item = contextFacts.item;
const counterparty = contextFacts.counterparty;
const organization = input.organization ?? contextFacts.organization;
const scopedDate = contextFacts.scopedDate;
const recapFacts = collectRecentRecapFacts({
@@ -166,6 +236,21 @@ function buildAddressMemoryRecapReply(input) {
"Могу продолжить по ней без переписывания сущности: кто поставил, когда купили, по каким документам или кому продали."
].join(" ");
}
if (counterparty) {
const organizationPart = organization ? ` по компании «${organization}»` : "";
const periodPart = periodPartForRecap(scopedDate);
if (recapFacts.length > 0) {
return [
`Да, помню. По контрагенту «${counterparty}»${organizationPart}${periodPart} мы уже выяснили:`,
...recapFacts.map((fact) => `- ${fact}.`),
"Могу сразу продолжить по нему: поступления, платежи, нетто, помесячную раскладку или границы подтверждения."
].join("\n");
}
return [
`Да, помню. Мы уже смотрели контур по контрагенту «${counterparty}»${organizationPart}${periodPart}.`,
"Могу продолжить по нему без переписывания контекста: поступления, платежи, нетто, документы или пояснение границ ответа."
].join(" ");
}
if (organization || scopedDate) {
const organizationPart = organization ? ` по компании «${organization}»` : "";
const datePart = scopedDate ? ` на ${scopedDate}` : "";
@@ -179,7 +264,35 @@ function buildAddressMemoryRecapReply(input) {
function buildSelectedObjectAnswerInspectionReply(input) {
const contextFacts = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.addressDebug, input.toNonEmptyString);
const itemLabel = contextFacts.item ?? "эта позиция";
const counterpartyLabel = contextFacts.counterparty;
const detectedIntent = String(input.addressDebug?.detected_intent ?? "");
const pilotScope = (0, assistantContinuityPolicy_1.readAssistantMcpDiscoveryPilotScope)(input.addressDebug, input.toNonEmptyString);
const periodPart = periodPartForRecap(contextFacts.scopedDate);
if (counterpartyLabel && pilotScope === "counterparty_bidirectional_value_flow_query_movements_v1") {
return [
`Да, в предыдущем ответе речь шла о двустороннем денежном потоке с контрагентом «${counterpartyLabel}»${periodPart}.`,
"Нетто там означало разницу между тем, что получили, и тем, что заплатили по найденным строкам 1С.",
"Это расчет по проверенному периоду и подтвержденным строкам, а не заявление про весь оборот вне этого окна."
].join(" ");
}
if (counterpartyLabel && pilotScope === "counterparty_supplier_payout_query_movements_v1") {
return [
`Да, в предыдущем ответе речь шла об исходящих платежах/списаниях по контрагенту «${counterpartyLabel}»${periodPart}.`,
"Это сумма по найденным строкам 1С за проверенный период, а не обещание, что за пределами этого окна больше движений не было."
].join(" ");
}
if (counterpartyLabel && pilotScope === "counterparty_value_flow_query_movements_v1") {
return [
`Да, в предыдущем ответе речь шла о денежном потоке по контрагенту «${counterpartyLabel}»${periodPart}.`,
"Это расчет по найденным движениям 1С за проверенный период, а не безусловный итог по всем временам."
].join(" ");
}
if (counterpartyLabel && pilotScope === "counterparty_lifecycle_query_documents_v1") {
return [
`Да, в предыдущем ответе речь шла об активности контрагента «${counterpartyLabel}»${periodPart}.`,
"Это оценка по подтвержденным строкам 1С, а не юридически подтвержденная дата регистрации."
].join(" ");
}
if (detectedIntent === "inventory_sale_trace_for_item") {
return [
`Да, если так прозвучало, это ошибка чтения ответа. «${itemLabel}» здесь не контрагент, а сама позиция, по которой мы смотрели продажу.`,
+1 -5
View File
@@ -3865,11 +3865,7 @@ function findLastGroundedAddressAnswerDebug(items) {
continue;
}
const debug = item.debug;
if (debug.execution_lane !== "address_query") {
continue;
}
const groundingStatus = toNonEmptyString(debug.answer_grounding_check?.status);
if (groundingStatus === "grounded") {
if ((0, assistantContinuityPolicy_1.isGroundedAddressDebug)(debug, toNonEmptyString)) {
return debug;
}
}