import { runServerToolOrchestration } from '../../../../../../servertool/engine.js';
import { detectProviderResponseShapeWithNative } from '../../../../../../router/virtual-router/engine-selection/native-chat-process-servertool-orchestration-semantics.js';
import { recordStage } from '../../../stages/utils.js';
export async function runRespProcessStage3ServerToolOrchestration(options) {
    const hasServerToolSupport = Boolean(options.providerInvoker) || Boolean(options.reenterPipeline) || Boolean(options.clientInjectDispatch);
    const inputShape = detectProviderResponseShapeWithNative(options.payload);
    if (!hasServerToolSupport) {
        recordStage(options.stageRecorder, 'chat_process.resp.stage5.servertool_orchestration', {
            executed: false,
            skipReason: 'no_servertool_support',
            inputShape
        });
        return {
            payload: options.payload,
            executed: false,
            skipReason: 'no_servertool_support'
        };
    }
    const orchestration = await runServerToolOrchestration({
        chat: options.payload,
        adapterContext: options.adapterContext,
        requestId: options.requestId,
        entryEndpoint: options.entryEndpoint,
        providerProtocol: options.providerProtocol,
        stageRecorder: options.stageRecorder,
        providerInvoker: options.providerInvoker,
        reenterPipeline: options.reenterPipeline,
        clientInjectDispatch: options.clientInjectDispatch
    });
    if (orchestration.executed) {
        const outputPayload = orchestration.chat;
        const outputShape = detectProviderResponseShapeWithNative(outputPayload);
        recordStage(options.stageRecorder, 'chat_process.resp.stage5.servertool_orchestration', {
            executed: true,
            flowId: orchestration.flowId,
            inputShape,
            outputShape
        });
        return {
            payload: outputPayload,
            executed: true,
            flowId: orchestration.flowId
        };
    }
    recordStage(options.stageRecorder, 'chat_process.resp.stage5.servertool_orchestration', {
        executed: false,
        inputShape
    });
    return {
        payload: options.payload,
        executed: false
    };
}
