import { selectParticipantAgent } from "./participant.js";
function resolveStageParticipant(stage, participants) {
    if (!Object.hasOwn(participants, stage.participant)) {
        throw new Error(`Unknown participant: ${stage.participant}`);
    }
    return participants[stage.participant];
}
function resolveStageMode(stage, participant) {
    const mode = stage.mode ?? participant.mode;
    if (mode === undefined) {
        throw new Error(`Stage is missing mode for participant "${participant.id}".`);
    }
    return mode;
}
function resolveStagePrompt(stage, participant) {
    return stage.prompt ?? participant.prompt ?? "";
}
function toError(error) {
    return error instanceof Error ? error : new Error(String(error));
}
export async function runWorkflowStage(stage, context) {
    const participant = resolveStageParticipant(stage, context.participants);
    const mode = resolveStageMode(stage, participant);
    try {
        await context.runAgent({
            agent: selectParticipantAgent(participant, context.iteration),
            prompt: resolveStagePrompt(stage, participant),
            mode,
            cwd: context.cwd,
            ...(participant.model ? { model: participant.model } : {}),
            ...(stage.skills ? { skills: stage.skills } : {}),
            ...(stage.hooks ? { hooks: stage.hooks } : {}),
            ...(context.signal ? { signal: context.signal } : {})
        });
        return { success: true };
    }
    catch (error) {
        const stageError = toError(error);
        if (stage.onFailure === "continue") {
            return { success: false, error: stageError };
        }
        throw stageError;
    }
}
