import { runAgent } from './runner.js';
import { parseParts } from '../core/workflow/engine/task-decomposer.js';
import { loadDecompositionSchema, loadMorePartsSchema } from '../infra/resources/schema-loader.js';
import { buildMaxTurnsOption } from './provider-call-options.js';
import { buildDecomposePrompt, buildMorePartsPrompt, toMorePartsResponse, toPartDefinitions, } from './team-leader-structured-output.js';
export const TEAM_LEADER_MAX_TURNS = 5;
export async function decomposeTask(instruction, maxParts, options) {
    const response = await runAgent(options.persona, buildDecomposePrompt(instruction, maxParts, options.language), {
        cwd: options.cwd,
        personaPath: options.personaPath,
        language: options.language,
        model: options.model,
        provider: options.provider,
        resolvedModel: options.resolvedModel,
        resolvedProvider: options.resolvedProvider,
        allowedTools: [],
        permissionMode: 'readonly',
        ...buildMaxTurnsOption(options.provider, options.resolvedProvider, TEAM_LEADER_MAX_TURNS),
        outputSchema: loadDecompositionSchema(maxParts),
        onStream: options.onStream,
        workflowMeta: options.workflowMeta,
        onPromptResolved: options.onPromptResolved,
    });
    if (response.status !== 'done') {
        const detail = response.error || response.content || response.status;
        throw new Error(`Team leader failed: ${detail}`);
    }
    const parts = response.structuredOutput?.parts;
    if (parts != null) {
        return toPartDefinitions(parts, maxParts);
    }
    return parseParts(response.content, maxParts);
}
export async function requestMoreParts(originalInstruction, allResults, existingIds, maxAdditionalParts, options) {
    const prompt = buildMorePartsPrompt(originalInstruction, allResults, existingIds, maxAdditionalParts, options.language);
    const response = await runAgent(options.persona, prompt, {
        cwd: options.cwd,
        personaPath: options.personaPath,
        language: options.language,
        model: options.model,
        provider: options.provider,
        resolvedModel: options.resolvedModel,
        resolvedProvider: options.resolvedProvider,
        allowedTools: [],
        permissionMode: 'readonly',
        ...buildMaxTurnsOption(options.provider, options.resolvedProvider, TEAM_LEADER_MAX_TURNS),
        outputSchema: loadMorePartsSchema(maxAdditionalParts),
        onStream: options.onStream,
        workflowMeta: options.workflowMeta,
    });
    if (response.status !== 'done') {
        const detail = response.error || response.content || response.status;
        throw new Error(`Team leader feedback failed: ${detail}`);
    }
    return toMorePartsResponse(response.structuredOutput, maxAdditionalParts);
}
//# sourceMappingURL=decompose-task-usecase.js.map