import { BestAgentError } from "@best-agent/foundation";
import { formatAskUserAnswers, normalizeAskUserInput, } from "../../tool/registry.js";
import { persistToolOutput } from "./tool-result-persistence.js";
export async function executeAskUserTool(input) {
    const { options, persistTerminalToolFailure, prepared, preparedToolResumeContext, profileName, runtime, toolCallId, turn, } = input;
    const toolName = "ask-user";
    const actionStartedAt = Date.now();
    const checkpointAction = options.resumeCheckpoint?.kind === "action" &&
        options.resumeCheckpoint.toolCallId === toolCallId &&
        options.resumeCheckpoint.toolName === toolName
        ? options.resumeCheckpoint
        : undefined;
    const resolution = checkpointAction?.resolution ??
        (await runtime.approvals.requestAction(turn, {
            questions: normalizeAskUserInput(prepared.normalizedInput).questions,
            resumeContext: {
                ...preparedToolResumeContext,
                toolCallId,
            },
            toolCallId,
            toolName,
        }));
    if (checkpointAction?.resolution) {
        await runtime.approvals.recordActionResolvedControl(turn, checkpointAction.actionId, toolName, toolCallId);
    }
    if (await runtime.interruptions.isInterrupted(turn)) {
        await persistTerminalToolFailure(toolCallId, prepared.normalizedInput, {
            ...preparedToolResumeContext,
            toolCallId,
        }, new Error("ask-user was interrupted before the user answered."), "ask-user was interrupted before the user answered.");
        await runtime.runCheckpoints.completeRunCheckpoint(turn.id);
        throw runtime.interruptions.createTurnTerminatedError({
            turn: await runtime.turnState.requireTurn(turn.id),
        });
    }
    if (resolution.status !== "answered") {
        await runtime.runCheckpoints.updateRunControlForTurn(turn.id, {
            status: "running",
            waitReason: "none",
        });
        const error = new BestAgentError("ACTION_EXPIRED", "ask-user timed out before the user answered.");
        await persistTerminalToolFailure(toolCallId, prepared.normalizedInput, {
            ...preparedToolResumeContext,
            toolCallId,
        }, error);
        await runtime.runCheckpoints.completeRunCheckpoint(turn.id);
        throw error;
    }
    await runtime.runCheckpoints.leaveWaitPhase(turn.id, checkpointAction?.phaseName ?? preparedToolResumeContext.phaseName, "User action resolved.");
    await runtime.runCheckpoints.updateRunControlForTurn(turn.id, {
        status: "running",
        waitReason: "none",
    });
    const output = formatAskUserAnswers(resolution.answers);
    let finalOutput;
    try {
        const postHookResult = await runtime.hooks.applyPostToolUseHooks({
            elapsedMs: Math.max(0, Date.now() - actionStartedAt),
            profileName,
            result: output,
            threadId: turn.threadId,
            toolCallId,
            toolInput: prepared.normalizedInput,
            toolName,
        });
        finalOutput = postHookResult.output;
    }
    catch (error) {
        const failureOutput = await persistTerminalToolFailure(toolCallId, prepared.normalizedInput, {
            ...preparedToolResumeContext,
            toolCallId,
        }, error);
        if (failureOutput !== undefined) {
            return failureOutput;
        }
        throw error;
    }
    await persistToolOutput({
        appendEvidence: false,
        output: finalOutput,
        resumeContext: {
            ...preparedToolResumeContext,
            toolCallId,
        },
        runtime,
        structuredContent: { answers: resolution.answers },
        toolCallId,
        toolInput: prepared.normalizedInput,
        toolName,
        turn,
    });
    return finalOutput;
}
//# sourceMappingURL=ask-user-tool-execution.js.map