NODEDC_1C/llm_normalizer/backend/dist/services/assistantRoutePolicy.js

837 lines
52 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAssistantRoutePolicy = createAssistantRoutePolicy;
// @ts-nocheck
const assistantContinuityPolicy_1 = require("./assistantContinuityPolicy");
const ADDRESS_INTENTS_KEEP_ADDRESS_LANE = new Set([
"period_coverage_profile",
"document_type_and_account_section_profile",
"counterparty_population_and_roles",
"counterparty_activity_lifecycle",
"customer_revenue_and_payments",
"supplier_payouts_profile",
"open_contracts_confirmed_as_of_date",
"list_open_contracts",
"open_items_by_counterparty_or_contract",
"list_payables_counterparties",
"list_receivables_counterparties",
"inventory_on_hand_as_of_date",
"payables_confirmed_as_of_date",
"receivables_confirmed_as_of_date",
"list_documents_by_contract",
"bank_operations_by_contract",
"list_documents_by_counterparty",
"bank_operations_by_counterparty",
"list_contracts_by_counterparty",
"inventory_purchase_provenance_for_item",
"inventory_purchase_documents_for_item",
"inventory_supplier_stock_overlap_as_of_date",
"inventory_sale_trace_for_item",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain",
"inventory_aging_by_purchase_date",
"contract_usage_overview",
"contract_usage_and_value",
"vat_payable_forecast",
"vat_liability_confirmed_for_tax_period",
"vat_payable_confirmed_as_of_date"
]);
const ADDRESS_INTENTS_ALLOW_STRICT_DEEP_INVESTIGATION_BYPASS = new Set([
"inventory_purchase_provenance_for_item",
"inventory_purchase_documents_for_item",
"inventory_sale_trace_for_item",
"inventory_profitability_for_item",
"inventory_purchase_to_sale_chain"
]);
function shouldBypassStrictDeepInvestigationCueForAddressIntent(intent) {
return Boolean(intent && ADDRESS_INTENTS_ALLOW_STRICT_DEEP_INVESTIGATION_BYPASS.has(intent));
}
function createAssistantRoutePolicy(deps) {
const { repairAddressMojibake, findLastGroundedAddressAnswerDebug, findLastOrganizationClarificationAddressDebug, mergeKnownOrganizations, normalizeOrganizationScopeValue, resolveOrganizationSelectionFromMessage, resolveMetaSignalSet, resolveHardMetaMode, isMetaFollowupOverGroundedAnswer, hasDataRetrievalRequestSignal, hasOrganizationFactLookupSignal, hasOrganizationFactFollowupSignal, hasAggregateBusinessAnalyticsSignal, hasStandaloneAddressTopicSignal, hasOpenContractsAddressSignal, detectAddressQuestionMode, resolveAddressIntent, toNonEmptyString, hasStrictDeepInvestigationCue, hasStrongDataIntentSignal, hasAccountingSignal, hasDangerOrCoercionSignal, hasAddressFollowupContextSignal, hasShortDebtMirrorFollowupSignal, isInventorySelectedObjectIntent, hasShortInventoryObjectFollowupSignal, isGroundedInventoryContextDebug, resolveRouteMemorySignals, findLastAddressAssistantItem, resolveAddressToolGateDecision, hasSameDateAccountFollowupSignalForPredecompose, hasLooseAllTimeAddressLookupSignal, hasDeepAnalysisPreferenceSignal, hasDirectDeepAnalysisSignal, compactWhitespace, hasDeepSessionContinuationSignal, resolveLivingAssistantModeDecision, resolveProviderExecutionState } = deps;
function hasInventoryRootRestatementFollowupSignal(text) {
const normalized = compactWhitespace(repairAddressMojibake(String(text ?? "")).toLowerCase()).replace(/ё/g, "е");
if (!normalized) {
return false;
}
if (!/(?:остатк(?:и|ов|ами|ах)?|на\s+складе|склад(?:е|у|ом)?)/iu.test(normalized)) {
return false;
}
const hasRequestCue = /(?:покажи|показать|выведи|список|какие|что\s+по|че\s+по|чё\s+по|тогда\s+покажи)/iu.test(normalized);
const hasTemporalCue = /(?:на\s+эту\s+же\s+дат[ауеы]|на\s+тот\s+же\s+период|за\s+этот\s+же\s+период|за\s+этот\s+период|март|апрел|ма[йя]|июн|июл|август|сентябр|октябр|ноябр|декабр|\b(?:19|20)\d{2}\b)/iu.test(normalized);
return hasRequestCue && hasTemporalCue;
}
function resolveAssistantOrchestrationDecision(input) {
const rawUserMessage = String(input?.rawUserMessage ?? input?.userMessage ?? "");
const effectiveAddressUserMessage = String(input?.effectiveAddressUserMessage ?? rawUserMessage);
const repairedRawUserMessage = repairAddressMojibake(rawUserMessage);
const repairedEffectiveAddressUserMessage = repairAddressMojibake(effectiveAddressUserMessage);
const followupContext = input?.followupContext ?? null;
const llmPreDecomposeMeta = input?.llmPreDecomposeMeta ?? null;
const useMock = Boolean(input?.useMock);
const sessionItems = Array.isArray(input?.sessionItems) ? input.sessionItems : null;
const sessionOrganizationScope = input?.sessionOrganizationScope && typeof input.sessionOrganizationScope === "object"
? input.sessionOrganizationScope
: null;
const organizationAuthority = (0, assistantContinuityPolicy_1.resolveAssistantOrganizationAuthority)({
sessionItems,
sessionKnownOrganizations: Array.isArray(sessionOrganizationScope?.knownOrganizations)
? sessionOrganizationScope.knownOrganizations
: [],
sessionSelectedOrganization: sessionOrganizationScope?.selectedOrganization,
sessionActiveOrganization: sessionOrganizationScope?.activeOrganization,
lastOrganizationClarificationDebug: findLastOrganizationClarificationAddressDebug(sessionItems),
toNonEmptyString,
normalizeOrganizationScopeValue,
mergeKnownOrganizations
});
const continuitySnapshot = organizationAuthority.continuitySnapshot;
const continuityActiveOrganization = organizationAuthority.continuityActiveOrganization;
const lastGroundedAddressDebug = findLastGroundedAddressAnswerDebug(sessionItems) ??
continuitySnapshot.lastGroundedAddressDebug;
const lastOrganizationClarificationDebug = findLastOrganizationClarificationAddressDebug(sessionItems);
const organizationClarificationCandidates = organizationAuthority.organizationClarificationCandidates;
const organizationClarificationSelectionFromScope = organizationAuthority.organizationClarificationSelectionFromScope;
const organizationClarificationSelection = resolveOrganizationSelectionFromMessage(rawUserMessage, organizationClarificationCandidates) ??
resolveOrganizationSelectionFromMessage(repairedRawUserMessage, organizationClarificationCandidates) ??
resolveOrganizationSelectionFromMessage(effectiveAddressUserMessage, organizationClarificationCandidates) ??
resolveOrganizationSelectionFromMessage(repairedEffectiveAddressUserMessage, organizationClarificationCandidates) ??
(organizationClarificationSelectionFromScope &&
organizationClarificationCandidates.some((candidate) => normalizeOrganizationScopeValue(candidate) === organizationClarificationSelectionFromScope)
? organizationClarificationSelectionFromScope
: null);
const metaSignals = resolveMetaSignalSet({
rawUserMessage,
repairedRawUserMessage,
effectiveAddressUserMessage,
repairedEffectiveAddressUserMessage
});
const dataScopeMetaQuery = metaSignals.dataScopeMetaQuery;
const capabilityMetaQuery = metaSignals.capabilityMetaQuery;
const dataRetrievalSignal = hasDataRetrievalRequestSignal(rawUserMessage) ||
hasDataRetrievalRequestSignal(repairedRawUserMessage) ||
hasDataRetrievalRequestSignal(effectiveAddressUserMessage) ||
hasDataRetrievalRequestSignal(repairedEffectiveAddressUserMessage);
const analyticsSample = compactWhitespace(`${repairedRawUserMessage} ${repairedEffectiveAddressUserMessage}`.toLowerCase());
const colloquialCustomerValueSignal = /(?:\u043a\u0442\u043e|\u043a\u043e\u043c\u0443|customer|client|counterparty)/iu.test(analyticsSample) &&
/(?:(?:\u043f\u0440\u0438\u043d\u0435\u0441|\u043f\u0440\u0438\u043d\u0451\u0441|\u0437\u0430\u043d\u0435\u0441|\u0437\u0430\u043d\u0451\u0441).*(?:\u0434\u0435\u043d\u0435\u0433|\u0434\u0435\u043d\u044c\u0433)|(?:\u0434\u0435\u043d\u0435\u0433|\u0434\u0435\u043d\u044c\u0433).*(?:\u043f\u0440\u0438\u043d\u0435\u0441|\u043f\u0440\u0438\u043d\u0451\u0441|\u0437\u0430\u043d\u0435\u0441|\u0437\u0430\u043d\u0451\u0441)|(?:\u0431\u043e\u043b\u044c\u0448\u0435(?:\s+\u0432\u0441\u0435\u0433\u043e)?).*(?:\u0434\u0435\u043d\u0435\u0433|\u0434\u0435\u043d\u044c\u0433))/iu.test(analyticsSample);
const turnoverAggregateSignal = /(?:\u043e\u0431\u043e\u0440\u043e\u0442(?:\u044b)?|\u0432\u044b\u0440\u0443\u0447\u043a|\u0434\u043e\u0445\u043e\u0434|turnover|revenue).*(?:\u0437\u0430\s+\d{4}\s+\u0433\u043e\u0434|\u043f\u0435\u0440\u0438\u043e\u0434|\u0433\u043e\u0434|year|month|quarter)/iu.test(analyticsSample);
const aggregateBusinessAnalyticsBridgeDetected = colloquialCustomerValueSignal || turnoverAggregateSignal;
const aggregateBusinessAnalyticsSignal = hasAggregateBusinessAnalyticsSignal(rawUserMessage) ||
hasAggregateBusinessAnalyticsSignal(repairedRawUserMessage) ||
hasAggregateBusinessAnalyticsSignal(effectiveAddressUserMessage) ||
hasAggregateBusinessAnalyticsSignal(repairedEffectiveAddressUserMessage) ||
aggregateBusinessAnalyticsBridgeDetected;
const standaloneAddressTopicSignal = hasStandaloneAddressTopicSignal(rawUserMessage) ||
hasStandaloneAddressTopicSignal(repairedRawUserMessage) ||
hasStandaloneAddressTopicSignal(effectiveAddressUserMessage) ||
hasStandaloneAddressTopicSignal(repairedEffectiveAddressUserMessage);
const openContractsAddressSignal = hasOpenContractsAddressSignal(rawUserMessage) ||
hasOpenContractsAddressSignal(repairedRawUserMessage) ||
hasOpenContractsAddressSignal(effectiveAddressUserMessage) ||
hasOpenContractsAddressSignal(repairedEffectiveAddressUserMessage);
const modeSample = repairedEffectiveAddressUserMessage || effectiveAddressUserMessage;
const modeDetection = detectAddressQuestionMode(modeSample);
const modeDetectionRaw = detectAddressQuestionMode(repairedRawUserMessage || rawUserMessage);
const resolvedModeDetection = modeDetection.mode === "address_query" ? modeDetection : modeDetectionRaw;
const intentResolution = resolveAddressIntent(modeSample);
const intentResolutionRaw = resolveAddressIntent(repairedRawUserMessage || rawUserMessage);
const resolvedIntentResolution = intentResolution.intent !== "unknown" ? intentResolution : intentResolutionRaw;
const llmContractIntent = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.intent);
const llmPreDecomposeReason = toNonEmptyString(llmPreDecomposeMeta?.reason);
const providerExecution = resolveProviderExecutionState({
useMock,
llmPreDecomposeReason
});
const llmRuntimeUnavailableDetected = providerExecution.llm_runtime_unavailable_detected === true;
const semanticExtractionContract = llmPreDecomposeMeta?.semanticExtractionContract &&
typeof llmPreDecomposeMeta.semanticExtractionContract === "object"
? llmPreDecomposeMeta.semanticExtractionContract
: null;
const semanticContractValid = semanticExtractionContract?.valid !== false;
const semanticApplyCanonicalRecommended = semanticExtractionContract?.apply_canonical_recommended !== false;
const semanticReasonCodes = Array.isArray(semanticExtractionContract?.reason_codes)
? semanticExtractionContract.reason_codes
: [];
const strictDeepInvestigationCueDetected = hasStrictDeepInvestigationCue(rawUserMessage) ||
hasStrictDeepInvestigationCue(repairedRawUserMessage) ||
hasStrictDeepInvestigationCue(effectiveAddressUserMessage) ||
hasStrictDeepInvestigationCue(repairedEffectiveAddressUserMessage);
const strictDeepInvestigationBypassAllowed = shouldBypassStrictDeepInvestigationCueForAddressIntent(resolvedIntentResolution.intent) ||
shouldBypassStrictDeepInvestigationCueForAddressIntent(llmContractIntent);
const keepAddressLaneByIntent = semanticApplyCanonicalRecommended &&
Boolean((resolvedIntentResolution.intent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(resolvedIntentResolution.intent)) ||
(llmContractIntent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent)) ||
openContractsAddressSignal) &&
(!strictDeepInvestigationCueDetected || strictDeepInvestigationBypassAllowed);
const strongDataSignal = hasStrongDataIntentSignal(rawUserMessage) ||
hasStrongDataIntentSignal(repairedRawUserMessage) ||
hasStrongDataIntentSignal(effectiveAddressUserMessage) ||
hasStrongDataIntentSignal(repairedEffectiveAddressUserMessage) ||
hasAccountingSignal(rawUserMessage) ||
hasAccountingSignal(repairedRawUserMessage) ||
hasAccountingSignal(effectiveAddressUserMessage) ||
hasAccountingSignal(repairedEffectiveAddressUserMessage) ||
hasDataRetrievalRequestSignal(rawUserMessage) ||
hasDataRetrievalRequestSignal(repairedRawUserMessage);
const llmContractMode = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.mode);
const llmFirstAddressCandidate = Boolean(llmContractMode === "address_query" && llmContractIntent && llmContractIntent !== "unknown");
const llmFirstUnsupportedCandidate = Boolean(llmContractMode === "unsupported" &&
(!llmContractIntent || llmContractIntent === "unknown"));
const dangerOrCoercionSignal = hasDangerOrCoercionSignal(rawUserMessage) ||
hasDangerOrCoercionSignal(repairedRawUserMessage) ||
hasDangerOrCoercionSignal(effectiveAddressUserMessage) ||
hasDangerOrCoercionSignal(repairedEffectiveAddressUserMessage);
const explicitAddressFollowupSignal = hasAddressFollowupContextSignal(rawUserMessage) ||
hasAddressFollowupContextSignal(repairedRawUserMessage) ||
hasAddressFollowupContextSignal(effectiveAddressUserMessage) ||
hasAddressFollowupContextSignal(repairedEffectiveAddressUserMessage) ||
hasShortDebtMirrorFollowupSignal(rawUserMessage) ||
hasShortDebtMirrorFollowupSignal(repairedRawUserMessage) ||
hasShortDebtMirrorFollowupSignal(effectiveAddressUserMessage) ||
hasShortDebtMirrorFollowupSignal(repairedEffectiveAddressUserMessage);
const followupPreviousIntent = toNonEmptyString(followupContext?.previous_intent);
const followupPreviousFilters = followupContext?.previous_filters && typeof followupContext.previous_filters === "object"
? followupContext.previous_filters
: null;
const protectedInventoryShortFollowup = Boolean(followupContext &&
(isInventorySelectedObjectIntent(followupPreviousIntent) ||
(followupPreviousIntent === "inventory_on_hand_as_of_date" &&
(toNonEmptyString(followupContext.previous_anchor_type) === "item" ||
toNonEmptyString(followupContext.previous_anchor_value) ||
toNonEmptyString(followupPreviousFilters?.item)))) &&
(hasShortInventoryObjectFollowupSignal(rawUserMessage) ||
hasShortInventoryObjectFollowupSignal(repairedRawUserMessage) ||
hasShortInventoryObjectFollowupSignal(effectiveAddressUserMessage) ||
hasShortInventoryObjectFollowupSignal(repairedEffectiveAddressUserMessage)));
const organizationClarificationContinuationDetected = Boolean((followupContext || continuitySnapshot.hasGroundedAddressContext) &&
lastOrganizationClarificationDebug &&
organizationClarificationSelection &&
!dataScopeMetaQuery &&
!capabilityMetaQuery &&
!dataRetrievalSignal);
const effectiveAddressFollowupSignal = explicitAddressFollowupSignal && !dangerOrCoercionSignal;
const baseToolGate = resolveAddressToolGateDecision(effectiveAddressUserMessage, followupContext, llmPreDecomposeMeta, rawUserMessage);
const deterministicNonDomainGuard = Boolean(!dataScopeMetaQuery &&
!capabilityMetaQuery &&
!dataRetrievalSignal &&
!aggregateBusinessAnalyticsSignal &&
!effectiveAddressFollowupSignal &&
resolvedModeDetection.mode === "unsupported" &&
resolvedIntentResolution.intent === "unknown");
const baseToolGatePreservesAddressLane = Boolean(baseToolGate?.runAddressLane &&
["address_intent_resolver_detected", "address_mode_classifier_detected", "address_signal_detected", "llm_canonical_data_signal_detected"].includes(String(baseToolGate?.reason ?? "")));
const nonDomainQueryIndexed = Boolean(!llmFirstAddressCandidate &&
deterministicNonDomainGuard &&
(llmFirstUnsupportedCandidate || llmContractMode === null) &&
!baseToolGatePreservesAddressLane &&
!protectedInventoryShortFollowup &&
!organizationClarificationContinuationDetected);
const lastAddressAssistantDebug = sessionItems
? findLastAddressAssistantItem(sessionItems)?.debug ?? null
: null;
const memorySignals = resolveRouteMemorySignals({
rawUserMessage,
repairedRawUserMessage,
effectiveAddressUserMessage,
repairedEffectiveAddressUserMessage,
dataScopeMetaQuery,
capabilityMetaQuery,
dataRetrievalSignal,
strongDataSignal,
aggregateBusinessAnalyticsSignal,
lastGroundedAddressDebug,
hasPriorAddressDebug: Boolean(lastGroundedAddressDebug || lastAddressAssistantDebug),
sessionItems
});
const contextualHistoricalCapabilityFollowupDetected = memorySignals.contextualHistoricalCapabilityFollowupDetected;
const contextualMemoryRecapFollowupDetected = memorySignals.contextualMemoryRecapFollowupDetected;
const organizationFactLookupDetected = hasOrganizationFactLookupSignal(rawUserMessage) ||
hasOrganizationFactLookupSignal(repairedRawUserMessage) ||
hasOrganizationFactLookupSignal(effectiveAddressUserMessage) ||
hasOrganizationFactLookupSignal(repairedEffectiveAddressUserMessage);
const previousIntent = toNonEmptyString(followupContext?.previous_intent);
const rootContextOnlyFollowup = Boolean(followupContext && followupContext.root_context_only === true);
const inventoryRootRestatementFollowupDetected = Boolean(followupContext &&
(previousIntent === "inventory_on_hand_as_of_date" ||
previousIntent === "inventory_supplier_stock_overlap_as_of_date" ||
rootContextOnlyFollowup) &&
(hasInventoryRootRestatementFollowupSignal(rawUserMessage) ||
hasInventoryRootRestatementFollowupSignal(repairedRawUserMessage) ||
hasInventoryRootRestatementFollowupSignal(effectiveAddressUserMessage) ||
hasInventoryRootRestatementFollowupSignal(repairedEffectiveAddressUserMessage)));
const organizationFactBoundaryFollowupDetected = hasOrganizationFactFollowupSignal(rawUserMessage, sessionItems ?? []) ||
hasOrganizationFactFollowupSignal(repairedRawUserMessage, sessionItems ?? []) ||
hasOrganizationFactFollowupSignal(effectiveAddressUserMessage, sessionItems ?? []) ||
hasOrganizationFactFollowupSignal(repairedEffectiveAddressUserMessage, sessionItems ?? []);
const hardMetaMode = resolveHardMetaMode({
dataScopeMetaQuery,
capabilityMetaQuery,
dataRetrievalSignal
});
if (hardMetaMode === "data_scope") {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "assistant_data_scope_query_detected",
livingMode: "chat",
livingReason: "assistant_data_scope_query_detected",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: "data_scope",
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "assistant_data_scope_query_detected",
living_mode: "chat",
living_reason: "assistant_data_scope_query_detected"
}
}
};
}
if (hardMetaMode === "capability") {
if (contextualHistoricalCapabilityFollowupDetected) {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "inventory_history_capability_followup_detected",
livingMode: "chat",
livingReason: "inventory_history_capability_followup_detected",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: "capability",
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext || lastGroundedAddressDebug),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "inventory_history_capability_followup_detected",
living_mode: "chat",
living_reason: "inventory_history_capability_followup_detected"
}
}
};
}
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "assistant_capability_query_detected",
livingMode: "chat",
livingReason: "assistant_capability_query_detected",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: "capability",
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "assistant_capability_query_detected",
living_mode: "chat",
living_reason: "assistant_capability_query_detected"
}
}
};
}
if (contextualMemoryRecapFollowupDetected) {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "memory_recap_followup_detected",
livingMode: "chat",
livingReason: "memory_recap_followup_detected",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: nonDomainQueryIndexed ? "non_domain" : null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext || lastGroundedAddressDebug || lastAddressAssistantDebug),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "memory_recap_followup_detected",
living_mode: "chat",
living_reason: "memory_recap_followup_detected"
}
}
};
}
if (organizationFactLookupDetected || organizationFactBoundaryFollowupDetected) {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "organization_fact_lookup_signal_detected",
livingMode: "chat",
livingReason: "organization_fact_lookup_signal_detected",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext || organizationFactBoundaryFollowupDetected),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "organization_fact_lookup_signal_detected",
living_mode: "chat",
living_reason: "organization_fact_lookup_signal_detected"
}
}
};
}
const supportedExactInvestigativeAddressBypass = Boolean(llmContractMode === "deep_analysis" &&
semanticApplyCanonicalRecommended &&
strictDeepInvestigationBypassAllowed &&
llmContractIntent &&
ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent));
if (supportedExactInvestigativeAddressBypass) {
return {
runAddressLane: true,
toolGateDecision: "run_address_lane",
toolGateReason: "address_signal_detected",
livingMode: "address_data",
livingReason: "address_lane_triggered",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
semantic_contract_valid: semanticContractValid,
semantic_apply_canonical_recommended: semanticApplyCanonicalRecommended,
semantic_reason_codes: semanticReasonCodes,
semantic_route_arbitration: {
supported_address_intent_detected: true,
strict_deep_investigation_bypass_allowed: true,
semantic_deep_investigation_hint_detected: semanticExtractionContract?.guard_hints?.deep_investigation_signal_detected === true,
semantic_aggregate_shape_detected: false,
followup_semantic_override_to_deep_allowed: false
},
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: false,
deep_analysis_signal_fallback_to_deep: false,
aggregate_analytics_signal_fallback_to_deep: false,
deep_session_continuation_fallback_to_deep: false,
final_decision: {
run_address_lane: true,
tool_gate_decision: "run_address_lane",
tool_gate_reason: "address_signal_detected",
living_mode: "address_data",
living_reason: "address_lane_triggered"
}
}
};
}
if (colloquialCustomerValueSignal) {
return {
runAddressLane: true,
toolGateDecision: "run_address_lane",
toolGateReason: "address_signal_detected",
livingMode: "address_data",
livingReason: "address_lane_triggered",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: true,
data_retrieval_signal_detected: dataRetrievalSignal,
semantic_contract_valid: semanticContractValid,
semantic_apply_canonical_recommended: semanticApplyCanonicalRecommended,
semantic_reason_codes: semanticReasonCodes,
semantic_route_arbitration: {
supported_address_intent_detected: true,
strict_deep_investigation_bypass_allowed: false,
semantic_deep_investigation_hint_detected: false,
semantic_aggregate_shape_detected: true,
followup_semantic_override_to_deep_allowed: false
},
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: false,
deep_analysis_signal_fallback_to_deep: false,
aggregate_analytics_signal_fallback_to_deep: false,
deep_session_continuation_fallback_to_deep: false,
final_decision: {
run_address_lane: true,
tool_gate_decision: "run_address_lane",
tool_gate_reason: "address_signal_detected",
living_mode: "address_data",
living_reason: "address_lane_triggered"
}
}
};
}
const standaloneAggregateAnalyticsFollowupFallback = Boolean(followupContext &&
aggregateBusinessAnalyticsBridgeDetected &&
llmContractMode === null &&
!((resolvedIntentResolution.intent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(resolvedIntentResolution.intent)) ||
(llmContractIntent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent)) ||
openContractsAddressSignal));
if (standaloneAggregateAnalyticsFollowupFallback) {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "aggregate_analytics_signal_fallback_to_deep",
livingMode: "deep_analysis",
livingReason: "aggregate_analytics_signal_fallback_to_deep",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
semantic_contract_valid: semanticContractValid,
semantic_apply_canonical_recommended: semanticApplyCanonicalRecommended,
semantic_reason_codes: semanticReasonCodes,
semantic_route_arbitration: {
supported_address_intent_detected: false,
strict_deep_investigation_bypass_allowed: false,
semantic_deep_investigation_hint_detected: false,
semantic_aggregate_shape_detected: true,
followup_semantic_override_to_deep_allowed: true
},
followup_context_detected: true,
unsupported_address_intent_fallback_to_deep: false,
deep_analysis_signal_fallback_to_deep: false,
aggregate_analytics_signal_fallback_to_deep: true,
deep_session_continuation_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "aggregate_analytics_signal_fallback_to_deep",
living_mode: "deep_analysis",
living_reason: "aggregate_analytics_signal_fallback_to_deep"
}
}
};
}
if (nonDomainQueryIndexed) {
return {
runAddressLane: false,
toolGateDecision: "skip_address_lane",
toolGateReason: "non_domain_query_indexed",
livingMode: "chat",
livingReason: "non_domain_query_indexed",
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: "non_domain",
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: false,
final_decision: {
run_address_lane: false,
tool_gate_decision: "skip_address_lane",
tool_gate_reason: "non_domain_query_indexed",
living_mode: "chat",
living_reason: "non_domain_query_indexed"
}
}
};
}
const metaAnswerFollowupSignal = metaSignals.metaAnswerFollowupSignal;
const preserveAddressLaneSignal = Boolean((llmPreDecomposeMeta?.llmCanonicalCandidateDetected &&
llmPreDecomposeMeta?.applied &&
llmContractMode === "address_query") ||
hasSameDateAccountFollowupSignalForPredecompose(rawUserMessage) ||
hasSameDateAccountFollowupSignalForPredecompose(effectiveAddressUserMessage) ||
hasSameDateAccountFollowupSignalForPredecompose(repairedRawUserMessage) ||
hasSameDateAccountFollowupSignalForPredecompose(repairedEffectiveAddressUserMessage) ||
hasLooseAllTimeAddressLookupSignal(rawUserMessage) ||
hasLooseAllTimeAddressLookupSignal(effectiveAddressUserMessage) ||
hasLooseAllTimeAddressLookupSignal(repairedRawUserMessage) ||
hasLooseAllTimeAddressLookupSignal(repairedEffectiveAddressUserMessage) ||
hasAddressFollowupContextSignal(rawUserMessage) ||
hasAddressFollowupContextSignal(effectiveAddressUserMessage) ||
hasAddressFollowupContextSignal(repairedRawUserMessage) ||
hasAddressFollowupContextSignal(repairedEffectiveAddressUserMessage) ||
hasShortDebtMirrorFollowupSignal(rawUserMessage) ||
hasShortDebtMirrorFollowupSignal(effectiveAddressUserMessage) ||
hasShortDebtMirrorFollowupSignal(repairedRawUserMessage) ||
hasShortDebtMirrorFollowupSignal(repairedEffectiveAddressUserMessage) ||
inventoryRootRestatementFollowupDetected);
const supportedAddressIntentDetected = (!strictDeepInvestigationCueDetected || strictDeepInvestigationBypassAllowed) &&
Boolean((resolvedIntentResolution.intent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(resolvedIntentResolution.intent)) ||
(llmContractIntent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent)) ||
openContractsAddressSignal);
const supportedAddressRouteCandidateDetected = Boolean(supportedAddressIntentDetected ||
keepAddressLaneByIntent ||
(baseToolGate?.runAddressLane &&
llmContractMode !== "deep_analysis" &&
!strictDeepInvestigationCueDetected &&
["address_intent_resolver_detected", "address_mode_classifier_detected", "address_signal_detected", "llm_canonical_data_signal_detected"].includes(String(baseToolGate?.reason ?? ""))));
const semanticGuardHints = semanticExtractionContract?.guard_hints &&
typeof semanticExtractionContract.guard_hints === "object"
? semanticExtractionContract.guard_hints
: null;
const semanticExtraction = semanticExtractionContract?.extraction &&
typeof semanticExtractionContract.extraction === "object"
? semanticExtractionContract.extraction
: null;
const semanticDeepInvestigationHintDetected = semanticGuardHints?.deep_investigation_signal_detected === true;
const semanticAggregateShapeDetected = semanticExtraction?.query_shape === "AGGREGATE_LOOKUP" ||
semanticExtraction?.aggregation_profile === "management_profile";
const followupSemanticOverrideToDeepAllowed = Boolean(followupContext &&
!supportedAddressIntentDetected &&
(rootContextOnlyFollowup ||
llmContractMode === "unsupported" ||
semanticAggregateShapeDetected ||
semanticDeepInvestigationHintDetected ||
!semanticApplyCanonicalRecommended));
const unsupportedIntentOrMode = (resolvedModeDetection.mode !== "address_query" && resolvedIntentResolution.intent === "unknown") ||
llmContractMode === "unsupported" ||
(rootContextOnlyFollowup &&
resolvedIntentResolution.intent === "unknown" &&
(!llmContractIntent || llmContractIntent === "unknown"));
const unsupportedAddressIntentFallbackToDeep = Boolean(baseToolGate?.runAddressLane &&
!llmRuntimeUnavailableDetected &&
unsupportedIntentOrMode &&
strongDataSignal &&
(rootContextOnlyFollowup ||
llmContractMode === "deep_analysis" ||
!dataRetrievalSignal ||
strictDeepInvestigationCueDetected ||
semanticDeepInvestigationHintDetected ||
aggregateBusinessAnalyticsSignal) &&
!preserveAddressLaneSignal &&
!supportedAddressRouteCandidateDetected &&
(!followupContext || followupSemanticOverrideToDeepAllowed));
const deepAnalysisPreferenceDetected = Boolean(hasDeepAnalysisPreferenceSignal(rawUserMessage) ||
hasDeepAnalysisPreferenceSignal(repairedRawUserMessage) ||
hasDeepAnalysisPreferenceSignal(effectiveAddressUserMessage) ||
hasDeepAnalysisPreferenceSignal(repairedEffectiveAddressUserMessage) ||
hasDirectDeepAnalysisSignal(rawUserMessage) ||
hasDirectDeepAnalysisSignal(repairedRawUserMessage) ||
hasDirectDeepAnalysisSignal(effectiveAddressUserMessage) ||
hasDirectDeepAnalysisSignal(repairedEffectiveAddressUserMessage));
const exactAddressIntentProtectedFromSemanticDeepHint = Boolean(supportedAddressRouteCandidateDetected &&
llmContractMode === "address_query" &&
llmContractIntent &&
ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent) &&
semanticApplyCanonicalRecommended &&
!deepAnalysisPreferenceDetected &&
!strictDeepInvestigationCueDetected &&
!semanticAggregateShapeDetected);
const protectAddressLaneFromFallback = Boolean(supportedAddressRouteCandidateDetected &&
!deepAnalysisPreferenceDetected &&
(exactAddressIntentProtectedFromSemanticDeepHint ||
!semanticDeepInvestigationHintDetected ||
strictDeepInvestigationBypassAllowed));
const vatExplainFollowupSignal = Boolean(followupContext &&
toNonEmptyString(followupContext.previous_intent) === "vat_payable_forecast" &&
/(?:\u043f\u043e\u0447\u0435\u043c\u0443|why).*(?:\u043f\u0440\u043e\u0433\u043d\u043e\u0437|forecast).*(?:\u0443\u043f\u043b\u0430\u0442|payable|\b0\b)/iu.test(compactWhitespace(`${repairedRawUserMessage} ${repairedEffectiveAddressUserMessage}`)));
const vatEvaluativeFollowupSignal = Boolean(followupContext &&
toNonEmptyString(followupContext.previous_intent) === "vat_payable_forecast" &&
/(?:^|\s)(?:это\s+)?много\s+или\s+мало(?:\?|$)|(?:^|\s)(?:это\s+)?нормально(?:\?|$)|(?:^|\s)(?:это\s+)?плохо(?:\?|$)|(?:^|\s)(?:это\s+)?хорошо(?:\?|$)/iu.test(compactWhitespace(`${repairedRawUserMessage} ${repairedEffectiveAddressUserMessage}`)));
const deepAnalysisSignalFallbackToDeep = Boolean(baseToolGate?.runAddressLane &&
!llmRuntimeUnavailableDetected &&
(deepAnalysisPreferenceDetected || semanticDeepInvestigationHintDetected) &&
!protectAddressLaneFromFallback &&
!vatExplainFollowupSignal &&
(!followupContext || !dataRetrievalSignal || followupSemanticOverrideToDeepAllowed));
const aggregateAnalyticsFallbackToDeep = Boolean(baseToolGate?.runAddressLane &&
!llmRuntimeUnavailableDetected &&
aggregateBusinessAnalyticsSignal &&
!protectAddressLaneFromFallback &&
(!followupContext ||
llmContractMode === "unsupported" ||
llmContractMode === null ||
semanticAggregateShapeDetected ||
!semanticApplyCanonicalRecommended ||
standaloneAddressTopicSignal));
const deepSessionContinuationFallbackToDeep = Boolean(!followupContext &&
baseToolGate?.runAddressLane &&
!llmRuntimeUnavailableDetected &&
!protectAddressLaneFromFallback &&
hasDeepSessionContinuationSignal({
rawUserMessage,
repairedRawUserMessage,
effectiveAddressUserMessage,
repairedEffectiveAddressUserMessage,
sessionItems
}));
const hasPriorAddressAnswerContext = Boolean(lastGroundedAddressDebug ||
continuitySnapshot.hasGroundedAddressContext ||
toNonEmptyString(followupContext?.previous_intent));
const metaFollowupOverGroundedAnswer = isMetaFollowupOverGroundedAnswer({
followupContext,
hasPriorAddressAnswerContext,
metaAnswerFollowupSignal,
vatEvaluativeFollowupSignal,
dataScopeMetaQuery,
capabilityMetaQuery,
aggregateBusinessAnalyticsSignal,
dataRetrievalSignal,
strongDataSignal,
resolvedMode: resolvedModeDetection.mode,
resolvedIntent: resolvedIntentResolution.intent,
llmContractIntent,
llmContractMode
});
let runAddressLane = Boolean(baseToolGate?.runAddressLane);
let toolGateDecision = String(baseToolGate?.decision ?? "skip_address_lane");
let toolGateReason = String(baseToolGate?.reason ?? "no_address_signal_after_l0");
if (unsupportedAddressIntentFallbackToDeep) {
runAddressLane = false;
toolGateDecision = "skip_address_lane";
toolGateReason = "address_signal_unsupported_intent_fallback_to_deep";
}
if (deepAnalysisSignalFallbackToDeep && !unsupportedAddressIntentFallbackToDeep) {
runAddressLane = false;
toolGateDecision = "skip_address_lane";
toolGateReason = "deep_analysis_signal_fallback_to_deep";
}
if (aggregateAnalyticsFallbackToDeep &&
!unsupportedAddressIntentFallbackToDeep &&
!deepAnalysisSignalFallbackToDeep) {
runAddressLane = false;
toolGateDecision = "skip_address_lane";
toolGateReason = "aggregate_analytics_signal_fallback_to_deep";
}
if (deepSessionContinuationFallbackToDeep) {
runAddressLane = false;
toolGateDecision = "skip_address_lane";
toolGateReason = "deep_session_continuation_fallback_to_deep";
}
if (metaFollowupOverGroundedAnswer) {
runAddressLane = false;
toolGateDecision = "skip_address_lane";
toolGateReason = "meta_followup_over_grounded_answer";
}
let livingDecision = resolveLivingAssistantModeDecision({
userMessage: rawUserMessage,
addressLaneTriggered: runAddressLane,
llmProvider: providerExecution.normalized_provider,
useMock,
predecomposeMode: llmPreDecomposeMeta?.predecomposeContract?.mode ?? null,
predecomposeModeConfidence: llmPreDecomposeMeta?.predecomposeContract?.mode_confidence ?? null
});
if (unsupportedAddressIntentFallbackToDeep) {
livingDecision = {
mode: "deep_analysis",
reason: "unsupported_address_intent_fallback_to_deep"
};
}
if (deepAnalysisSignalFallbackToDeep && !unsupportedAddressIntentFallbackToDeep) {
livingDecision = {
mode: "deep_analysis",
reason: "deep_analysis_signal_fallback_to_deep"
};
}
if (aggregateAnalyticsFallbackToDeep &&
!unsupportedAddressIntentFallbackToDeep &&
!deepAnalysisSignalFallbackToDeep) {
livingDecision = {
mode: "deep_analysis",
reason: "aggregate_analytics_signal_fallback_to_deep"
};
}
if (deepSessionContinuationFallbackToDeep) {
livingDecision = {
mode: "deep_analysis",
reason: "deep_session_continuation_fallback_to_deep"
};
}
if (metaFollowupOverGroundedAnswer) {
livingDecision = {
mode: "chat",
reason: "meta_followup_over_grounded_answer"
};
}
return {
runAddressLane,
toolGateDecision,
toolGateReason,
livingMode: livingDecision.mode,
livingReason: livingDecision.reason,
orchestrationContract: {
schema_version: "assistant_orchestration_contract_v1",
hard_meta_mode: null,
provider_execution: providerExecution,
address_mode: resolvedModeDetection.mode,
address_mode_confidence: resolvedModeDetection.confidence,
address_intent: resolvedIntentResolution.intent,
address_intent_confidence: resolvedIntentResolution.confidence,
strong_data_signal_detected: strongDataSignal,
data_retrieval_signal_detected: dataRetrievalSignal,
semantic_contract_valid: semanticContractValid,
semantic_apply_canonical_recommended: semanticApplyCanonicalRecommended,
semantic_reason_codes: semanticReasonCodes,
semantic_route_arbitration: {
supported_address_intent_detected: supportedAddressRouteCandidateDetected,
strict_deep_investigation_bypass_allowed: strictDeepInvestigationBypassAllowed,
semantic_deep_investigation_hint_detected: semanticDeepInvestigationHintDetected,
semantic_aggregate_shape_detected: semanticAggregateShapeDetected,
exact_address_intent_protected_from_semantic_deep_hint: exactAddressIntentProtectedFromSemanticDeepHint,
followup_semantic_override_to_deep_allowed: followupSemanticOverrideToDeepAllowed
},
followup_context_detected: Boolean(followupContext),
unsupported_address_intent_fallback_to_deep: unsupportedAddressIntentFallbackToDeep,
deep_analysis_signal_fallback_to_deep: deepAnalysisSignalFallbackToDeep,
aggregate_analytics_signal_fallback_to_deep: aggregateAnalyticsFallbackToDeep,
deep_session_continuation_fallback_to_deep: deepSessionContinuationFallbackToDeep,
final_decision: {
run_address_lane: runAddressLane,
tool_gate_decision: toolGateDecision,
tool_gate_reason: toolGateReason,
living_mode: livingDecision.mode,
living_reason: livingDecision.reason
}
}
};
}
return {
resolveAssistantOrchestrationDecision
};
}