"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.supplyResponseToAskerDialog = supplyResponseToAskerDialog;
exports.supplySideDialogResponseToSpecificAskerIfPendingV2 = supplySideDialogResponseToSpecificAskerIfPendingV2;
exports.supplySideDialogResponseToAssignedAskerIfPendingV2 = supplySideDialogResponseToAssignedAskerIfPendingV2;
const storage_1 = require("@longrun-ai/kernel/types/storage");
const time_1 = require("@longrun-ai/kernel/utils/time");
const dialog_1 = require("../../dialog");
const dialog_display_state_1 = require("../../dialog-display-state");
const dialog_global_registry_1 = require("../../dialog-global-registry");
const dialog_instance_registry_1 = require("../../dialog-instance-registry");
const log_1 = require("../../log");
const persistence_1 = require("../../persistence");
const background_callee_summary_1 = require("../../runtime/background-callee-summary");
const inter_dialog_format_1 = require("../../runtime/inter-dialog-format");
const work_language_1 = require("../../runtime/work-language");
const pending_tellask_reminder_1 = require("../../tools/pending-tellask-reminder");
const sideDialog_txn_1 = require("./sideDialog-txn");
async function syncPendingTellaskReminderBestEffort(dlg, where) {
    try {
        const changed = await (0, pending_tellask_reminder_1.syncPendingTellaskReminderState)(dlg);
        if (!changed)
            return;
        await dlg.processReminderUpdates();
    }
    catch (err) {
        log_1.log.warn('Failed to sync pending tellask reminder', undefined, {
            where,
            dialogId: dlg.id.selfId,
            rootId: dlg.id.rootId,
            error: err instanceof Error ? err.message : String(err),
        });
    }
}
async function resolveCallerDialogBySelfId(sideDialog, callerDialogId) {
    const mainDialog = sideDialog.mainDialog;
    if (!(await ensureDialogFreshOrDiscard(mainDialog, 'resolveCallerDialogBySelfId:root'))) {
        return undefined;
    }
    if (callerDialogId === mainDialog.id.selfId) {
        return mainDialog;
    }
    const existing = mainDialog.lookupDialog(callerDialogId);
    if (existing) {
        if (!(await ensureDialogFreshOrDiscard(existing, 'resolveCallerDialogBySelfId:lookup'))) {
            return undefined;
        }
        return existing;
    }
    const restored = await (0, dialog_instance_registry_1.ensureDialogLoaded)(mainDialog, new dialog_1.DialogID(callerDialogId, mainDialog.id.rootId), mainDialog.status);
    if (!restored) {
        return undefined;
    }
    if (!(await ensureDialogFreshOrDiscard(restored, 'resolveCallerDialogBySelfId:restore'))) {
        return undefined;
    }
    return restored;
}
async function ensureDialogFreshOrDiscard(dialog, where) {
    try {
        const metadata = await persistence_1.DialogPersistence.loadDialogMetadata(dialog.id, dialog.status);
        if (metadata) {
            return true;
        }
        const statuses = ['running', 'completed', 'archived'];
        for (const status of statuses) {
            if (status === dialog.status) {
                continue;
            }
            const other = await persistence_1.DialogPersistence.loadDialogMetadata(dialog.id, status);
            if (other) {
                log_1.log.warn('kernel-driver discarding stale dialog object due to persisted status mismatch', undefined, {
                    where,
                    rootId: dialog.id.rootId,
                    selfId: dialog.id.selfId,
                    inMemoryStatus: dialog.status,
                    persistedStatus: status,
                });
                if (dialog instanceof dialog_1.MainDialog) {
                    dialog_global_registry_1.globalDialogRegistry.unregister(dialog.id.rootId);
                }
                return false;
            }
        }
        if (dialog instanceof dialog_1.MainDialog && dialog.status === 'running') {
            const createdAt = (0, time_1.formatUnifiedTimestamp)(new Date());
            await persistence_1.DialogPersistence.saveDialogMetadata(dialog.id, {
                id: dialog.id.selfId,
                agentId: dialog.agentId,
                taskDocPath: dialog.taskDocPath,
                createdAt,
            }, 'running');
            log_1.log.warn('kernel-driver auto-persisted missing main dialog metadata', undefined, {
                where,
                rootId: dialog.id.rootId,
                selfId: dialog.id.selfId,
            });
            return true;
        }
    }
    catch (err) {
        log_1.log.warn('kernel-driver failed to verify dialog freshness against persisted status', undefined, {
            where,
            rootId: dialog.id.rootId,
            selfId: dialog.id.selfId,
            status: dialog.status,
            error: err instanceof Error ? err.message : String(err),
        });
    }
    log_1.log.warn('kernel-driver discarding stale dialog object due to status/path mismatch', undefined, {
        where,
        rootId: dialog.id.rootId,
        selfId: dialog.id.selfId,
        status: dialog.status,
    });
    if (dialog instanceof dialog_1.MainDialog) {
        dialog_global_registry_1.globalDialogRegistry.unregister(dialog.id.rootId);
    }
    return false;
}
async function resolveLatestAssignmentAnchorRef(args) {
    const normalizedCallId = args.callId.trim();
    if (normalizedCallId === '') {
        return undefined;
    }
    const latest = await persistence_1.DialogPersistence.loadDialogLatest(args.calleeDialogId, args.status);
    if (!latest) {
        return undefined;
    }
    const latestAssignmentAnchor = latest.latestAssignmentAnchor;
    if (latestAssignmentAnchor?.callId !== normalizedCallId) {
        return undefined;
    }
    return {
        course: latestAssignmentAnchor.assignmentCourse,
        genseq: latestAssignmentAnchor.assignmentGenseq,
    };
}
async function supplyResponseToAskerDialog(args) {
    const { callerDialog, sideDialogId, responseText, callType, callId, status = 'completed', deliveryMode = 'reply_tool', directFallbackSource, calleeResponseRef, askerCourseOverride, scheduleDrive, sideDialog: maybeSideDialog, } = args;
    const requestedCallId = typeof callId === 'string' ? callId.trim() : '';
    if (requestedCallId === '') {
        throw new Error(`sideDialog response supply invariant violation: callId is required ` +
            `(callerId=${callerDialog.id.selfId}, sideDialogId=${sideDialogId.selfId})`);
    }
    try {
        const result = await (0, sideDialog_txn_1.withSideDialogTxnLock)(callerDialog.id, async () => {
            const activeCalleeDispatches = await persistence_1.DialogPersistence.loadActiveCalleeDispatches(callerDialog.id, callerDialog.status);
            let activeCalleeDispatch;
            for (const dispatch of activeCalleeDispatches) {
                if (dispatch.calleeDialogId === sideDialogId.selfId &&
                    dispatch.callId === requestedCallId &&
                    activeCalleeDispatch === undefined) {
                    activeCalleeDispatch = dispatch;
                }
            }
            let responderId = sideDialogId.rootId;
            let responderAgentId;
            let callName = 'tellaskSessionless';
            let mentionList;
            let tellaskContent = responseText;
            let originMemberId;
            let sessionSlug;
            try {
                const metadata = await persistence_1.DialogPersistence.loadDialogMetadata(sideDialogId, callerDialog.status);
                if (metadata) {
                    const assignmentFromAsker = await persistence_1.DialogPersistence.loadSideDialogAssignmentFromAsker(sideDialogId, callerDialog.status);
                    originMemberId = assignmentFromAsker.originMemberId;
                    if (!activeCalleeDispatch) {
                        callName = assignmentFromAsker.callName;
                        mentionList = assignmentFromAsker.mentionList;
                        tellaskContent = assignmentFromAsker.tellaskContent;
                    }
                    if (!activeCalleeDispatch && metadata.agentId.trim() !== '') {
                        responderId = metadata.agentId;
                        responderAgentId = metadata.agentId;
                    }
                }
            }
            catch (err) {
                log_1.log.warn('Failed to load sideDialog metadata for response record', undefined, {
                    callerId: callerDialog.id.selfId,
                    sideDialogId: sideDialogId.selfId,
                    error: err,
                });
            }
            if (!originMemberId) {
                originMemberId = callerDialog.agentId;
            }
            if (activeCalleeDispatch) {
                callName = activeCalleeDispatch.callName;
                responderId = activeCalleeDispatch.targetAgentId;
                responderAgentId = activeCalleeDispatch.targetAgentId;
                mentionList = activeCalleeDispatch.mentionList;
                tellaskContent = activeCalleeDispatch.tellaskContent;
                sessionSlug = activeCalleeDispatch.sessionSlug;
            }
            if ((callName === 'tellask' || callName === 'tellaskSessionless') &&
                (!Array.isArray(mentionList) || mentionList.length < 1)) {
                mentionList = [`@${responderId}`];
            }
            const activeCalleeOutcome = activeCalleeDispatch === undefined
                ? undefined
                : await persistence_1.DialogPersistence.resolveActiveCallee(callerDialog.id, {
                    batchId: activeCalleeDispatch.batchId,
                    callId: activeCalleeDispatch.callId,
                    sideDialogId: sideDialogId.selfId,
                    deliveryMode,
                    directFallbackSource,
                }, callerDialog.status);
            const hasQ4H = await callerDialog.hasPendingQ4H();
            const batchCompleted = activeCalleeOutcome?.batchCompleted === true;
            const shouldDriveContinuation = batchCompleted && !hasQ4H;
            if (batchCompleted && activeCalleeOutcome !== undefined) {
                await persistence_1.DialogPersistence.upsertNextStepTrigger(callerDialog.id, {
                    triggerId: `result-arrival:${activeCalleeOutcome.batchId}`,
                    kind: 'result_arrival',
                    batchId: activeCalleeOutcome.batchId,
                }, callerDialog.status);
                dialog_global_registry_1.globalDialogRegistry.queueRootDrive(callerDialog.id.rootId, {
                    source: 'kernel_driver_supply_response',
                    reason: `result_arrival_triggered:type_${callType}`,
                });
            }
            if (activeCalleeOutcome !== undefined) {
                await (0, background_callee_summary_1.broadcastBackgroundCalleeSummary)(callerDialog);
            }
            return {
                responderId,
                responderAgentId,
                callName,
                mentionList,
                tellaskContent,
                originMemberId,
                sessionSlug,
                callId: activeCalleeDispatch?.callId,
                callSiteCourse: activeCalleeOutcome?.callSiteCourse ?? activeCalleeDispatch?.callSiteCourse,
                callSiteGenseq: activeCalleeOutcome?.callSiteGenseq ?? activeCalleeDispatch?.callSiteGenseq,
                batchId: activeCalleeOutcome?.batchId ?? activeCalleeDispatch?.batchId,
                resolvedCallIds: activeCalleeOutcome?.resolvedCallIds ?? [],
                askerCourse: activeCalleeDispatch?.callSiteCourse !== undefined
                    ? (0, storage_1.toAskerCourseNumber)(activeCalleeDispatch.callSiteCourse)
                    : askerCourseOverride,
                shouldDriveContinuation,
            };
        });
        const normalizedCallId = requestedCallId;
        const fallbackCallId = typeof result.callId === 'string' ? result.callId.trim() : '';
        const resolvedCallId = normalizedCallId !== '' ? normalizedCallId : fallbackCallId;
        const rootForLookup = callerDialog instanceof dialog_1.MainDialog
            ? callerDialog
            : callerDialog instanceof dialog_1.SideDialog
                ? callerDialog.mainDialog
                : undefined;
        const lookedUpSideDialog = rootForLookup?.lookupDialog(sideDialogId.selfId);
        const resolvedSideDialog = maybeSideDialog ??
            (lookedUpSideDialog instanceof dialog_1.SideDialog ? lookedUpSideDialog : undefined);
        const tellaskerResponseBody = responseText;
        const tellaskerId = result.originMemberId ?? callerDialog.agentId;
        const tellaskerResponseText = (0, inter_dialog_format_1.formatTellaskResponseContent)({
            callName: result.callName,
            callId: resolvedCallId,
            responderId: result.responderId,
            tellaskerId,
            mentionList: result.mentionList,
            sessionSlug: result.sessionSlug,
            tellaskContent: result.tellaskContent,
            responseBody: tellaskerResponseBody,
            status,
            deliveryMode,
            directFallbackSource,
            language: (0, work_language_1.getWorkLanguage)(),
        });
        const carryoverCallSiteCourse = result.callSiteCourse;
        let assignmentRef;
        const carryoverContent = carryoverCallSiteCourse !== undefined &&
            carryoverCallSiteCourse !== callerDialog.currentCourse
            ? (0, inter_dialog_format_1.formatTellaskCarryoverResultContent)({
                callSiteCourse: carryoverCallSiteCourse,
                callName: result.callName,
                callId: resolvedCallId,
                responderId: result.responderId,
                mentionList: result.mentionList,
                sessionSlug: result.sessionSlug,
                tellaskContent: result.tellaskContent,
                responseBody: tellaskerResponseBody,
                status,
                language: (0, work_language_1.getWorkLanguage)(),
            })
            : undefined;
        if (resolvedCallId !== '' && calleeResponseRef) {
            const askerCourse = result.askerCourse;
            if (askerCourse === undefined) {
                throw new Error(`tellask response anchor invariant violation: missing askerCourse ` +
                    `(callerId=${callerDialog.id.selfId}, sideDialogId=${sideDialogId.selfId}, callId=${resolvedCallId})`);
            }
            assignmentRef = await resolveLatestAssignmentAnchorRef({
                calleeDialogId: sideDialogId,
                callId: resolvedCallId,
                status: callerDialog.status,
            });
            if (!assignmentRef) {
                // A Side Dialog can legitimately finish a pending tellask before the queued assignment
                // prompt for that call is rendered locally, for example after a direct user nudge inside
                // the Side Dialog. Keep the asker deep-link anchor, but do not treat the missing
                // local assignment bubble as an invariant violation.
                log_1.log.debug('Tellask response anchor has no local assignment anchor', undefined, {
                    callerId: callerDialog.id.selfId,
                    sideDialogId: sideDialogId.selfId,
                    callId: resolvedCallId,
                    responseCourse: calleeResponseRef.course,
                    responseGenseq: calleeResponseRef.genseq,
                });
            }
            if (args.replyResolution) {
                const replyResolutionRecord = {
                    ts: (0, time_1.formatUnifiedTimestamp)(new Date()),
                    type: 'tellask_reply_resolution_record',
                    genseq: calleeResponseRef.genseq,
                    callId: args.replyResolution.callId,
                    replyCallName: args.replyResolution.replyCallName,
                    targetCallId: resolvedCallId,
                    ...(0, storage_1.toRootGenerationAnchor)({
                        rootCourse: callerDialog instanceof dialog_1.SideDialog
                            ? callerDialog.mainDialog.currentCourse
                            : callerDialog.currentCourse,
                        rootGenseq: callerDialog instanceof dialog_1.SideDialog
                            ? (callerDialog.mainDialog.activeGenSeqOrUndefined ?? 0)
                            : (callerDialog.activeGenSeqOrUndefined ?? 0),
                    }),
                };
                await persistence_1.DialogPersistence.appendEvent(sideDialogId, calleeResponseRef.course, replyResolutionRecord, callerDialog.status);
                await persistence_1.DialogPersistence.markReplyDeliveryDelivered(sideDialogId, args.replyResolution.callId, replyResolutionRecord.ts, callerDialog.status);
                const activeReplyObligation = await persistence_1.DialogPersistence.loadActiveTellaskReplyObligation(sideDialogId, callerDialog.status);
                if (activeReplyObligation?.targetCallId === resolvedCallId) {
                    await persistence_1.DialogPersistence.setActiveTellaskReplyObligation(sideDialogId, undefined, callerDialog.status);
                    if (maybeSideDialog) {
                        const nextAskerStackState = await persistence_1.DialogPersistence.loadSideDialogAskerStackState(maybeSideDialog.id, maybeSideDialog.status);
                        if (!nextAskerStackState) {
                            throw new Error(`Missing asker stack after reply obligation pop: ${maybeSideDialog.id.valueOf()}`);
                        }
                        maybeSideDialog.askerStack = nextAskerStackState;
                    }
                }
            }
            const anchorRecord = {
                ts: (0, time_1.formatUnifiedTimestamp)(new Date()),
                type: 'tellask_anchor_record',
                anchorRole: 'response',
                callId: resolvedCallId,
                genseq: calleeResponseRef.genseq,
                ...(0, storage_1.toRootGenerationAnchor)({
                    rootCourse: callerDialog instanceof dialog_1.SideDialog
                        ? callerDialog.mainDialog.currentCourse
                        : callerDialog.currentCourse,
                    rootGenseq: callerDialog instanceof dialog_1.SideDialog
                        ? (callerDialog.mainDialog.activeGenSeqOrUndefined ?? 0)
                        : (callerDialog.activeGenSeqOrUndefined ?? 0),
                }),
                assignmentCourse: assignmentRef?.course,
                assignmentGenseq: assignmentRef?.genseq,
                askerDialogId: callerDialog.id.selfId,
                askerCourse,
            };
            await persistence_1.DialogPersistence.appendEvent(sideDialogId, calleeResponseRef.course, anchorRecord, callerDialog.status);
            await persistence_1.DialogPersistence.mutateDialogLatest(sideDialogId, () => ({
                kind: 'patch',
                patch: {
                    sideDialogFinalResponse: {
                        callId: resolvedCallId,
                        responseCourse: (0, storage_1.toDialogCourseNumber)(calleeResponseRef.course),
                        responseGenseq: (0, storage_1.toCalleeGenerationSeqNumber)(calleeResponseRef.genseq),
                        askerDialogId: callerDialog.id.selfId,
                        askerCourse,
                    },
                },
            }), callerDialog.status);
            if (maybeSideDialog) {
                const displayState = await (0, dialog_display_state_1.computeIdleDisplayState)(maybeSideDialog);
                await (0, dialog_display_state_1.setDialogDisplayState)(sideDialogId, displayState, callerDialog.status);
            }
        }
        await syncPendingTellaskReminderBestEffort(callerDialog, 'kernel-driver:supplyResponseToAskerDialog');
        const responseRouteRef = calleeResponseRef;
        await callerDialog.receiveTellaskResponse(result.responderId, result.callName, result.mentionList, result.tellaskContent, status, sideDialogId, {
            response: tellaskerResponseText,
            agentId: result.responderAgentId ?? result.responderId,
            callId: resolvedCallId,
            originMemberId: tellaskerId,
            callSiteCourse: carryoverCallSiteCourse,
            callSiteGenseq: result.callSiteGenseq !== undefined
                ? (0, storage_1.toCallSiteGenseqNo)(result.callSiteGenseq)
                : assignmentRef !== undefined
                    ? (0, storage_1.toCallSiteGenseqNo)(assignmentRef.genseq)
                    : undefined,
            carryoverContent,
            sessionSlug: result.sessionSlug,
            calleeCourse: responseRouteRef !== undefined
                ? (0, storage_1.toCalleeCourseNumber)(responseRouteRef.course)
                : undefined,
            calleeGenseq: responseRouteRef !== undefined
                ? (0, storage_1.toCalleeGenerationSeqNumber)(responseRouteRef.genseq)
                : undefined,
        });
        const immediateMirror = carryoverContent !== undefined
            ? {
                type: 'tellask_carryover_msg',
                role: 'user',
                genseq: callerDialog.activeGenSeqOrUndefined ?? 1,
                content: carryoverContent,
                callSiteCourse: carryoverCallSiteCourse,
                carryoverCourse: callerDialog.currentCourse,
                responderId: result.responderId,
                callName: result.callName,
                tellaskContent: result.tellaskContent,
                status,
                response: tellaskerResponseText,
                agentId: result.responderAgentId ?? result.responderId,
                callId: resolvedCallId,
                originMemberId: tellaskerId,
                ...(result.callName === 'tellask'
                    ? {
                        mentionList: result.mentionList ?? [],
                        sessionSlug: result.sessionSlug,
                    }
                    : result.callName === 'tellaskSessionless'
                        ? {
                            mentionList: result.mentionList ?? [],
                        }
                        : {}),
                ...(responseRouteRef !== undefined
                    ? {
                        calleeDialogId: sideDialogId.selfId,
                        calleeCourse: responseRouteRef.course,
                        calleeGenseq: responseRouteRef.genseq,
                    }
                    : {
                        calleeDialogId: sideDialogId.selfId,
                    }),
            }
            : {
                type: 'tellask_result_msg',
                role: 'tool',
                callId: resolvedCallId,
                callName: result.callName,
                status,
                content: tellaskerResponseText,
                ...(result.callSiteCourse !== undefined
                    ? { callSiteCourse: result.callSiteCourse }
                    : {}),
                ...(result.callSiteGenseq !== undefined
                    ? { callSiteGenseq: result.callSiteGenseq }
                    : assignmentRef !== undefined
                        ? { callSiteGenseq: assignmentRef.genseq }
                        : {}),
                call: result.callName === 'tellask'
                    ? {
                        tellaskContent: result.tellaskContent,
                        mentionList: result.mentionList ?? [],
                        ...(result.sessionSlug ? { sessionSlug: result.sessionSlug } : {}),
                    }
                    : result.callName === 'tellaskSessionless'
                        ? {
                            tellaskContent: result.tellaskContent,
                            mentionList: result.mentionList ?? [],
                        }
                        : {
                            tellaskContent: result.tellaskContent,
                        },
                responder: {
                    responderId: result.responderId,
                    agentId: result.responderAgentId ?? result.responderId,
                    originMemberId: tellaskerId,
                },
                route: {
                    calleeDialogId: sideDialogId.selfId,
                    ...(responseRouteRef !== undefined
                        ? {
                            calleeCourse: responseRouteRef.course,
                            calleeGenseq: responseRouteRef.genseq,
                        }
                        : {}),
                },
            };
        await callerDialog.addChatMessages(immediateMirror);
        if (result.shouldDriveContinuation) {
            const isRoot = callerDialog instanceof dialog_1.MainDialog;
            const hasRegistryEntry = isRoot
                ? dialog_global_registry_1.globalDialogRegistry.get(callerDialog.id.rootId) !== undefined
                : false;
            log_1.log.debug(`All Type ${callType} sideDialogs complete, caller ${callerDialog.id.selfId} scheduling continuation drive`, undefined, {
                rootId: callerDialog.id.rootId,
                selfId: callerDialog.id.selfId,
                callSiteCourse: result.callSiteCourse,
                callSiteGenseq: result.callSiteGenseq,
                via: isRoot && hasRegistryEntry ? 'backend_loop_trigger' : 'direct_schedule_drive',
                isRoot,
                hasRegistryEntry,
            });
            if (result.callSiteCourse === undefined || result.callSiteGenseq === undefined) {
                throw new Error(`sideDialog result-arrival invariant violation: missing dispatch batch coordinates ` +
                    `(rootId=${callerDialog.id.rootId}, selfId=${callerDialog.id.selfId}, callId=${resolvedCallId})`);
            }
            if (result.batchId === undefined) {
                throw new Error(`sideDialog result-arrival invariant violation: missing batchId ` +
                    `(rootId=${callerDialog.id.rootId}, selfId=${callerDialog.id.selfId}, callId=${resolvedCallId})`);
            }
            scheduleDrive(callerDialog, {
                waitInQue: true,
                driveOptions: {
                    suppressDiligencePush: callerDialog.disableDiligencePush,
                    businessContinuation: {
                        kind: 'requested_work_reply',
                        callerDialogId: callerDialog.id.selfId,
                        batchId: result.batchId,
                        callSiteCourse: (0, storage_1.toCallSiteCourseNo)(result.callSiteCourse),
                        callSiteGenseq: (0, storage_1.toCallSiteGenseqNo)(result.callSiteGenseq),
                        sideDialogId: sideDialogId.selfId,
                        callType,
                        callId: resolvedCallId,
                        ...(result.resolvedCallIds === undefined
                            ? {}
                            : { resolvedCallIds: result.resolvedCallIds }),
                        triggerCallId: resolvedCallId,
                    },
                    source: 'kernel_driver_business_continuation',
                    reason: `dispatch_batch_resolved:type_${callType}:c${result.callSiteCourse}:g${result.callSiteGenseq}`,
                },
            });
        }
    }
    catch (error) {
        log_1.log.error('kernel-driver failed to supply sideDialog response', error, {
            callerId: callerDialog.id.selfId,
            sideDialogId: sideDialogId.selfId,
        });
        throw error;
    }
}
async function supplySideDialogResponseToSpecificAskerIfPendingV2(args) {
    const { sideDialog, responseText, responseGenseq, target, scheduleDrive } = args;
    const assignment = sideDialog.assignmentFromAsker;
    if (!assignment) {
        return false;
    }
    const callerDialog = await resolveCallerDialogBySelfId(sideDialog, target.callerDialogId);
    if (!callerDialog) {
        return false;
    }
    if (!(await ensureDialogFreshOrDiscard(callerDialog, 'supplySideDialogResponseToSpecificAskerIfPendingV2:caller'))) {
        return false;
    }
    const activeCalleeDispatches = await persistence_1.DialogPersistence.loadActiveCalleeDispatches(callerDialog.id, callerDialog.status);
    const activeCalleeDispatch = activeCalleeDispatches.find((dispatch) => dispatch.calleeDialogId === sideDialog.id.selfId && dispatch.callId === target.callId);
    if (!activeCalleeDispatch) {
        return false;
    }
    if (activeCalleeDispatch.callType !== target.callType) {
        log_1.log.warn('Reply target callType does not match pending callType; skipping stale reply target', undefined, {
            rootId: sideDialog.mainDialog.id.rootId,
            sideDialogId: sideDialog.id.selfId,
            callerDialogId: callerDialog.id.selfId,
            targetCallType: target.callType,
            activeCalleeCallType: activeCalleeDispatch.callType,
        });
        return false;
    }
    if (activeCalleeDispatch.callType === 'B') {
        const assignmentAnchorRef = await resolveLatestAssignmentAnchorRef({
            calleeDialogId: sideDialog.id,
            callId: activeCalleeDispatch.callId,
            status: sideDialog.status,
        });
        if (!assignmentAnchorRef) {
            log_1.log.debug('Skip Type B response supply before updated assignment is rendered locally', undefined, {
                rootId: sideDialog.mainDialog.id.rootId,
                sideDialogId: sideDialog.id.selfId,
                callerDialogId: callerDialog.id.selfId,
                callId: activeCalleeDispatch.callId,
                responseGenseq,
            });
            return false;
        }
        if (sideDialog.currentCourse < assignmentAnchorRef.course ||
            (sideDialog.currentCourse === assignmentAnchorRef.course &&
                responseGenseq < assignmentAnchorRef.genseq)) {
            log_1.log.debug('Skip stale Type B response supply from before latest local assignment', undefined, {
                rootId: sideDialog.mainDialog.id.rootId,
                sideDialogId: sideDialog.id.selfId,
                callerDialogId: callerDialog.id.selfId,
                callId: activeCalleeDispatch.callId,
                responseCourse: sideDialog.currentCourse,
                responseGenseq,
                assignmentCourse: assignmentAnchorRef.course,
                assignmentGenseq: assignmentAnchorRef.genseq,
            });
            return false;
        }
    }
    await supplyResponseToAskerDialog({
        callerDialog: callerDialog,
        sideDialogId: sideDialog.id,
        responseText,
        sideDialog,
        callType: activeCalleeDispatch.callType,
        callId: target.callId,
        status: 'completed',
        deliveryMode: args.deliveryMode,
        directFallbackSource: args.directFallbackSource,
        replyResolution: args.replyResolution,
        calleeResponseRef: { course: sideDialog.currentCourse, genseq: responseGenseq },
        scheduleDrive,
    });
    return true;
}
async function supplySideDialogResponseToAssignedAskerIfPendingV2(args) {
    const { sideDialog, responseText, responseGenseq, scheduleDrive } = args;
    const assignment = sideDialog.assignmentFromAsker;
    if (!assignment) {
        return false;
    }
    const askerDialog = await resolveCallerDialogBySelfId(sideDialog, assignment.askerDialogId);
    if (!askerDialog) {
        log_1.log.warn('Missing tellasker for sideDialog response supply', undefined, {
            rootId: sideDialog.mainDialog.id.rootId,
            sideDialogId: sideDialog.id.selfId,
            askerDialogId: assignment.askerDialogId,
        });
        return false;
    }
    if (!(await ensureDialogFreshOrDiscard(askerDialog, 'supplySideDialogResponseToAssignedAskerIfPendingV2:asker'))) {
        return false;
    }
    const activeCalleeDispatches = await persistence_1.DialogPersistence.loadActiveCalleeDispatches(askerDialog.id, askerDialog.status);
    const activeCalleeDispatch = activeCalleeDispatches.find((dispatch) => dispatch.calleeDialogId === sideDialog.id.selfId && dispatch.callId === assignment.callId);
    if (!activeCalleeDispatch) {
        return false;
    }
    if (activeCalleeDispatch.callType === 'B') {
        const assignmentAnchorRef = await resolveLatestAssignmentAnchorRef({
            calleeDialogId: sideDialog.id,
            callId: activeCalleeDispatch.callId,
            status: sideDialog.status,
        });
        if (!assignmentAnchorRef) {
            const replyResolution = args.replyResolution;
            if (args.allowExplicitReplyWithoutAssignmentAnchor === true &&
                args.deliveryMode === 'reply_tool' &&
                replyResolution !== undefined) {
                log_1.log.warn('Delivering assigned Type B reply without local assignment anchor', undefined, {
                    rootId: sideDialog.mainDialog.id.rootId,
                    sideDialogId: sideDialog.id.selfId,
                    askerDialogId: askerDialog.id.selfId,
                    callId: activeCalleeDispatch.callId,
                    replyCallId: replyResolution.callId,
                    replyCallName: replyResolution.replyCallName,
                    responseCourse: sideDialog.currentCourse,
                    responseGenseq,
                });
            }
            else {
                log_1.log.debug('Skip assigned Type B response supply before updated assignment is rendered locally', undefined, {
                    rootId: sideDialog.mainDialog.id.rootId,
                    sideDialogId: sideDialog.id.selfId,
                    askerDialogId: askerDialog.id.selfId,
                    callId: activeCalleeDispatch.callId,
                    responseGenseq,
                });
                return false;
            }
        }
        if (assignmentAnchorRef !== undefined &&
            (sideDialog.currentCourse < assignmentAnchorRef.course ||
                (sideDialog.currentCourse === assignmentAnchorRef.course &&
                    responseGenseq < assignmentAnchorRef.genseq))) {
            log_1.log.debug('Skip assigned stale Type B response supply from before latest local assignment', undefined, {
                rootId: sideDialog.mainDialog.id.rootId,
                sideDialogId: sideDialog.id.selfId,
                askerDialogId: askerDialog.id.selfId,
                callId: activeCalleeDispatch.callId,
                responseCourse: sideDialog.currentCourse,
                responseGenseq,
                assignmentCourse: assignmentAnchorRef.course,
                assignmentGenseq: assignmentAnchorRef.genseq,
            });
            return false;
        }
    }
    await supplyResponseToAskerDialog({
        callerDialog: askerDialog,
        sideDialogId: sideDialog.id,
        responseText,
        sideDialog,
        callType: activeCalleeDispatch.callType,
        callId: assignment.callId,
        status: 'completed',
        deliveryMode: args.deliveryMode,
        directFallbackSource: args.directFallbackSource,
        replyResolution: args.replyResolution,
        calleeResponseRef: { course: sideDialog.currentCourse, genseq: responseGenseq },
        scheduleDrive,
    });
    return true;
}
