1152 lines
61 KiB
JavaScript
1152 lines
61 KiB
JavaScript
"use strict";
|
||
Object.defineProperty(exports, "__esModule", { value: true });
|
||
exports.ASSISTANT_MCP_DISCOVERY_RESPONSE_POLICY_SCHEMA_VERSION = void 0;
|
||
exports.applyAssistantMcpDiscoveryResponsePolicy = applyAssistantMcpDiscoveryResponsePolicy;
|
||
const assistantMcpDiscoveryResponseCandidate_1 = require("./assistantMcpDiscoveryResponseCandidate");
|
||
exports.ASSISTANT_MCP_DISCOVERY_RESPONSE_POLICY_SCHEMA_VERSION = "assistant_mcp_discovery_response_policy_v1";
|
||
const ALLOWED_CANDIDATE_STATUSES = new Set([
|
||
"ready_for_guarded_use",
|
||
"checked_sources_only_candidate",
|
||
"clarification_candidate"
|
||
]);
|
||
function toRecordObject(value) {
|
||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||
return null;
|
||
}
|
||
return value;
|
||
}
|
||
function toNonEmptyString(value) {
|
||
if (value === null || value === undefined) {
|
||
return null;
|
||
}
|
||
const text = String(value).trim();
|
||
return text.length > 0 ? text : null;
|
||
}
|
||
function normalizeReasonCode(value) {
|
||
const normalized = value
|
||
.trim()
|
||
.replace(/[^\p{L}\p{N}_.:-]+/gu, "_")
|
||
.replace(/^_+|_+$/g, "")
|
||
.toLowerCase();
|
||
return normalized.length > 0 ? normalized.slice(0, 120) : null;
|
||
}
|
||
function pushReason(target, value) {
|
||
const normalized = normalizeReasonCode(value);
|
||
if (normalized && !target.includes(normalized)) {
|
||
target.push(normalized);
|
||
}
|
||
}
|
||
function hasInternalMechanics(value) {
|
||
const text = value.toLowerCase();
|
||
return (text.includes("mcp fetch failed") ||
|
||
text.includes("this operation was aborted") ||
|
||
text.includes("entity-resolution") ||
|
||
text.includes("could not continue") ||
|
||
text.includes("checked catalog search step") ||
|
||
text.includes("query_documents") ||
|
||
text.includes("query_movements") ||
|
||
text.includes("primitive") ||
|
||
text.includes("pilot_") ||
|
||
text.includes("runtime_") ||
|
||
text.includes("planner_") ||
|
||
text.includes("catalog_") ||
|
||
text.includes("select "));
|
||
}
|
||
function stripRoutineShortAnswerPrefix(value) {
|
||
return String(value ?? "")
|
||
.split(/\r?\n/g)
|
||
.map((line) => line
|
||
.replace(/^((?:\s|\uFEFF)*(?:[-*]\s*)?)(?:\u041a\u043e\u0440\u043e\u0442\u043a\u043e:\s*)+/u, "$1")
|
||
.replace(/(:\s*)\u041a\u043e\u0440\u043e\u0442\u043a\u043e:\s*/u, "$1"))
|
||
.join("\n")
|
||
.trim();
|
||
}
|
||
function isMcpDiscoveryEntryPointContract(value) {
|
||
const record = toRecordObject(value);
|
||
return (record?.schema_version === "assistant_mcp_discovery_runtime_entry_point_v1" &&
|
||
record?.policy_owner === "assistantMcpDiscoveryRuntimeEntryPoint");
|
||
}
|
||
function resolveEntryPoint(input) {
|
||
if (isMcpDiscoveryEntryPointContract(input.entryPoint)) {
|
||
return input.entryPoint;
|
||
}
|
||
const runtimeMetaEntryPoint = input.addressRuntimeMeta?.mcpDiscoveryRuntimeEntryPoint ??
|
||
input.addressRuntimeMeta?.assistantMcpDiscoveryRuntimeEntryPoint ??
|
||
input.addressRuntimeMeta?.assistant_mcp_discovery_entry_point_v1;
|
||
return isMcpDiscoveryEntryPointContract(runtimeMetaEntryPoint) ? runtimeMetaEntryPoint : null;
|
||
}
|
||
function isUnsupportedCurrentTurnBoundary(input) {
|
||
return (input.modeDecisionReason === "unsupported_current_turn_meaning_boundary" ||
|
||
input.livingChatSource === "deterministic_unsupported_current_turn_boundary" ||
|
||
input.currentReplySource === "deterministic_unsupported_current_turn_boundary");
|
||
}
|
||
function isDeterministicBroadBusinessEvaluationReply(input) {
|
||
return (input.livingChatSource === "deterministic_broad_business_evaluation_contract" ||
|
||
input.currentReplySource === "deterministic_broad_business_evaluation_contract");
|
||
}
|
||
function isDiscoveryReadyChatCandidate(input, entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
return (entryPoint?.entry_status === "bridge_executed" &&
|
||
entryPoint.discovery_attempted === true &&
|
||
turnInput?.should_run_discovery === true &&
|
||
(input.livingChatSource === "llm_chat" || input.currentReplySource === "llm_chat"));
|
||
}
|
||
function isDiscoveryReadyDeepCandidate(input, entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
const source = String(input.currentReplySource ?? input.livingChatSource ?? "").trim().toLowerCase();
|
||
return (entryPoint?.entry_status === "bridge_executed" &&
|
||
entryPoint.discovery_attempted === true &&
|
||
turnInput?.should_run_discovery === true &&
|
||
(source === "deep_analysis" || source === "partial_coverage" || source === "normalizer_v2_0_2"));
|
||
}
|
||
function isDiscoveryReadyAddressCandidate(input, entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
const source = String(input.currentReplySource ?? input.livingChatSource ?? "").trim().toLowerCase();
|
||
return (entryPoint?.entry_status === "bridge_executed" &&
|
||
entryPoint.discovery_attempted === true &&
|
||
turnInput?.should_run_discovery === true &&
|
||
(source === "address_lane" || source === "address_exact" || source === "address_query_runtime_v1"));
|
||
}
|
||
function isDetectedIntentAlignedWithTurnMeaning(detectedIntent, turnMeaning) {
|
||
const normalizedIntent = String(detectedIntent ?? "").trim().toLowerCase();
|
||
if (!normalizedIntent) {
|
||
return false;
|
||
}
|
||
const askedDomain = String(toNonEmptyString(turnMeaning?.asked_domain_family) ?? "").trim().toLowerCase();
|
||
const askedAction = String(toNonEmptyString(turnMeaning?.asked_action_family) ?? "").trim().toLowerCase();
|
||
if (normalizedIntent === "counterparty_activity_lifecycle") {
|
||
return (askedDomain === "counterparty_lifecycle" ||
|
||
askedAction === "activity_duration" ||
|
||
askedAction === "age_or_activity_duration");
|
||
}
|
||
if (normalizedIntent === "supplier_payouts_profile") {
|
||
return (askedDomain === "counterparty_value" || askedDomain === "counterparty") && askedAction === "payout";
|
||
}
|
||
if (normalizedIntent === "customer_revenue_and_payments") {
|
||
return ((askedDomain === "counterparty_value" || askedDomain === "counterparty") &&
|
||
(askedAction === "turnover" || askedAction === "counterparty_value_or_turnover"));
|
||
}
|
||
if (normalizedIntent === "receivables_confirmed_as_of_date") {
|
||
return askedDomain === "receivables" || askedAction === "confirmed_snapshot";
|
||
}
|
||
if (normalizedIntent === "payables_confirmed_as_of_date") {
|
||
return askedDomain === "payables" || askedAction === "confirmed_snapshot";
|
||
}
|
||
if (normalizedIntent === "vat_liability_confirmed_for_tax_period") {
|
||
return askedDomain === "vat" && askedAction === "confirmed_tax_period";
|
||
}
|
||
if (normalizedIntent === "vat_payable_confirmed_as_of_date") {
|
||
return askedDomain === "vat" && askedAction === "confirmed_snapshot";
|
||
}
|
||
if (normalizedIntent === "vat_payable_forecast") {
|
||
return askedDomain === "vat" && askedAction === "forecast";
|
||
}
|
||
if (normalizedIntent === "list_documents_by_counterparty") {
|
||
return askedAction === "list_documents" || askedDomain === "counterparty_documents" || askedDomain === "counterparty";
|
||
}
|
||
if (normalizedIntent === "inventory_on_hand_as_of_date" || normalizedIntent === "inventory_aging_by_purchase_date") {
|
||
return askedDomain === "inventory" && askedAction === "confirmed_snapshot";
|
||
}
|
||
if (normalizedIntent === "inventory_purchase_provenance_for_item" ||
|
||
normalizedIntent === "inventory_purchase_documents_for_item" ||
|
||
normalizedIntent === "inventory_sale_trace_for_item" ||
|
||
normalizedIntent === "inventory_margin_ranking_for_nomenclature" ||
|
||
normalizedIntent === "inventory_profitability_for_item" ||
|
||
normalizedIntent === "inventory_purchase_to_sale_chain") {
|
||
return askedDomain === "inventory";
|
||
}
|
||
return false;
|
||
}
|
||
function readDiscoveryTurnMeaning(entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
return toRecordObject(turnInput?.turn_meaning_ref);
|
||
}
|
||
function readDiscoveryDataNeedGraph(entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
return toRecordObject(turnInput?.data_need_graph);
|
||
}
|
||
function isMetadataDiscoveryTurn(entryPoint) {
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const pilot = toRecordObject(bridge?.pilot);
|
||
const reasonCodes = Array.isArray(entryPoint?.reason_codes) ? entryPoint.reason_codes : [];
|
||
return Boolean(toNonEmptyString(turnMeaning?.asked_domain_family) === "metadata" ||
|
||
toNonEmptyString(turnMeaning?.unsupported_but_understood_family) === "1c_metadata_surface" ||
|
||
toNonEmptyString(graph?.business_fact_family) === "schema_surface" ||
|
||
toNonEmptyString(pilot?.pilot_scope) === "metadata_inspection_v1" ||
|
||
reasonCodes.some((reason) => toNonEmptyString(reason) === "mcp_discovery_metadata_signal_detected"));
|
||
}
|
||
function isExplicitMetadataDiscoveryTurn(entryPoint) {
|
||
const turnInput = toRecordObject(entryPoint?.turn_input);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const reasonCodes = [
|
||
...(Array.isArray(entryPoint?.reason_codes) ? entryPoint.reason_codes : []),
|
||
...(Array.isArray(turnInput?.reason_codes) ? turnInput.reason_codes : [])
|
||
];
|
||
const decompositionCandidates = Array.isArray(graph?.decomposition_candidates) ? graph.decomposition_candidates : [];
|
||
return Boolean(toNonEmptyString(turnMeaning?.asked_domain_family) === "metadata" ||
|
||
toNonEmptyString(turnMeaning?.unsupported_but_understood_family) === "1c_metadata_surface" ||
|
||
toNonEmptyString(graph?.business_fact_family) === "schema_surface" ||
|
||
decompositionCandidates.some((candidate) => toNonEmptyString(candidate) === "inspect_metadata_surface") ||
|
||
reasonCodes.some((reason) => toNonEmptyString(reason) === "mcp_discovery_metadata_signal_detected"));
|
||
}
|
||
function isInventoryExactAddressIntent(intent) {
|
||
return /^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_margin_ranking_for_nomenclature|inventory_profitability_for_item|inventory_purchase_to_sale_chain|inventory_aging_by_purchase_date|inventory_on_hand_as_of_date)$/u.test(String(intent ?? ""));
|
||
}
|
||
function hasMetadataDiscoveryPriority(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (!isMetadataDiscoveryTurn(entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!isExplicitMetadataDiscoveryTurn(entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
return !isInventoryExactAddressIntent(detectedIntent);
|
||
}
|
||
function isOpenScopeValueFlowWithoutSubject(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const businessFactFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const subjectCandidates = Array.isArray(graph?.subject_candidates) ? graph.subject_candidates : [];
|
||
const reasonCodes = readStringArray(graph?.reason_codes);
|
||
const clarificationGaps = readStringArray(graph?.clarification_gaps);
|
||
const explicitOrganizationScope = toNonEmptyString(turnMeaning?.explicit_organization_scope);
|
||
return (businessFactFamily === "value_flow" &&
|
||
subjectCandidates.length === 0 &&
|
||
(reasonCodes.includes("data_need_graph_open_scope_total_without_subject") ||
|
||
(Boolean(explicitOrganizationScope) && clarificationGaps.includes("subject"))));
|
||
}
|
||
function needsOpenScopeValueFlowOrganizationClarification(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const businessFactFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const subjectCandidates = Array.isArray(graph?.subject_candidates) ? graph.subject_candidates : [];
|
||
const clarificationGaps = Array.isArray(graph?.clarification_gaps) ? graph.clarification_gaps : [];
|
||
return (businessFactFamily === "value_flow" &&
|
||
subjectCandidates.length === 0 &&
|
||
clarificationGaps.some((gap) => toNonEmptyString(gap) === "organization"));
|
||
}
|
||
function isOpenScopeValueFlowRanking(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const businessFactFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const subjectCandidates = Array.isArray(graph?.subject_candidates) ? graph.subject_candidates : [];
|
||
return businessFactFamily === "value_flow" && subjectCandidates.length === 0 && Boolean(toNonEmptyString(graph?.ranking_need));
|
||
}
|
||
function readDiscoverySelectedChainId(entryPoint) {
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const pilot = toRecordObject(bridge?.pilot);
|
||
const routeCandidate = toRecordObject(bridge?.route_candidate);
|
||
return (toNonEmptyString(routeCandidate?.selected_chain_id) ??
|
||
toNonEmptyString(bridge?.selected_chain_id) ??
|
||
toNonEmptyString(pilot?.selected_chain_id));
|
||
}
|
||
function isValueFlowRankingDiscoveryTurn(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const routeCandidate = toRecordObject(bridge?.route_candidate);
|
||
const selectedChainId = readDiscoverySelectedChainId(entryPoint);
|
||
const graphReasonCodes = readStringArray(graph?.reason_codes);
|
||
return Boolean(toNonEmptyString(graph?.business_fact_family) === "value_flow" &&
|
||
(selectedChainId === "value_flow_ranking" ||
|
||
toNonEmptyString(routeCandidate?.nearest_catalog_chain_template) === "value_flow_ranking" ||
|
||
toNonEmptyString(graph?.ranking_need) === "top_desc" ||
|
||
graphReasonCodes.includes("data_need_graph_ranking_top_desc")));
|
||
}
|
||
function readTruthAnswerShape(input) {
|
||
const directShape = toRecordObject(input.addressRuntimeMeta?.answer_shape_contract);
|
||
if (directShape) {
|
||
return directShape;
|
||
}
|
||
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
|
||
return toRecordObject(truthAnswerPolicy?.answer_shape);
|
||
}
|
||
function hasCurrentClarificationRequiredAddressReply(input) {
|
||
const answerShape = toNonEmptyString(input.addressRuntimeMeta?.answer_shape) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.truth_mode) ??
|
||
toNonEmptyString(readTruthAnswerShape(input)?.answer_shape);
|
||
if (answerShape === "clarification_required") {
|
||
return true;
|
||
}
|
||
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
|
||
const truthGate = toRecordObject(truthAnswerPolicy?.truth_gate);
|
||
const policyAnswerShape = toRecordObject(truthAnswerPolicy?.answer_shape);
|
||
return (toNonEmptyString(truthGate?.truth_mode) === "clarification_required" ||
|
||
toNonEmptyString(policyAnswerShape?.answer_shape) === "clarification_required");
|
||
}
|
||
function hasDiscoveryClarificationCandidatePriorityOverCurrentClarification(input, entryPoint, candidate) {
|
||
if (!hasCurrentClarificationRequiredAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (candidate.candidate_status !== "clarification_candidate") {
|
||
return false;
|
||
}
|
||
if (!candidate.eligible_for_future_hot_runtime || !toNonEmptyString(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const discoveryFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family) ?? toNonEmptyString(graph?.action_family);
|
||
const asksForMovements = discoveryFamily === "movement_evidence" || askedDomain === "movements" || askedAction === "list_movements";
|
||
const truthAnswerShape = readTruthAnswerShape(input);
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const capabilityId = toNonEmptyString(input.addressRuntimeMeta?.capability_id) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.capability_contract_id) ??
|
||
toNonEmptyString(truthAnswerShape?.capability_contract_id);
|
||
const missingFilters = [
|
||
...readStringArray(input.addressRuntimeMeta?.missing_required_filters),
|
||
...readStringArray(input.addressRuntimeMeta?.missing_anchors),
|
||
...readStringArray(toRecordObject(input.addressRuntimeMeta?.capability_binding_contract)?.missing_anchors)
|
||
];
|
||
const staleInventoryItemClarification = Boolean(missingFilters.includes("item") &&
|
||
(detectedIntent?.startsWith("inventory_") ||
|
||
selectedRecipe?.includes("inventory_") ||
|
||
capabilityId?.includes("inventory_")));
|
||
return asksForMovements && staleInventoryItemClarification;
|
||
}
|
||
function hasGroundedMovementCandidatePriorityOverCurrentInventoryItemClarification(input, entryPoint, candidate) {
|
||
if (!hasCurrentClarificationRequiredAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (candidate.candidate_status !== "ready_for_guarded_use") {
|
||
return false;
|
||
}
|
||
if (!candidate.eligible_for_future_hot_runtime || !toNonEmptyString(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (candidate.reply_text && hasInternalMechanics(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const pilot = toRecordObject(bridge?.pilot);
|
||
const handoff = toRecordObject(bridge?.execution_handoff);
|
||
const selectedChainId = readDiscoverySelectedChainId(entryPoint);
|
||
const discoveryFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family) ?? toNonEmptyString(graph?.action_family);
|
||
const asksForMovements = Boolean(selectedChainId === "movement_evidence" ||
|
||
discoveryFamily === "movement_evidence" ||
|
||
askedDomain === "movements" ||
|
||
askedAction === "list_movements");
|
||
const truthAnswerShape = readTruthAnswerShape(input);
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const capabilityId = toNonEmptyString(input.addressRuntimeMeta?.capability_id) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.capability_contract_id) ??
|
||
toNonEmptyString(truthAnswerShape?.capability_contract_id);
|
||
const missingFilters = [
|
||
...readStringArray(input.addressRuntimeMeta?.missing_required_filters),
|
||
...readStringArray(input.addressRuntimeMeta?.missing_anchors),
|
||
...readStringArray(toRecordObject(input.addressRuntimeMeta?.capability_binding_contract)?.missing_anchors)
|
||
];
|
||
const staleInventoryItemClarification = Boolean(missingFilters.includes("item") &&
|
||
(detectedIntent?.startsWith("inventory_") ||
|
||
selectedRecipe?.includes("inventory_") ||
|
||
capabilityId?.includes("inventory_")));
|
||
const mcpExecutionPerformed = handoff?.mcp_execution_performed === true || pilot?.mcp_execution_performed === true;
|
||
const boundedMovementAnswerAllowed = bridge?.user_facing_response_allowed === true && bridge?.business_fact_answer_allowed === true;
|
||
return asksForMovements && staleInventoryItemClarification && mcpExecutionPerformed && boundedMovementAnswerAllowed;
|
||
}
|
||
function hasBusinessOverviewBoundaryCandidatePriorityOverCurrentInventoryItemClarification(input, entryPoint, candidate) {
|
||
if (!hasCurrentClarificationRequiredAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (candidate.candidate_status !== "clarification_candidate" && candidate.candidate_status !== "ready_for_guarded_use") {
|
||
return false;
|
||
}
|
||
if (!candidate.eligible_for_future_hot_runtime || !toNonEmptyString(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (candidate.reply_text && hasInternalMechanics(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const selectedChainId = readDiscoverySelectedChainId(entryPoint);
|
||
const discoveryFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const separateCounterpartyCandidates = readStringArray(turnMeaning?.business_overview_separate_entity_candidates);
|
||
const hasPreviousCounterpartyBundle = Boolean(toRecordObject(turnMeaning?.previous_counterparty_value_flow_bundle) ||
|
||
toRecordObject(turnMeaning?.previous_counterparty_document_bundle));
|
||
const asksForBoundarySummary = Boolean((selectedChainId === "business_overview" ||
|
||
discoveryFamily === "business_overview" ||
|
||
askedDomain === "business_overview") &&
|
||
(separateCounterpartyCandidates.length > 0 || hasPreviousCounterpartyBundle));
|
||
const truthAnswerShape = readTruthAnswerShape(input);
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const capabilityId = toNonEmptyString(input.addressRuntimeMeta?.capability_id) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.capability_contract_id) ??
|
||
toNonEmptyString(truthAnswerShape?.capability_contract_id);
|
||
const missingFilters = [
|
||
...readStringArray(input.addressRuntimeMeta?.missing_required_filters),
|
||
...readStringArray(input.addressRuntimeMeta?.missing_anchors),
|
||
...readStringArray(toRecordObject(input.addressRuntimeMeta?.capability_binding_contract)?.missing_anchors)
|
||
];
|
||
const staleInventoryItemClarification = Boolean(missingFilters.includes("item") &&
|
||
(detectedIntent?.startsWith("inventory_") ||
|
||
selectedRecipe?.includes("inventory_") ||
|
||
capabilityId?.includes("inventory_")));
|
||
return asksForBoundarySummary && staleInventoryItemClarification;
|
||
}
|
||
function hasGroundedValueFlowCandidatePriorityOverCurrentClarification(input, entryPoint, candidate) {
|
||
if (!hasCurrentClarificationRequiredAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (candidate.candidate_status !== "ready_for_guarded_use") {
|
||
return false;
|
||
}
|
||
if (!candidate.hot_runtime_wired || !candidate.eligible_for_future_hot_runtime || !toNonEmptyString(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const pilot = toRecordObject(bridge?.pilot);
|
||
const handoff = toRecordObject(bridge?.execution_handoff);
|
||
const selectedChainId = readDiscoverySelectedChainId(entryPoint);
|
||
const pilotScope = toNonEmptyString(pilot?.pilot_scope);
|
||
const actionFamily = toNonEmptyString(graph?.action_family);
|
||
const comparisonNeed = toNonEmptyString(graph?.comparison_need);
|
||
const valueFlowComparison = Boolean(selectedChainId === "value_flow_comparison" ||
|
||
pilotScope === "counterparty_bidirectional_value_flow_query_movements_v1" ||
|
||
(actionFamily === "net_value_flow" && comparisonNeed === "incoming_vs_outgoing"));
|
||
const mcpExecutionPerformed = handoff?.mcp_execution_performed === true || pilot?.mcp_execution_performed === true;
|
||
const guardedBusinessAnswerAllowed = bridge?.user_facing_response_allowed === true &&
|
||
bridge?.business_fact_answer_allowed === true &&
|
||
(handoff?.can_use_guarded_response === true || toNonEmptyString(bridge?.bridge_status) === "answer_draft_ready");
|
||
return valueFlowComparison && mcpExecutionPerformed && guardedBusinessAnswerAllowed;
|
||
}
|
||
function hasCounterpartyRankingQuestionSignal(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const rawMessage = toNonEmptyString(turnMeaning?.raw_message) ?? "";
|
||
const effectiveMessage = toNonEmptyString(turnMeaning?.effective_message) ?? "";
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family);
|
||
const text = `${rawMessage}\n${effectiveMessage}`.toLowerCase();
|
||
return Boolean(isValueFlowRankingDiscoveryTurn(entryPoint) &&
|
||
(askedDomain === "counterparty_value" || askedDomain === "counterparty") &&
|
||
(askedAction === "turnover" || askedAction === "counterparty_value_or_turnover") &&
|
||
(/\bкто\b/u.test(text) ||
|
||
text.includes("контрагент") ||
|
||
text.includes("клиент") ||
|
||
text.includes("покупател") ||
|
||
text.includes("заказчик") ||
|
||
text.includes("принес") ||
|
||
text.includes("принёс") ||
|
||
text.includes("больше всего") ||
|
||
toNonEmptyString(graph?.ranking_need) === "top_desc"));
|
||
}
|
||
function hasWrongPeriodRankingCurrentReply(input) {
|
||
const currentReply = String(input.currentReply ?? "").toLowerCase();
|
||
return (currentReply.includes("самый доходный год") ||
|
||
currentReply.includes("топ-1 лет") ||
|
||
currentReply.includes("топ-5 лет") ||
|
||
currentReply.includes("топ-10 лет") ||
|
||
/топ-\d+\s+лет/u.test(currentReply) ||
|
||
currentReply.includes("лет по сумме поступлений") ||
|
||
currentReply.includes("год по подтвержденным поступлениям"));
|
||
}
|
||
function hasConfirmedValueFlowRankingEvidence(entryPoint) {
|
||
const bridge = toRecordObject(entryPoint?.bridge);
|
||
const pilot = toRecordObject(bridge?.pilot);
|
||
const handoff = toRecordObject(bridge?.execution_handoff);
|
||
const evidence = toRecordObject(pilot?.evidence);
|
||
const confirmedFacts = readStringArray(evidence?.confirmed_facts);
|
||
const mcpExecutionPerformed = handoff?.mcp_execution_performed === true || pilot?.mcp_execution_performed === true;
|
||
const businessAnswerAllowed = bridge?.user_facing_response_allowed === true && bridge?.business_fact_answer_allowed === true;
|
||
const confirmedRankingEvidence = Boolean(toNonEmptyString(evidence?.evidence_status) === "confirmed" ||
|
||
toNonEmptyString(evidence?.answer_permission) === "confirmed_answer" ||
|
||
confirmedFacts.some((fact) => /ranked by counterparty|рейтинг.*контрагент/iu.test(fact)));
|
||
return mcpExecutionPerformed && businessAnswerAllowed && confirmedRankingEvidence;
|
||
}
|
||
function hasGroundedValueFlowRankingCandidatePriorityOverCurrentExactReply(input, entryPoint, candidate) {
|
||
if (candidate.candidate_status !== "ready_for_guarded_use") {
|
||
return false;
|
||
}
|
||
if (!candidate.eligible_for_future_hot_runtime || !toNonEmptyString(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (candidate.reply_text && hasInternalMechanics(candidate.reply_text)) {
|
||
return false;
|
||
}
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
return Boolean(hasCounterpartyRankingQuestionSignal(entryPoint) &&
|
||
hasWrongPeriodRankingCurrentReply(input) &&
|
||
hasConfirmedValueFlowRankingEvidence(entryPoint));
|
||
}
|
||
function hasEffectivelyFactualAddressReply(input) {
|
||
if (toNonEmptyString(input.currentReplyType) === "factual") {
|
||
return true;
|
||
}
|
||
const truthAnswerShape = readTruthAnswerShape(input);
|
||
return toNonEmptyString(truthAnswerShape?.reply_type) === "factual";
|
||
}
|
||
function readStateTransitionReasonCodes(input) {
|
||
const directTransition = toRecordObject(input.addressRuntimeMeta?.assistant_state_transition_v1);
|
||
const fallbackTransition = toRecordObject(input.addressRuntimeMeta?.state_transition_contract);
|
||
const stateTransition = directTransition ?? fallbackTransition;
|
||
if (!stateTransition || !Array.isArray(stateTransition.reason_codes)) {
|
||
return [];
|
||
}
|
||
return stateTransition.reason_codes
|
||
.map((item) => toNonEmptyString(item))
|
||
.filter((item) => Boolean(item));
|
||
}
|
||
function hasFullConfirmedTruth(input) {
|
||
const truthGateStatus = toNonEmptyString(input.addressRuntimeMeta?.truth_gate_contract_status);
|
||
if (truthGateStatus === "full_confirmed") {
|
||
return true;
|
||
}
|
||
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
|
||
const truthGate = toRecordObject(truthAnswerPolicy?.truth_gate);
|
||
const sourceTruthGateStatus = toNonEmptyString(truthGate?.source_truth_gate_status);
|
||
const coverageStatus = toNonEmptyString(truthGate?.coverage_status);
|
||
const groundingStatus = toNonEmptyString(truthGate?.grounding_status);
|
||
return sourceTruthGateStatus === "full_confirmed" || (coverageStatus === "full" && groundingStatus === "grounded");
|
||
}
|
||
function readStringArray(value) {
|
||
return Array.isArray(value)
|
||
? value.map((item) => toNonEmptyString(item)).filter((item) => Boolean(item))
|
||
: [];
|
||
}
|
||
function hasConfirmedAddressExecution(input) {
|
||
const mcpCallStatus = toNonEmptyString(input.addressRuntimeMeta?.mcp_call_status);
|
||
const truthMode = toNonEmptyString(input.addressRuntimeMeta?.truth_mode);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const bindingStatus = toNonEmptyString(input.addressRuntimeMeta?.capability_binding_status);
|
||
const bindingViolations = readStringArray(input.addressRuntimeMeta?.capability_binding_violations);
|
||
return Boolean(mcpCallStatus === "matched_non_empty" &&
|
||
truthMode === "confirmed" &&
|
||
selectedRecipe?.startsWith("address_") &&
|
||
(bindingStatus === "bound" || bindingStatus === "bound_with_limits") &&
|
||
bindingViolations.length === 0);
|
||
}
|
||
function hasStaleMetadataDiscoveryFallbackAgainstExactAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (!isMetadataDiscoveryTurn(entryPoint) || isExplicitMetadataDiscoveryTurn(entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
return Boolean(detectedIntent &&
|
||
hasConfirmedAddressExecution(input) &&
|
||
isDetectedIntentAlignedWithTurnMeaning(detectedIntent, readDiscoveryTurnMeaning(entryPoint)));
|
||
}
|
||
function hasBusinessOverviewDirectMoneyClarification(entryPoint) {
|
||
const graph = readDiscoveryDataNeedGraph(entryPoint);
|
||
const businessFactFamily = toNonEmptyString(graph?.business_fact_family);
|
||
const reasonCodes = readStringArray(graph?.reason_codes);
|
||
const clarificationGaps = readStringArray(graph?.clarification_gaps);
|
||
return Boolean(businessFactFamily === "business_overview" &&
|
||
reasonCodes.includes("data_need_graph_business_overview_direct_money_answer") &&
|
||
(toNonEmptyString(graph?.ranking_need) || reasonCodes.includes("data_need_graph_ranking_top_desc")) &&
|
||
clarificationGaps.includes("organization"));
|
||
}
|
||
function hasExactValueFlowReplyForBusinessOverviewDirectMoneyNeed(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
return Boolean(detectedIntent === "customer_revenue_and_payments" &&
|
||
hasConfirmedAddressExecution(input) &&
|
||
hasBusinessOverviewDirectMoneyClarification(entryPoint));
|
||
}
|
||
function hasExactBankOperationsAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const source = String(input.currentReplySource ?? input.livingChatSource ?? "").trim().toLowerCase();
|
||
if (source !== "address_query_runtime_v1" && source !== "address_exact" && source !== "address_lane") {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const isBankIntent = detectedIntent === "bank_operations_by_counterparty" || detectedIntent === "bank_operations_by_contract";
|
||
const isBankRecipe = selectedRecipe === "address_bank_operations_by_counterparty_v1" ||
|
||
selectedRecipe === "address_bank_operations_by_contract_v1";
|
||
if (!isBankIntent || !isBankRecipe) {
|
||
return false;
|
||
}
|
||
const grounding = toRecordObject(input.addressRuntimeMeta?.answer_grounding_check);
|
||
const groundingStatus = toNonEmptyString(grounding?.status);
|
||
const mcpCallStatus = toNonEmptyString(input.addressRuntimeMeta?.mcp_call_status);
|
||
const routeMode = toNonEmptyString(input.addressRuntimeMeta?.capability_route_mode);
|
||
return Boolean(mcpCallStatus === "matched_non_empty" ||
|
||
groundingStatus === "grounded" ||
|
||
routeMode === "exact" ||
|
||
hasFullConfirmedTruth(input));
|
||
}
|
||
function hasExactDocumentListAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const source = String(input.currentReplySource ?? input.livingChatSource ?? "").trim().toLowerCase();
|
||
if (source !== "address_query_runtime_v1" && source !== "address_exact" && source !== "address_lane") {
|
||
return false;
|
||
}
|
||
if (hasValueFlowActionConflictWithDiscoveryTurnMeaning(input, entryPoint) ||
|
||
hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint) ||
|
||
hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const isDocumentIntent = detectedIntent === "list_documents_by_counterparty" || detectedIntent === "list_documents_by_contract";
|
||
const isDocumentRecipe = selectedRecipe === "address_documents_by_counterparty_v1" ||
|
||
selectedRecipe === "address_documents_by_contract_v1";
|
||
if (!isDocumentIntent || !isDocumentRecipe) {
|
||
return false;
|
||
}
|
||
const mcpCallStatus = toNonEmptyString(input.addressRuntimeMeta?.mcp_call_status);
|
||
const responseType = toNonEmptyString(input.addressRuntimeMeta?.response_type);
|
||
return Boolean(mcpCallStatus === "matched_non_empty" || responseType === "FACTUAL_LIST" || hasFullConfirmedTruth(input));
|
||
}
|
||
function hasInventoryMarginRankingAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!toNonEmptyString(input.currentReply)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const capabilityId = toNonEmptyString(input.addressRuntimeMeta?.capability_id) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.capability_contract_id);
|
||
return Boolean(detectedIntent === "inventory_margin_ranking_for_nomenclature" ||
|
||
selectedRecipe === "address_inventory_margin_ranking_for_nomenclature_v1" ||
|
||
capabilityId === "inventory_inventory_margin_ranking_for_nomenclature");
|
||
}
|
||
function hasExactInventoryPurchaseToSaleChainAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const source = String(input.currentReplySource ?? input.livingChatSource ?? "").trim().toLowerCase();
|
||
if (source !== "address_query_runtime_v1" && source !== "address_exact" && source !== "address_lane") {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
|
||
const capabilityId = toNonEmptyString(input.addressRuntimeMeta?.capability_id) ??
|
||
toNonEmptyString(input.addressRuntimeMeta?.capability_contract_id);
|
||
if (detectedIntent !== "inventory_purchase_to_sale_chain" &&
|
||
selectedRecipe !== "address_inventory_purchase_to_sale_chain_v1" &&
|
||
capabilityId !== "inventory_inventory_purchase_to_sale_chain") {
|
||
return false;
|
||
}
|
||
const mcpCallStatus = toNonEmptyString(input.addressRuntimeMeta?.mcp_call_status);
|
||
const responseType = toNonEmptyString(input.addressRuntimeMeta?.response_type);
|
||
return Boolean(hasConfirmedAddressExecution(input) || mcpCallStatus === "matched_non_empty" || responseType === "FACTUAL_LIST");
|
||
}
|
||
function hasValueFlowActionConflictWithDiscoveryTurnMeaning(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family);
|
||
if (askedDomain !== "counterparty_value") {
|
||
return false;
|
||
}
|
||
if (askedAction === "net_value_flow") {
|
||
return true;
|
||
}
|
||
if (hasExactBankOperationsAddressReply(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
if (askedAction === "payout") {
|
||
return detectedIntent !== "supplier_payouts_profile";
|
||
}
|
||
return false;
|
||
}
|
||
function hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family);
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
if (!detectedIntent) {
|
||
return false;
|
||
}
|
||
const asksForMovements = askedDomain === "movements" || askedAction === "list_movements";
|
||
const asksForDocuments = askedDomain === "documents" || askedAction === "list_documents";
|
||
const detectedDocumentsLane = detectedIntent === "list_documents_by_counterparty" || detectedIntent === "list_documents_by_contract";
|
||
const detectedCashLane = detectedIntent === "bank_operations_by_counterparty" || detectedIntent === "bank_operations_by_contract";
|
||
return (asksForMovements && detectedDocumentsLane) || (asksForDocuments && detectedCashLane);
|
||
}
|
||
function hasExactMatchedFactualAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasValueFlowActionConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family);
|
||
if (detectedIntent === "inventory_supplier_stock_overlap_as_of_date" &&
|
||
hasConfirmedAddressExecution(input) &&
|
||
(askedDomain === "entity_resolution" || askedAction === "search_business_entity")) {
|
||
return true;
|
||
}
|
||
if (!(isMetadataDiscoveryTurn(entryPoint) && isInventoryExactAddressIntent(detectedIntent))) {
|
||
return false;
|
||
}
|
||
}
|
||
return hasConfirmedAddressExecution(input);
|
||
}
|
||
function hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
return Boolean(isOpenScopeValueFlowRanking(entryPoint) ||
|
||
needsOpenScopeValueFlowOrganizationClarification(entryPoint) ||
|
||
(detectedIntent === "customer_revenue_and_payments" && isOpenScopeValueFlowWithoutSubject(entryPoint)));
|
||
}
|
||
function hasRuntimeAdjustedExactReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasFullConfirmedTruth(input)) {
|
||
return false;
|
||
}
|
||
const truthAnswerShape = readTruthAnswerShape(input);
|
||
const capabilityContractId = toNonEmptyString(truthAnswerShape?.capability_contract_id);
|
||
if (!capabilityContractId) {
|
||
return false;
|
||
}
|
||
return readStateTransitionReasonCodes(input).some((reason) => /^intent_adjusted_to_.+_followup_context$/i.test(reason));
|
||
}
|
||
function hasRuntimeMatchedExactReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasFullConfirmedTruth(input)) {
|
||
return false;
|
||
}
|
||
const reasonCodes = readStateTransitionReasonCodes(input);
|
||
return (reasonCodes.some((reason) => reason === "route_expectation_matched") &&
|
||
reasonCodes.some((reason) => /(?:confirmed_balance_exact|exact_.+_intent|vat_period_inspection_bridge_signal_detected)/iu.test(reason)));
|
||
}
|
||
function hasAlignedFactualAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
return isDetectedIntentAlignedWithTurnMeaning(detectedIntent, readDiscoveryTurnMeaning(entryPoint));
|
||
}
|
||
function hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasRuntimeAdjustedExactReply(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasRuntimeMatchedExactReply(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasExactBankOperationsAddressReply(input, entryPoint)) {
|
||
const askedAction = toNonEmptyString(readDiscoveryTurnMeaning(entryPoint)?.asked_action_family);
|
||
if (askedAction === "net_value_flow") {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
|
||
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
|
||
const askedAction = toNonEmptyString(turnMeaning?.asked_action_family);
|
||
const unsupportedFamily = toNonEmptyString(turnMeaning?.unsupported_but_understood_family);
|
||
if (!detectedIntent || (!askedDomain && !askedAction && !unsupportedFamily)) {
|
||
return false;
|
||
}
|
||
if (isOpenScopeValueFlowRanking(entryPoint)) {
|
||
return true;
|
||
}
|
||
if (needsOpenScopeValueFlowOrganizationClarification(entryPoint)) {
|
||
return true;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return true;
|
||
}
|
||
if (detectedIntent === "customer_revenue_and_payments" &&
|
||
isOpenScopeValueFlowWithoutSubject(entryPoint)) {
|
||
return true;
|
||
}
|
||
return !isDetectedIntentAlignedWithTurnMeaning(detectedIntent, turnMeaning);
|
||
}
|
||
function hasMatchedFactualAddressContinuationTarget(input, entryPoint) {
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const dialogContinuationContract = toRecordObject(input.addressRuntimeMeta?.dialogContinuationContract) ??
|
||
toRecordObject(input.addressRuntimeMeta?.dialog_continuation_contract_v2);
|
||
const targetIntent = toNonEmptyString(dialogContinuationContract?.target_intent);
|
||
return Boolean(detectedIntent && targetIntent && detectedIntent === targetIntent);
|
||
}
|
||
function hasMatchedFactualSuggestedIntentPivotTarget(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
|
||
const dialogContinuationContract = toRecordObject(input.addressRuntimeMeta?.dialogContinuationContract) ??
|
||
toRecordObject(input.addressRuntimeMeta?.dialog_continuation_contract_v2);
|
||
const targetIntent = toNonEmptyString(dialogContinuationContract?.target_intent);
|
||
const decision = toNonEmptyString(dialogContinuationContract?.decision);
|
||
const selectionMode = toNonEmptyString(dialogContinuationContract?.intent_selection_mode);
|
||
const suggestedPivotSignal = dialogContinuationContract?.suggested_intent_pivot_signal === true;
|
||
return Boolean(detectedIntent &&
|
||
targetIntent &&
|
||
detectedIntent === targetIntent &&
|
||
(decision === "switch_to_suggested" ||
|
||
selectionMode === "switch_to_suggested_intent" ||
|
||
suggestedPivotSignal));
|
||
}
|
||
function hasFullConfirmedFactualAddressReply(input, entryPoint) {
|
||
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (!hasEffectivelyFactualAddressReply(input)) {
|
||
return false;
|
||
}
|
||
if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
if (hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint)) {
|
||
return false;
|
||
}
|
||
return hasFullConfirmedTruth(input);
|
||
}
|
||
function applyAssistantMcpDiscoveryResponsePolicy(input) {
|
||
const currentReply = String(input.currentReply ?? "");
|
||
const currentReplySource = toNonEmptyString(input.currentReplySource) ?? toNonEmptyString(input.livingChatSource) ?? "unknown";
|
||
const entryPoint = resolveEntryPoint(input);
|
||
const candidate = (0, assistantMcpDiscoveryResponseCandidate_1.buildAssistantMcpDiscoveryResponseCandidate)(entryPoint);
|
||
const reasonCodes = [...candidate.reason_codes];
|
||
const unsupportedBoundary = isUnsupportedCurrentTurnBoundary(input);
|
||
const deterministicBroadBusinessEvaluationReply = isDeterministicBroadBusinessEvaluationReply(input);
|
||
const discoveryReadyChatCandidate = isDiscoveryReadyChatCandidate(input, entryPoint);
|
||
const discoveryReadyDeepCandidate = isDiscoveryReadyDeepCandidate(input, entryPoint);
|
||
const discoveryReadyAddressCandidate = isDiscoveryReadyAddressCandidate(input, entryPoint);
|
||
const alignedFactualAddressReply = hasAlignedFactualAddressReply(input, entryPoint);
|
||
const semanticConflictWithDiscoveryTurnMeaning = hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint);
|
||
const matchedFactualAddressContinuationTarget = hasMatchedFactualAddressContinuationTarget(input, entryPoint);
|
||
const matchedFactualSuggestedIntentPivotTarget = hasMatchedFactualSuggestedIntentPivotTarget(input, entryPoint);
|
||
const fullConfirmedFactualAddressReply = hasFullConfirmedFactualAddressReply(input, entryPoint);
|
||
const exactMatchedFactualAddressReply = hasExactMatchedFactualAddressReply(input, entryPoint);
|
||
const runtimeAdjustedExactReply = hasRuntimeAdjustedExactReply(input, entryPoint);
|
||
const runtimeMatchedExactReply = hasRuntimeMatchedExactReply(input, entryPoint);
|
||
const staleMetadataDiscoveryFallbackAgainstExactAddressReply = hasStaleMetadataDiscoveryFallbackAgainstExactAddressReply(input, entryPoint);
|
||
const exactValueFlowReplyForBusinessOverviewDirectMoneyNeed = hasExactValueFlowReplyForBusinessOverviewDirectMoneyNeed(input, entryPoint);
|
||
const exactBankOperationsAddressReply = hasExactBankOperationsAddressReply(input, entryPoint);
|
||
const exactDocumentListAddressReply = hasExactDocumentListAddressReply(input, entryPoint);
|
||
const inventoryMarginRankingAddressReply = hasInventoryMarginRankingAddressReply(input, entryPoint);
|
||
const exactInventoryPurchaseToSaleChainAddressReply = hasExactInventoryPurchaseToSaleChainAddressReply(input, entryPoint);
|
||
const openScopeValueFlowDiscoveryPriority = hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint);
|
||
const metadataDiscoveryPriority = hasMetadataDiscoveryPriority(input, entryPoint);
|
||
const valueFlowActionConflictWithDiscoveryTurnMeaning = hasValueFlowActionConflictWithDiscoveryTurnMeaning(input, entryPoint);
|
||
const evidenceLaneConflictWithDiscoveryTurnMeaning = hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint);
|
||
const currentClarificationRequiredAddressReply = hasCurrentClarificationRequiredAddressReply(input);
|
||
const discoveryClarificationCandidatePriority = hasDiscoveryClarificationCandidatePriorityOverCurrentClarification(input, entryPoint, candidate);
|
||
const groundedValueFlowCandidatePriority = hasGroundedValueFlowCandidatePriorityOverCurrentClarification(input, entryPoint, candidate);
|
||
const groundedMovementCandidatePriority = hasGroundedMovementCandidatePriorityOverCurrentInventoryItemClarification(input, entryPoint, candidate);
|
||
const businessOverviewBoundaryCandidatePriority = hasBusinessOverviewBoundaryCandidatePriorityOverCurrentInventoryItemClarification(input, entryPoint, candidate);
|
||
const groundedValueFlowRankingCandidatePriority = hasGroundedValueFlowRankingCandidatePriorityOverCurrentExactReply(input, entryPoint, candidate);
|
||
const currentClarificationProtectsCurrentReply = currentClarificationRequiredAddressReply &&
|
||
!discoveryClarificationCandidatePriority &&
|
||
!groundedValueFlowCandidatePriority &&
|
||
!groundedMovementCandidatePriority &&
|
||
!businessOverviewBoundaryCandidatePriority &&
|
||
!groundedValueFlowRankingCandidatePriority;
|
||
const alignedFactualAddressReplyProtectsCurrent = alignedFactualAddressReply && !groundedValueFlowRankingCandidatePriority;
|
||
const matchedFactualAddressContinuationTargetProtectsCurrent = matchedFactualAddressContinuationTarget && !groundedValueFlowRankingCandidatePriority;
|
||
const fullConfirmedFactualAddressReplyProtectsCurrent = fullConfirmedFactualAddressReply && !groundedValueFlowRankingCandidatePriority;
|
||
const exactMatchedFactualAddressReplyProtectsCurrent = exactMatchedFactualAddressReply && !groundedValueFlowRankingCandidatePriority;
|
||
const exactBankOperationsProtectsCurrent = exactBankOperationsAddressReply &&
|
||
!semanticConflictWithDiscoveryTurnMeaning &&
|
||
!valueFlowActionConflictWithDiscoveryTurnMeaning;
|
||
const exactInventoryChainProtectsCurrent = exactInventoryPurchaseToSaleChainAddressReply &&
|
||
candidate.candidate_status === "clarification_candidate" &&
|
||
valueFlowActionConflictWithDiscoveryTurnMeaning;
|
||
if (!entryPoint) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_no_entry_point");
|
||
}
|
||
if (!unsupportedBoundary) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_not_unsupported_boundary");
|
||
}
|
||
if (!discoveryReadyChatCandidate) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_not_discovery_ready_chat_candidate");
|
||
}
|
||
if (!discoveryReadyDeepCandidate) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_not_discovery_ready_deep_candidate");
|
||
}
|
||
if (!discoveryReadyAddressCandidate) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_not_discovery_ready_address_candidate");
|
||
}
|
||
if (alignedFactualAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_aligned_factual_address_reply");
|
||
}
|
||
if (semanticConflictWithDiscoveryTurnMeaning) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_semantic_conflict_allows_candidate_override");
|
||
}
|
||
if (valueFlowActionConflictWithDiscoveryTurnMeaning) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_value_flow_action_conflict_allows_candidate_override");
|
||
}
|
||
if (evidenceLaneConflictWithDiscoveryTurnMeaning) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_evidence_lane_conflict_allows_candidate_override");
|
||
}
|
||
if (currentClarificationProtectsCurrentReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_current_clarification_required_reply");
|
||
}
|
||
if (discoveryClarificationCandidatePriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_clarification_candidate_priority_over_stale_address_clarification");
|
||
}
|
||
if (groundedValueFlowCandidatePriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_grounded_value_flow_candidate_priority_over_current_clarification");
|
||
}
|
||
if (groundedMovementCandidatePriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_grounded_movement_candidate_priority_over_inventory_item_clarification");
|
||
}
|
||
if (businessOverviewBoundaryCandidatePriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_business_overview_boundary_candidate_priority_over_inventory_item_clarification");
|
||
}
|
||
if (groundedValueFlowRankingCandidatePriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_grounded_value_flow_ranking_candidate_priority_over_current_exact_reply");
|
||
}
|
||
if (openScopeValueFlowDiscoveryPriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_open_scope_value_flow_candidate_priority");
|
||
}
|
||
if (metadataDiscoveryPriority) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_metadata_candidate_priority");
|
||
}
|
||
if (matchedFactualAddressContinuationTarget) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_factual_address_continuation_target");
|
||
}
|
||
if (matchedFactualSuggestedIntentPivotTarget) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_factual_suggested_intent_pivot_target");
|
||
}
|
||
if (fullConfirmedFactualAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply");
|
||
}
|
||
if (exactMatchedFactualAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_matched_factual_address_reply");
|
||
}
|
||
if (runtimeAdjustedExactReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_runtime_adjusted_exact_reply_over_stale_discovery_turn_meaning");
|
||
}
|
||
if (runtimeMatchedExactReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_runtime_matched_exact_reply_over_stale_discovery_turn_meaning");
|
||
}
|
||
if (staleMetadataDiscoveryFallbackAgainstExactAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_address_reply_over_stale_metadata_discovery");
|
||
}
|
||
if (exactValueFlowReplyForBusinessOverviewDirectMoneyNeed) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_value_flow_reply_over_business_overview_direct_money_clarification");
|
||
}
|
||
if (exactBankOperationsProtectsCurrent) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_bank_operations_address_reply");
|
||
}
|
||
if (exactDocumentListAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_document_list_address_reply");
|
||
}
|
||
if (inventoryMarginRankingAddressReply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_inventory_margin_ranking_address_reply");
|
||
}
|
||
if (exactInventoryChainProtectsCurrent) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_exact_inventory_chain_reply_over_value_flow_clarification");
|
||
}
|
||
if (deterministicBroadBusinessEvaluationReply && candidate.candidate_status === "clarification_candidate") {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_broad_business_summary_over_clarification_candidate");
|
||
}
|
||
if (!ALLOWED_CANDIDATE_STATUSES.has(candidate.candidate_status)) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_status_not_allowed");
|
||
}
|
||
if (!candidate.eligible_for_future_hot_runtime) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_not_eligible");
|
||
}
|
||
if (candidate.hot_runtime_wired) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_guarded_hot_wired");
|
||
}
|
||
if (!toNonEmptyString(candidate.reply_text)) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_missing_reply_text");
|
||
}
|
||
if (candidate.reply_text && hasInternalMechanics(candidate.reply_text)) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_contains_internal_mechanics");
|
||
}
|
||
const canApply = Boolean(entryPoint) &&
|
||
(unsupportedBoundary || discoveryReadyChatCandidate || discoveryReadyDeepCandidate || discoveryReadyAddressCandidate) &&
|
||
!alignedFactualAddressReplyProtectsCurrent &&
|
||
!matchedFactualAddressContinuationTargetProtectsCurrent &&
|
||
!matchedFactualSuggestedIntentPivotTarget &&
|
||
!fullConfirmedFactualAddressReplyProtectsCurrent &&
|
||
!exactMatchedFactualAddressReplyProtectsCurrent &&
|
||
!runtimeAdjustedExactReply &&
|
||
!runtimeMatchedExactReply &&
|
||
!staleMetadataDiscoveryFallbackAgainstExactAddressReply &&
|
||
!exactValueFlowReplyForBusinessOverviewDirectMoneyNeed &&
|
||
!exactBankOperationsProtectsCurrent &&
|
||
!exactDocumentListAddressReply &&
|
||
!inventoryMarginRankingAddressReply &&
|
||
!exactInventoryChainProtectsCurrent &&
|
||
!currentClarificationProtectsCurrentReply &&
|
||
!(deterministicBroadBusinessEvaluationReply && candidate.candidate_status === "clarification_candidate") &&
|
||
ALLOWED_CANDIDATE_STATUSES.has(candidate.candidate_status) &&
|
||
candidate.eligible_for_future_hot_runtime &&
|
||
Boolean(toNonEmptyString(candidate.reply_text)) &&
|
||
!hasInternalMechanics(String(candidate.reply_text ?? ""));
|
||
if (!canApply) {
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_kept_current_reply");
|
||
return {
|
||
schema_version: exports.ASSISTANT_MCP_DISCOVERY_RESPONSE_POLICY_SCHEMA_VERSION,
|
||
policy_owner: "assistantMcpDiscoveryResponsePolicy",
|
||
decision: "keep_current_reply",
|
||
applied: false,
|
||
reply_text: currentReply,
|
||
reply_source: currentReplySource,
|
||
candidate,
|
||
reason_codes: reasonCodes
|
||
};
|
||
}
|
||
pushReason(reasonCodes, "mcp_discovery_response_policy_candidate_applied");
|
||
const replyText = stripRoutineShortAnswerPrefix(String(candidate.reply_text));
|
||
return {
|
||
schema_version: exports.ASSISTANT_MCP_DISCOVERY_RESPONSE_POLICY_SCHEMA_VERSION,
|
||
policy_owner: "assistantMcpDiscoveryResponsePolicy",
|
||
decision: "apply_candidate",
|
||
applied: true,
|
||
reply_text: replyText || String(candidate.reply_text),
|
||
reply_source: "mcp_discovery_response_candidate_guarded",
|
||
candidate,
|
||
reason_codes: reasonCodes
|
||
};
|
||
}
|