import { executeAgent } from '../../../agents/agent-usecases.js';
import { buildSessionKey } from '../session-key.js';
import { buildAbortSignal } from './abort-signal.js';
import { createPartStep } from './team-leader-common.js';
import { buildGitRules } from '../instruction/instruction-context.js';
import { renderFallbackNotice } from '../instruction/fallback-notice.js';
import { getErrorMessage } from '../../../shared/utils/index.js';
import { classifyAbortSignalReason } from '../../../shared/types/agent-failure.js';
import { runWithPhaseSpan } from '../observability/workflowSpans.js';
function buildTeamLeaderPartInstruction(partStep, part, language, runtime) {
    const gitRules = buildGitRules(partStep.allowGitCommit, language, 'phase1');
    const fallbackNotice = runtime?.fallback
        ? renderFallbackNotice(runtime.fallback, language)
        : '';
    return [gitRules, fallbackNotice, part.instruction]
        .filter((item) => typeof item === 'string' && item.length > 0)
        .join('\n\n');
}
export async function runTeamLeaderPart(optionsBuilder, step, leaderWorkflowMeta, part, partIndex, defaultTimeoutMs, updatePersonaSession, parallelLogger, observability, runtime) {
    const partStep = createPartStep(step, part);
    const partProviderInfo = runtime
        ? optionsBuilder.resolveStepProviderModel(partStep, runtime)
        : optionsBuilder.resolveStepProviderModel(partStep);
    const baseOptions = optionsBuilder.buildAgentOptions(partStep, {
        ...runtime,
        providerInfo: partProviderInfo,
        teamLeaderPart: {
            partAllowedTools: step.teamLeader?.partAllowedTools,
            processSafety: leaderWorkflowMeta?.processSafety,
        },
    });
    const { signal, dispose } = buildAbortSignal(defaultTimeoutMs, baseOptions.abortSignal);
    const options = parallelLogger
        ? {
            ...baseOptions,
            abortSignal: signal,
            onStream: parallelLogger.createStreamHandler(part.id, partIndex),
        }
        : {
            ...baseOptions,
            abortSignal: signal,
        };
    try {
        const partInstruction = buildTeamLeaderPartInstruction(partStep, part, options.language ?? 'en', runtime);
        const response = await runWithPhaseSpan({
            enabled: observability.enabled,
            runId: observability.runId,
            workflowName: observability.workflowName,
            step: partStep,
            iteration: observability.iteration,
            phase: 1,
            phaseName: 'execute',
            instruction: partInstruction,
            workflowStack: observability.workflowStack,
            sanitizeText: observability.sanitizeText,
            providerInfo: partProviderInfo,
        }, () => executeAgent(partStep.persona, partInstruction, options), (result) => ({
            status: result.status,
            content: result.content,
            error: result.error,
        }));
        updatePersonaSession(buildSessionKey(partStep, partProviderInfo.provider), response.sessionId);
        return {
            part,
            providerInfo: partProviderInfo,
            response: {
                ...response,
                persona: partStep.name,
            },
        };
    }
    catch (error) {
        return buildTeamLeaderErrorPartResult(step, part, error, signal);
    }
    finally {
        dispose();
    }
}
export function buildTeamLeaderErrorPartResult(step, part, error, abortSignal) {
    const message = getErrorMessage(error);
    const failure = abortSignal?.aborted ? classifyAbortSignalReason(abortSignal.reason) : undefined;
    const errorMsg = failure ? failure.reason : message;
    const errorResponse = {
        persona: `${step.name}.${part.id}`,
        status: 'error',
        content: '',
        timestamp: new Date(),
        error: errorMsg,
        ...(failure ? { failureCategory: failure.category } : {}),
    };
    return { part, response: errorResponse };
}
//# sourceMappingURL=team-leader-part-runner.js.map