import { BestAgentError } from "@best-agent/foundation";
import { appendRuntimeObservation } from "./runtime-observation.js";
import { validateProviderResponseFinalAnswer } from "./provider-final-answer-handler.js";
import { assertValidProviderProseResponse } from "./provider-response-validation.js";
export async function repairDurableGenerateFinalAnswer(input) {
    const finalValidation = validateProviderResponseFinalAnswer({
        availableTools: input.availableTools,
        messages: input.messages,
        objective: input.objective,
        text: input.responseText,
    });
    if (finalValidation.ok) {
        return {
            repaired: false,
            responseText: input.responseText,
        };
    }
    if (input.finalAnswerRepairAttempted) {
        throw new BestAgentError("PROVIDER_DECISION_INVALID", finalValidation.observation.message);
    }
    const repairMessages = appendRuntimeObservation(input.messages, finalValidation.observation);
    const correctionTrace = input.runtime.buildCorrectionTrace({
        code: "PROVIDER_DECISION_INVALID",
        messages: input.messages,
        operation: input.operation,
        systemPrompt: input.systemPrompt,
    });
    const repairResponse = await input.runtime.provider.generate(input.turn.threadId, input.turn.id, {
        cacheControl: input.cacheControl,
        messages: repairMessages,
        systemPrompt: input.systemPrompt,
    }, "repair", input.runtime.buildProviderInvokeContext({
        correctionTrace,
        requestBudgetSnapshot: input.requestBudgetSnapshot,
        supersedePendingProviderRequest: true,
    }));
    return {
        repairValidation: {
            message: finalValidation.observation.message,
            reasonCode: "final-answer-unsupported",
        },
        repaired: true,
        responseText: assertValidProviderProseResponse({
            assertValidTerminalAssistantText: input.runtime.assertValidTerminalAssistantText,
            availableTools: input.availableTools,
            messages: repairMessages,
            objective: input.objective,
            text: repairResponse.text,
        }),
    };
}
//# sourceMappingURL=provider-final-answer-repair-runner.js.map