"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("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 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" && askedAction === "payout"; } if (normalizedIntent === "customer_revenue_and_payments") { return askedDomain === "counterparty_value" && (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"; } return false; } function readDiscoveryTurnMeaning(entryPoint) { const turnInput = toRecordObject(entryPoint?.turn_input); return toRecordObject(turnInput?.turn_meaning_ref); } 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 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 hasRuntimeAdjustedExactReply(input, entryPoint) { if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) { return false; } if (!hasEffectivelyFactualAddressReply(input)) { return false; } const truthGateStatus = toNonEmptyString(input.addressRuntimeMeta?.truth_gate_contract_status); 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); const hasFullConfirmedTruth = truthGateStatus === "full_confirmed" || sourceTruthGateStatus === "full_confirmed" || (coverageStatus === "full" && groundingStatus === "grounded"); if (!hasFullConfirmedTruth) { 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 hasAlignedFactualAddressReply(input, entryPoint) { if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) { return false; } if (!hasEffectivelyFactualAddressReply(input)) { 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; } 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; } return !isDetectedIntentAlignedWithTurnMeaning(detectedIntent, turnMeaning); } function hasMatchedFactualAddressContinuationTarget(input, entryPoint) { if (!hasEffectivelyFactualAddressReply(input)) { return false; } if (hasSemanticConflictWithDiscoveryTurnMeaning(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 hasFullConfirmedFactualAddressReply(input, entryPoint) { if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) { return false; } if (!hasEffectivelyFactualAddressReply(input)) { return false; } if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) { return false; } 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 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 fullConfirmedFactualAddressReply = hasFullConfirmedFactualAddressReply(input, entryPoint); const runtimeAdjustedExactReply = hasRuntimeAdjustedExactReply(input, entryPoint); 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 (matchedFactualAddressContinuationTarget) { pushReason(reasonCodes, "mcp_discovery_response_policy_keep_factual_address_continuation_target"); } if (fullConfirmedFactualAddressReply) { pushReason(reasonCodes, "mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply"); } if (runtimeAdjustedExactReply) { pushReason(reasonCodes, "mcp_discovery_response_policy_keep_runtime_adjusted_exact_reply_over_stale_discovery_turn_meaning"); } 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 (!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) && !alignedFactualAddressReply && !matchedFactualAddressContinuationTarget && !fullConfirmedFactualAddressReply && !runtimeAdjustedExactReply && !(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"); return { schema_version: exports.ASSISTANT_MCP_DISCOVERY_RESPONSE_POLICY_SCHEMA_VERSION, policy_owner: "assistantMcpDiscoveryResponsePolicy", decision: "apply_candidate", applied: true, reply_text: String(candidate.reply_text), reply_source: "mcp_discovery_response_candidate_guarded", candidate, reason_codes: reasonCodes }; }