import { classifyRuntimeFailure } from "../failure-classification.js";
import { repairReplayDecideDeliverables } from "./provider-replay-decide-deliverable-repair.js";
import { repairReplayDecideTerminalOutput } from "./provider-replay-decide-repair.js";
import { repairReplayGenerateDeliverables } from "./provider-replay-generate-deliverable-repair.js";
import { repairReplayGenerateTerminalOutput } from "./provider-replay-generate-repair.js";
import { buildReplayTerminalRepairState, } from "./provider-replay-terminal-repair-state.js";
export async function repairReplayedTerminalProviderResponse(input) {
    const { runtime } = input;
    let { responseText } = input;
    const state = buildReplayTerminalRepairState(input);
    let terminalOutputRepaired = false;
    try {
        responseText = runtime.assertValidTerminalAssistantText(responseText);
    }
    catch (error) {
        const failure = classifyRuntimeFailure(error);
        if (failure.errorCode !== "TERMINAL_OUTPUT_INVALID") {
            throw error;
        }
        responseText = await repairReplayTerminalOutputInvalid({
            error,
            responseText,
            state,
        });
        terminalOutputRepaired = true;
    }
    if (input.payload.requestKind === "generate" &&
        input.payload.request &&
        !terminalOutputRepaired) {
        const request = input.payload.request;
        responseText = await runtime.finalizeGeneratedResponse({
            availableTools: state.replayContextAvailableTools ?? [],
            messages: request.messages,
            objective: input.payload.replayContext?.objective,
            text: responseText,
        });
    }
    const generateRepair = await repairReplayGenerateDeliverables({ responseText, state });
    if (generateRepair !== undefined) {
        return generateRepair;
    }
    const decideRepair = await repairReplayDecideDeliverables({ responseText, state });
    return decideRepair ?? responseText;
}
async function repairReplayTerminalOutputInvalid(input) {
    const { payload } = input.state;
    if (!payload.request || !payload.requestKind) {
        throw input.error;
    }
    return payload.requestKind === "generate"
        ? repairReplayGenerateTerminalOutput(input)
        : repairReplayDecideTerminalOutput(input);
}
//# sourceMappingURL=provider-replay-terminal-repair.js.map