1315 lines
73 KiB
TypeScript
1315 lines
73 KiB
TypeScript
// @ts-nocheck
|
||
import {
|
||
resolveAssistantOrganizationAuthority,
|
||
resolveOrganizationClarificationContinuation
|
||
} from "./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 resolveAddressFallbackToDeepArbitration(input) {
|
||
const {
|
||
baseToolGateRunAddressLane,
|
||
llmRuntimeUnavailableDetected,
|
||
unsupportedIntentOrMode,
|
||
strongDataSignal,
|
||
rootContextOnlyFollowup,
|
||
llmContractMode,
|
||
strictDeepInvestigationCueDetected,
|
||
semanticDeepInvestigationHintDetected,
|
||
aggregateBusinessAnalyticsSignal,
|
||
preserveAddressLaneSignal,
|
||
supportedAddressRouteCandidateDetected,
|
||
followupContext,
|
||
followupSemanticOverrideToDeepAllowed,
|
||
deepAnalysisPreferenceDetected,
|
||
protectAddressLaneFromFallback,
|
||
dataRetrievalSignal,
|
||
vatExplainFollowupSignal,
|
||
semanticAggregateShapeDetected,
|
||
semanticApplyCanonicalRecommended,
|
||
standaloneAddressTopicSignal,
|
||
hasDeepSessionContinuationSignalDetected
|
||
} = input;
|
||
const unsupportedAddressIntentFallbackToDeep = Boolean(baseToolGateRunAddressLane &&
|
||
!llmRuntimeUnavailableDetected &&
|
||
unsupportedIntentOrMode &&
|
||
strongDataSignal &&
|
||
(rootContextOnlyFollowup ||
|
||
llmContractMode === "deep_analysis" ||
|
||
!dataRetrievalSignal ||
|
||
strictDeepInvestigationCueDetected ||
|
||
semanticDeepInvestigationHintDetected ||
|
||
aggregateBusinessAnalyticsSignal) &&
|
||
!preserveAddressLaneSignal &&
|
||
!supportedAddressRouteCandidateDetected &&
|
||
(!followupContext || followupSemanticOverrideToDeepAllowed));
|
||
const deepAnalysisSignalFallbackToDeep = Boolean(baseToolGateRunAddressLane &&
|
||
!llmRuntimeUnavailableDetected &&
|
||
(deepAnalysisPreferenceDetected || semanticDeepInvestigationHintDetected) &&
|
||
!protectAddressLaneFromFallback &&
|
||
!vatExplainFollowupSignal &&
|
||
(!followupContext || !dataRetrievalSignal || followupSemanticOverrideToDeepAllowed));
|
||
const aggregateAnalyticsFallbackToDeep = Boolean(baseToolGateRunAddressLane &&
|
||
!llmRuntimeUnavailableDetected &&
|
||
aggregateBusinessAnalyticsSignal &&
|
||
!protectAddressLaneFromFallback &&
|
||
(!followupContext ||
|
||
llmContractMode === "unsupported" ||
|
||
llmContractMode === null ||
|
||
semanticAggregateShapeDetected ||
|
||
!semanticApplyCanonicalRecommended ||
|
||
standaloneAddressTopicSignal));
|
||
const deepSessionContinuationFallbackToDeep = Boolean(!followupContext &&
|
||
baseToolGateRunAddressLane &&
|
||
!llmRuntimeUnavailableDetected &&
|
||
!protectAddressLaneFromFallback &&
|
||
hasDeepSessionContinuationSignalDetected);
|
||
return {
|
||
unsupportedAddressIntentFallbackToDeep,
|
||
deepAnalysisSignalFallbackToDeep,
|
||
aggregateAnalyticsFallbackToDeep,
|
||
deepSessionContinuationFallbackToDeep
|
||
};
|
||
}
|
||
function resolveAddressLaneProtectionArbitration(input) {
|
||
const {
|
||
resolvedIntent,
|
||
llmContractIntent,
|
||
llmContractMode,
|
||
strictDeepInvestigationCueDetected,
|
||
strictDeepInvestigationBypassAllowed,
|
||
openContractsAddressSignal,
|
||
keepAddressLaneByIntent,
|
||
baseToolGateRunAddressLane,
|
||
baseToolGateReason,
|
||
semanticExtractionContract,
|
||
followupContext,
|
||
rootContextOnlyFollowup,
|
||
semanticApplyCanonicalRecommended,
|
||
deepAnalysisPreferenceDetected
|
||
} = input;
|
||
const supportedAddressIntentDetected = (!strictDeepInvestigationCueDetected || strictDeepInvestigationBypassAllowed) &&
|
||
Boolean((resolvedIntent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(resolvedIntent)) ||
|
||
(llmContractIntent && ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(llmContractIntent)) ||
|
||
openContractsAddressSignal);
|
||
const supportedAddressRouteCandidateDetected = Boolean(supportedAddressIntentDetected ||
|
||
keepAddressLaneByIntent ||
|
||
(baseToolGateRunAddressLane &&
|
||
llmContractMode !== "deep_analysis" &&
|
||
!strictDeepInvestigationCueDetected &&
|
||
["address_intent_resolver_detected", "address_mode_classifier_detected", "address_signal_detected", "llm_canonical_data_signal_detected"].includes(String(baseToolGateReason ?? ""))));
|
||
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 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));
|
||
return {
|
||
supportedAddressIntentDetected,
|
||
supportedAddressRouteCandidateDetected,
|
||
semanticDeepInvestigationHintDetected,
|
||
semanticAggregateShapeDetected,
|
||
followupSemanticOverrideToDeepAllowed,
|
||
exactAddressIntentProtectedFromSemanticDeepHint,
|
||
protectAddressLaneFromFallback
|
||
};
|
||
}
|
||
export function createAssistantRoutePolicy(deps) {
|
||
const {
|
||
repairAddressMojibake,
|
||
findLastGroundedAddressAnswerDebug,
|
||
findLastOrganizationClarificationAddressDebug,
|
||
mergeKnownOrganizations,
|
||
normalizeOrganizationScopeValue,
|
||
resolveOrganizationSelectionFromMessage,
|
||
resolveMetaSignalSet,
|
||
resolveHardMetaMode,
|
||
isMetaFollowupOverGroundedAnswer,
|
||
isAnswerInspectionFollowupOverGroundedAnswer,
|
||
hasDataRetrievalRequestSignal,
|
||
hasOrganizationFactLookupSignal,
|
||
hasOrganizationFactFollowupSignal,
|
||
hasAggregateBusinessAnalyticsSignal,
|
||
hasStandaloneAddressTopicSignal,
|
||
hasOpenContractsAddressSignal,
|
||
detectAddressQuestionMode,
|
||
resolveAddressIntent,
|
||
toNonEmptyString,
|
||
hasStrictDeepInvestigationCue,
|
||
hasStrongDataIntentSignal,
|
||
hasAccountingSignal,
|
||
hasDangerOrCoercionSignal,
|
||
hasAddressFollowupContextSignal,
|
||
hasShortDebtMirrorFollowupSignal,
|
||
isInventorySelectedObjectIntent,
|
||
hasShortInventoryObjectFollowupSignal,
|
||
isGroundedInventoryContextDebug,
|
||
resolveRouteMemorySignals,
|
||
findLastAddressAssistantItem,
|
||
resolveAddressToolGateDecision: resolveAddressToolGateDecisionOverride,
|
||
hasAddressLlmPreDecomposeCandidate,
|
||
hasSameDateAccountFollowupSignalForPredecompose,
|
||
hasLooseAllTimeAddressLookupSignal,
|
||
hasDeepAnalysisPreferenceSignal,
|
||
hasDirectDeepAnalysisSignal,
|
||
shouldEmitOrganizationSelectionReply,
|
||
compactWhitespace,
|
||
hasDeepSessionContinuationSignal,
|
||
resolveLivingAssistantModeDecision,
|
||
resolveProviderExecutionState,
|
||
resolveAssistantTurnMeaning
|
||
} = deps;
|
||
function resolveBaseAddressToolGateDecision(addressInputMessage, followupContext, llmPreDecomposeMeta = null, rawUserMessage = null) {
|
||
const repairedInputMessage = repairAddressMojibake(String(addressInputMessage ?? ""));
|
||
const rawMessageForGate = String(rawUserMessage ?? addressInputMessage ?? "");
|
||
const repairedRawMessageForGate = repairAddressMojibake(rawMessageForGate);
|
||
const rawMetaSignals = resolveMetaSignalSet({
|
||
rawUserMessage: rawMessageForGate,
|
||
repairedRawUserMessage: repairedRawMessageForGate,
|
||
effectiveAddressUserMessage: rawMessageForGate,
|
||
repairedEffectiveAddressUserMessage: repairedRawMessageForGate
|
||
});
|
||
const effectiveMetaSignals = resolveMetaSignalSet({
|
||
rawUserMessage: rawMessageForGate,
|
||
repairedRawUserMessage: repairedRawMessageForGate,
|
||
effectiveAddressUserMessage: String(addressInputMessage ?? ""),
|
||
repairedEffectiveAddressUserMessage: repairedInputMessage
|
||
});
|
||
const dataScopeMetaQuery = Boolean(rawMetaSignals.dataScopeMetaQuery || effectiveMetaSignals.dataScopeMetaQuery);
|
||
const rawCapabilityMetaQuery = Boolean(rawMetaSignals.capabilityMetaQuery);
|
||
const capabilityMetaQuery = Boolean(rawCapabilityMetaQuery || effectiveMetaSignals.capabilityMetaQuery);
|
||
const rawDataRetrievalSignal = hasDataRetrievalRequestSignal(rawMessageForGate) ||
|
||
hasDataRetrievalRequestSignal(repairedRawMessageForGate);
|
||
const dataRetrievalSignal = rawDataRetrievalSignal || hasDataRetrievalRequestSignal(repairedInputMessage);
|
||
const rawCapabilityMetaOverride = rawCapabilityMetaQuery && !rawDataRetrievalSignal;
|
||
if (dataScopeMetaQuery || rawCapabilityMetaOverride || (capabilityMetaQuery && !dataRetrievalSignal)) {
|
||
return {
|
||
runAddressLane: false,
|
||
decision: "skip_address_lane",
|
||
reason: dataScopeMetaQuery ? "assistant_data_scope_query_detected" : "assistant_capability_query_detected"
|
||
};
|
||
}
|
||
const modeDetection = detectAddressQuestionMode(repairedInputMessage || addressInputMessage);
|
||
const modeDetectionRaw = detectAddressQuestionMode(String(addressInputMessage ?? ""));
|
||
const hasClassifierSignal = modeDetection.mode === "address_query" || modeDetectionRaw.mode === "address_query";
|
||
const intentResolution = resolveAddressIntent(repairedInputMessage || addressInputMessage);
|
||
const intentResolutionRaw = resolveAddressIntent(String(addressInputMessage ?? ""));
|
||
const hasIntentSignal = intentResolution.intent !== "unknown" || intentResolutionRaw.intent !== "unknown";
|
||
const llmContractMode = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.mode);
|
||
const llmContractModeConfidence = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.mode_confidence);
|
||
const llmContractIntent = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.intent);
|
||
const semanticExtractionContract = llmPreDecomposeMeta?.semanticExtractionContract &&
|
||
typeof llmPreDecomposeMeta.semanticExtractionContract === "object"
|
||
? llmPreDecomposeMeta.semanticExtractionContract
|
||
: null;
|
||
const semanticCanonicalRecommended = semanticExtractionContract?.apply_canonical_recommended !== false;
|
||
const llmSupportedDeepAddressIntentSignal = llmContractMode === "deep_analysis" &&
|
||
/^(?:inventory_purchase_provenance_for_item|inventory_purchase_documents_for_item|inventory_sale_trace_for_item|inventory_profitability_for_item|inventory_purchase_to_sale_chain)$/u.test(llmContractIntent ?? "") &&
|
||
semanticCanonicalRecommended;
|
||
const llmCanonicalEntitySignal = /(?:заказчик|поставщик|контрагент|компан|customer|supplier|counterparty|company|vendor|client)/iu.test(compactWhitespace(repairedInputMessage.toLowerCase()));
|
||
const llmCanonicalAppliedSignal = Boolean(llmPreDecomposeMeta?.applied) && llmContractMode !== "deep_analysis";
|
||
const hasLlmCanonicalSignal = semanticCanonicalRecommended &&
|
||
Boolean(llmPreDecomposeMeta?.llmCanonicalCandidateDetected) &&
|
||
((llmContractMode === "address_query" && llmContractModeConfidence !== "low") ||
|
||
(llmCanonicalAppliedSignal &&
|
||
(hasStrongDataIntentSignal(repairedInputMessage) || llmCanonicalEntitySignal)));
|
||
const hasLlmCanonicalDataSignal = semanticCanonicalRecommended &&
|
||
Boolean(llmPreDecomposeMeta?.llmCanonicalCandidateDetected) &&
|
||
Boolean(llmPreDecomposeMeta?.applied) &&
|
||
(llmContractMode === "address_query" || llmContractMode === "unsupported" || llmContractMode === null) &&
|
||
hasStrongDataIntentSignal(repairedInputMessage);
|
||
const hasBusinessRankingAddressSignal = /(?:кто\s+(?:нам\s+)?(?:больше(?:\s+всего)?\s+принес|принес\s+больше(?:\s+всего)?).*(?:денег)?|who\s+brought\s+(?:us\s+)?(?:the\s+)?most\s+money)/iu.test(compactWhitespace(repairedInputMessage.toLowerCase()));
|
||
const sameDateAccountFollowupSignal = hasSameDateAccountFollowupSignalForPredecompose(rawMessageForGate) ||
|
||
hasSameDateAccountFollowupSignalForPredecompose(repairedInputMessage);
|
||
const hasLexicalAddressSignal = hasAddressLlmPreDecomposeCandidate(addressInputMessage) ||
|
||
hasAddressLlmPreDecomposeCandidate(repairedInputMessage) ||
|
||
hasAccountingSignal(addressInputMessage) ||
|
||
hasAccountingSignal(repairedInputMessage) ||
|
||
hasShortDebtMirrorFollowupSignal(rawMessageForGate) ||
|
||
hasShortDebtMirrorFollowupSignal(repairedInputMessage) ||
|
||
hasBusinessRankingAddressSignal ||
|
||
sameDateAccountFollowupSignal;
|
||
const hasUnsupportedLowConfidencePredecomposeSignal = llmContractMode === "unsupported" &&
|
||
(llmContractModeConfidence === "low" || llmContractModeConfidence === "medium") &&
|
||
llmContractIntent === "unknown";
|
||
const hasAnyAddressSignal = hasClassifierSignal ||
|
||
hasIntentSignal ||
|
||
hasLlmCanonicalSignal ||
|
||
hasLlmCanonicalDataSignal ||
|
||
hasLexicalAddressSignal ||
|
||
llmSupportedDeepAddressIntentSignal;
|
||
const strongDataSignalFromRawMessage = hasStrongDataIntentSignal(rawMessageForGate) ||
|
||
hasDataRetrievalRequestSignal(rawMessageForGate) ||
|
||
hasAccountingSignal(rawMessageForGate) ||
|
||
hasSameDateAccountFollowupSignalForPredecompose(rawMessageForGate);
|
||
const strongDataSignalFromEffectiveMessage = hasStrongDataIntentSignal(repairedInputMessage) ||
|
||
hasAccountingSignal(repairedInputMessage) ||
|
||
hasDataRetrievalRequestSignal(repairedInputMessage);
|
||
if (!semanticCanonicalRecommended &&
|
||
llmContractIntent === "unknown" &&
|
||
!followupContext &&
|
||
!hasClassifierSignal &&
|
||
!hasIntentSignal &&
|
||
!hasLexicalAddressSignal &&
|
||
!llmSupportedDeepAddressIntentSignal &&
|
||
!strongDataSignalFromRawMessage &&
|
||
!strongDataSignalFromEffectiveMessage) {
|
||
return {
|
||
runAddressLane: false,
|
||
decision: "skip_address_lane",
|
||
reason: "llm_predecompose_semantic_guard_rejected"
|
||
};
|
||
}
|
||
if (hasUnsupportedLowConfidencePredecomposeSignal &&
|
||
!followupContext &&
|
||
!hasAnyAddressSignal &&
|
||
!llmSupportedDeepAddressIntentSignal &&
|
||
!strongDataSignalFromRawMessage &&
|
||
!strongDataSignalFromEffectiveMessage) {
|
||
return {
|
||
runAddressLane: false,
|
||
decision: "skip_address_lane",
|
||
reason: "llm_predecompose_unsupported_mode"
|
||
};
|
||
}
|
||
const hasMessageSignal = hasAnyAddressSignal || strongDataSignalFromRawMessage || strongDataSignalFromEffectiveMessage;
|
||
if (hasMessageSignal) {
|
||
return {
|
||
runAddressLane: true,
|
||
decision: "run_address_lane",
|
||
reason: hasClassifierSignal
|
||
? "address_mode_classifier_detected"
|
||
: hasIntentSignal
|
||
? "address_intent_resolver_detected"
|
||
: hasLlmCanonicalSignal
|
||
? "llm_canonical_candidate_detected"
|
||
: hasLlmCanonicalDataSignal
|
||
? "llm_canonical_data_signal_detected"
|
||
: "address_signal_detected"
|
||
};
|
||
}
|
||
if (followupContext) {
|
||
return {
|
||
runAddressLane: true,
|
||
decision: "run_address_lane",
|
||
reason: "followup_context_detected"
|
||
};
|
||
}
|
||
return {
|
||
runAddressLane: false,
|
||
decision: "skip_address_lane",
|
||
reason: "no_address_signal_after_l0"
|
||
};
|
||
}
|
||
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 = 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 organizationClarificationContinuation = resolveOrganizationClarificationContinuation({
|
||
rawMessages: [
|
||
rawUserMessage,
|
||
repairedRawUserMessage,
|
||
effectiveAddressUserMessage,
|
||
repairedEffectiveAddressUserMessage
|
||
],
|
||
organizationClarificationCandidates,
|
||
organizationClarificationSelectionFromScope: organizationAuthority.organizationClarificationSelectionFromScope,
|
||
lastOrganizationClarificationDebug,
|
||
resolveOrganizationSelectionFromMessage,
|
||
toNonEmptyString,
|
||
normalizeOrganizationScopeValue
|
||
});
|
||
const explicitOrganizationClarificationSelection = organizationClarificationContinuation.explicitSelection;
|
||
const organizationClarificationSelection = organizationClarificationContinuation.selection;
|
||
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 llmContractIntent = toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.intent);
|
||
const assistantTurnMeaning =
|
||
typeof resolveAssistantTurnMeaning === "function"
|
||
? resolveAssistantTurnMeaning({
|
||
rawUserMessage,
|
||
effectiveAddressUserMessage,
|
||
repairedRawUserMessage,
|
||
repairedEffectiveAddressUserMessage,
|
||
llmPreDecomposeMeta
|
||
})
|
||
: null;
|
||
const turnMeaningIntentCandidate = toNonEmptyString(assistantTurnMeaning?.explicit_intent_candidate);
|
||
const baseResolvedIntentResolution = intentResolution.intent !== "unknown" ? intentResolution : intentResolutionRaw;
|
||
const resolvedIntentResolution =
|
||
turnMeaningIntentCandidate &&
|
||
baseResolvedIntentResolution.intent === "unknown" &&
|
||
ADDRESS_INTENTS_KEEP_ADDRESS_LANE.has(turnMeaningIntentCandidate)
|
||
? {
|
||
intent: turnMeaningIntentCandidate,
|
||
confidence: assistantTurnMeaning?.meaning_confidence === "high" ? "high" : "medium",
|
||
reasons: [
|
||
"assistant_turn_meaning_intent_recovery",
|
||
...(Array.isArray(assistantTurnMeaning?.reason_codes) ? assistantTurnMeaning.reason_codes : [])
|
||
]
|
||
}
|
||
: baseResolvedIntentResolution;
|
||
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 &&
|
||
explicitOrganizationClarificationSelection &&
|
||
!dataScopeMetaQuery &&
|
||
!capabilityMetaQuery &&
|
||
!dataRetrievalSignal);
|
||
const organizationScopeSwitchDetected = Boolean(explicitOrganizationClarificationSelection &&
|
||
!organizationClarificationContinuationDetected &&
|
||
!dataScopeMetaQuery &&
|
||
!capabilityMetaQuery &&
|
||
(shouldEmitOrganizationSelectionReply(rawUserMessage, organizationClarificationSelection) ||
|
||
shouldEmitOrganizationSelectionReply(repairedRawUserMessage, organizationClarificationSelection) ||
|
||
shouldEmitOrganizationSelectionReply(effectiveAddressUserMessage, organizationClarificationSelection) ||
|
||
shouldEmitOrganizationSelectionReply(repairedEffectiveAddressUserMessage, organizationClarificationSelection)));
|
||
const effectiveAddressFollowupSignal = explicitAddressFollowupSignal && !dangerOrCoercionSignal;
|
||
const baseToolGate = typeof resolveAddressToolGateDecisionOverride === "function"
|
||
? resolveAddressToolGateDecisionOverride(effectiveAddressUserMessage, followupContext, llmPreDecomposeMeta, rawUserMessage)
|
||
: resolveBaseAddressToolGateDecision(effectiveAddressUserMessage, followupContext, llmPreDecomposeMeta, rawUserMessage);
|
||
const deterministicNonDomainGuard = Boolean(!dataScopeMetaQuery &&
|
||
!capabilityMetaQuery &&
|
||
!dataRetrievalSignal &&
|
||
!aggregateBusinessAnalyticsSignal &&
|
||
!effectiveAddressFollowupSignal &&
|
||
resolvedModeDetection.mode === "unsupported" &&
|
||
resolvedIntentResolution.intent === "unknown");
|
||
const groundedValueFlowFollowupContextDetected = Boolean(followupContext &&
|
||
[
|
||
"counterparty_value_flow_query_movements_v1",
|
||
"counterparty_supplier_payout_query_movements_v1",
|
||
"counterparty_bidirectional_value_flow_query_movements_v1"
|
||
].includes(String(toNonEmptyString(followupContext?.previous_discovery_pilot_scope) ?? "")) &&
|
||
!dangerOrCoercionSignal &&
|
||
(toNonEmptyString(assistantTurnMeaning?.asked_domain_family) === "counterparty_value" ||
|
||
[
|
||
"turnover",
|
||
"payout",
|
||
"net_value_flow"
|
||
].includes(String(toNonEmptyString(assistantTurnMeaning?.asked_action_family) ?? "")) ||
|
||
/(?:нетто|сальдо|сколько\s+мы\s+(?:получили|заплатили)|incoming|outgoing)/iu.test(analyticsSample)));
|
||
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 ?? ""))) ||
|
||
Boolean(baseToolGate?.runAddressLane &&
|
||
String(baseToolGate?.reason ?? "") === "followup_context_detected" &&
|
||
groundedValueFlowFollowupContextDetected);
|
||
const nonDomainQueryIndexed = Boolean(!llmFirstAddressCandidate &&
|
||
deterministicNonDomainGuard &&
|
||
(llmFirstUnsupportedCandidate || llmContractMode === null) &&
|
||
!baseToolGatePreservesAddressLane &&
|
||
!groundedValueFlowFollowupContextDetected &&
|
||
!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"
|
||
}
|
||
}
|
||
};
|
||
}
|
||
const unsupportedCurrentTurnMeaningBoundary = Boolean(
|
||
assistantTurnMeaning?.unsupported_but_understood_family &&
|
||
assistantTurnMeaning?.stale_replay_forbidden === true &&
|
||
!turnMeaningIntentCandidate &&
|
||
!aggregateBusinessAnalyticsSignal &&
|
||
!dataScopeMetaQuery &&
|
||
!capabilityMetaQuery &&
|
||
!dangerOrCoercionSignal &&
|
||
!groundedValueFlowFollowupContextDetected &&
|
||
!organizationClarificationContinuationDetected);
|
||
if (unsupportedCurrentTurnMeaningBoundary) {
|
||
return {
|
||
runAddressLane: false,
|
||
toolGateDecision: "skip_address_lane",
|
||
toolGateReason: "unsupported_current_turn_meaning_boundary",
|
||
livingMode: "chat",
|
||
livingReason: "unsupported_current_turn_meaning_boundary",
|
||
orchestrationContract: {
|
||
schema_version: "assistant_orchestration_contract_v1",
|
||
hard_meta_mode: null,
|
||
provider_execution: providerExecution,
|
||
assistant_turn_meaning: assistantTurnMeaning,
|
||
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_current_turn_meaning_boundary: true,
|
||
unsupported_current_turn_family: assistantTurnMeaning.unsupported_but_understood_family,
|
||
unsupported_address_intent_fallback_to_deep: false,
|
||
final_decision: {
|
||
run_address_lane: false,
|
||
tool_gate_decision: "skip_address_lane",
|
||
tool_gate_reason: "unsupported_current_turn_meaning_boundary",
|
||
living_mode: "chat",
|
||
living_reason: "unsupported_current_turn_meaning_boundary"
|
||
}
|
||
}
|
||
};
|
||
}
|
||
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"
|
||
}
|
||
}
|
||
};
|
||
}
|
||
if (organizationScopeSwitchDetected) {
|
||
return {
|
||
runAddressLane: false,
|
||
toolGateDecision: "skip_address_lane",
|
||
toolGateReason: "organization_scope_switch_detected",
|
||
livingMode: "chat",
|
||
livingReason: "organization_scope_switch_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 || continuitySnapshot.hasGroundedAddressContext),
|
||
organization_scope_switch_detected: true,
|
||
organization_scope_selection: organizationClarificationSelection,
|
||
unsupported_address_intent_fallback_to_deep: false,
|
||
final_decision: {
|
||
run_address_lane: false,
|
||
tool_gate_decision: "skip_address_lane",
|
||
tool_gate_reason: "organization_scope_switch_detected",
|
||
living_mode: "chat",
|
||
living_reason: "organization_scope_switch_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 answerInspectionFollowupSignal = metaSignals.answerInspectionFollowupSignal;
|
||
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 deepAnalysisPreferenceDetected = Boolean(hasDeepAnalysisPreferenceSignal(rawUserMessage) ||
|
||
hasDeepAnalysisPreferenceSignal(repairedRawUserMessage) ||
|
||
hasDeepAnalysisPreferenceSignal(effectiveAddressUserMessage) ||
|
||
hasDeepAnalysisPreferenceSignal(repairedEffectiveAddressUserMessage) ||
|
||
hasDirectDeepAnalysisSignal(rawUserMessage) ||
|
||
hasDirectDeepAnalysisSignal(repairedRawUserMessage) ||
|
||
hasDirectDeepAnalysisSignal(effectiveAddressUserMessage) ||
|
||
hasDirectDeepAnalysisSignal(repairedEffectiveAddressUserMessage));
|
||
const laneProtectionArbitration = resolveAddressLaneProtectionArbitration({
|
||
resolvedIntent: resolvedIntentResolution.intent,
|
||
llmContractIntent,
|
||
llmContractMode,
|
||
strictDeepInvestigationCueDetected,
|
||
strictDeepInvestigationBypassAllowed,
|
||
openContractsAddressSignal,
|
||
keepAddressLaneByIntent,
|
||
baseToolGateRunAddressLane: Boolean(baseToolGate?.runAddressLane),
|
||
baseToolGateReason: baseToolGate?.reason,
|
||
semanticExtractionContract,
|
||
followupContext,
|
||
rootContextOnlyFollowup,
|
||
semanticApplyCanonicalRecommended,
|
||
deepAnalysisPreferenceDetected
|
||
});
|
||
const supportedAddressIntentDetected = laneProtectionArbitration.supportedAddressIntentDetected;
|
||
const supportedAddressRouteCandidateDetected = laneProtectionArbitration.supportedAddressRouteCandidateDetected;
|
||
const semanticDeepInvestigationHintDetected = laneProtectionArbitration.semanticDeepInvestigationHintDetected;
|
||
const semanticAggregateShapeDetected = laneProtectionArbitration.semanticAggregateShapeDetected;
|
||
const followupSemanticOverrideToDeepAllowed = laneProtectionArbitration.followupSemanticOverrideToDeepAllowed;
|
||
const unsupportedIntentOrMode = (resolvedModeDetection.mode !== "address_query" && resolvedIntentResolution.intent === "unknown") ||
|
||
llmContractMode === "unsupported" ||
|
||
(rootContextOnlyFollowup &&
|
||
resolvedIntentResolution.intent === "unknown" &&
|
||
(!llmContractIntent || llmContractIntent === "unknown"));
|
||
const exactAddressIntentProtectedFromSemanticDeepHint = laneProtectionArbitration.exactAddressIntentProtectedFromSemanticDeepHint;
|
||
const protectAddressLaneFromFallback = laneProtectionArbitration.protectAddressLaneFromFallback;
|
||
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 hasDeepSessionContinuationSignalDetected = hasDeepSessionContinuationSignal({
|
||
rawUserMessage,
|
||
repairedRawUserMessage,
|
||
effectiveAddressUserMessage,
|
||
repairedEffectiveAddressUserMessage,
|
||
sessionItems
|
||
});
|
||
const finalizedDeepFallbackArbitration = resolveAddressFallbackToDeepArbitration({
|
||
baseToolGateRunAddressLane: Boolean(baseToolGate?.runAddressLane),
|
||
llmRuntimeUnavailableDetected,
|
||
unsupportedIntentOrMode,
|
||
strongDataSignal,
|
||
rootContextOnlyFollowup,
|
||
llmContractMode,
|
||
strictDeepInvestigationCueDetected,
|
||
semanticDeepInvestigationHintDetected,
|
||
aggregateBusinessAnalyticsSignal,
|
||
preserveAddressLaneSignal,
|
||
supportedAddressRouteCandidateDetected,
|
||
followupContext,
|
||
followupSemanticOverrideToDeepAllowed,
|
||
deepAnalysisPreferenceDetected,
|
||
protectAddressLaneFromFallback,
|
||
dataRetrievalSignal,
|
||
vatExplainFollowupSignal,
|
||
semanticAggregateShapeDetected,
|
||
semanticApplyCanonicalRecommended,
|
||
standaloneAddressTopicSignal,
|
||
hasDeepSessionContinuationSignalDetected
|
||
});
|
||
const unsupportedAddressIntentFallbackToDeep = finalizedDeepFallbackArbitration.unsupportedAddressIntentFallbackToDeep;
|
||
const deepAnalysisSignalFallbackToDeep = finalizedDeepFallbackArbitration.deepAnalysisSignalFallbackToDeep;
|
||
const aggregateAnalyticsFallbackToDeep = finalizedDeepFallbackArbitration.aggregateAnalyticsFallbackToDeep;
|
||
const deepSessionContinuationFallbackToDeep = finalizedDeepFallbackArbitration.deepSessionContinuationFallbackToDeep;
|
||
const hasPriorAddressAnswerContext = Boolean(lastGroundedAddressDebug ||
|
||
continuitySnapshot.hasGroundedAddressContext ||
|
||
toNonEmptyString(followupContext?.previous_intent));
|
||
const metaFollowupOverGroundedAnswer = isMetaFollowupOverGroundedAnswer({
|
||
followupContext,
|
||
hasPriorAddressAnswerContext,
|
||
metaAnswerFollowupSignal,
|
||
answerInspectionFollowupSignal,
|
||
vatEvaluativeFollowupSignal,
|
||
dataScopeMetaQuery,
|
||
capabilityMetaQuery,
|
||
aggregateBusinessAnalyticsSignal,
|
||
dataRetrievalSignal,
|
||
strongDataSignal,
|
||
resolvedMode: resolvedModeDetection.mode,
|
||
resolvedIntent: resolvedIntentResolution.intent,
|
||
llmContractIntent,
|
||
llmContractMode
|
||
});
|
||
const answerInspectionFollowupOverGroundedAnswer = isAnswerInspectionFollowupOverGroundedAnswer({
|
||
followupContext,
|
||
hasPriorAddressAnswerContext,
|
||
metaAnswerFollowupSignal,
|
||
answerInspectionFollowupSignal,
|
||
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");
|
||
const semanticAddressLaneRecovery = Boolean(!runAddressLane &&
|
||
supportedAddressRouteCandidateDetected &&
|
||
!deepAnalysisPreferenceDetected &&
|
||
!unsupportedAddressIntentFallbackToDeep &&
|
||
!deepAnalysisSignalFallbackToDeep &&
|
||
!aggregateAnalyticsFallbackToDeep &&
|
||
!deepSessionContinuationFallbackToDeep);
|
||
if (semanticAddressLaneRecovery) {
|
||
runAddressLane = true;
|
||
toolGateDecision = "run_address_lane";
|
||
toolGateReason = resolvedIntentResolution.intent !== "unknown" || llmContractIntent
|
||
? "address_intent_resolver_detected"
|
||
: "address_signal_detected";
|
||
}
|
||
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";
|
||
}
|
||
if (answerInspectionFollowupOverGroundedAnswer) {
|
||
runAddressLane = false;
|
||
toolGateDecision = "skip_address_lane";
|
||
toolGateReason = "answer_inspection_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"
|
||
};
|
||
}
|
||
if (answerInspectionFollowupOverGroundedAnswer) {
|
||
livingDecision = {
|
||
mode: "chat",
|
||
reason: "answer_inspection_followup_detected"
|
||
};
|
||
}
|
||
return {
|
||
runAddressLane,
|
||
toolGateDecision,
|
||
toolGateReason,
|
||
livingMode: livingDecision.mode,
|
||
livingReason: livingDecision.reason,
|
||
orchestrationContract: {
|
||
schema_version: "assistant_orchestration_contract_v1",
|
||
hard_meta_mode: null,
|
||
provider_execution: providerExecution,
|
||
assistant_turn_meaning: assistantTurnMeaning,
|
||
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,
|
||
answer_inspection_followup_over_grounded_answer: answerInspectionFollowupOverGroundedAnswer,
|
||
final_decision: {
|
||
run_address_lane: runAddressLane,
|
||
tool_gate_decision: toolGateDecision,
|
||
tool_gate_reason: toolGateReason,
|
||
living_mode: livingDecision.mode,
|
||
living_reason: livingDecision.reason
|
||
}
|
||
}
|
||
};
|
||
}
|
||
return {
|
||
resolveAssistantOrchestrationDecision
|
||
};
|
||
}
|