/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
import { BaseConnector } from '../../../services/connectors/base/BaseConnector.js';
import { consumeSSEStream } from '../../../services/agent/sseStream.js';
import { buildAgentPayload } from '../../../services/agent/payloadBuilder.js';
import { AGUIToTrajectoryConverter, computeTrajectoryFromRawEvents } from '../../../services/agent/aguiConverter.js';
/**
 * AG-UI Streaming Connector
 * Uses Server-Sent Events (SSE) to stream agent responses in AG-UI format
 */
export class AGUIStreamingConnector extends BaseConnector {
    constructor() {
        super(...arguments);
        this.type = 'agui-streaming';
        this.name = 'AG-UI Streaming';
        this.traceContext = { propagateHeader: true };
        this.supportsStreaming = true;
    }
    /**
     * Build AG-UI payload from standard request
     */
    buildPayload(request) {
        return buildAgentPayload(request.testCase, request.modelId, request.threadId, request.runId);
    }
    /**
     * Execute the request using SSE streaming
     */
    async execute(endpoint, request, auth, onProgress, onRawEvent) {
        // Use pre-built payload from hook if available, otherwise build fresh
        const hasPrebuiltPayload = !!request.payload;
        const payload = request.payload || this.buildPayload(request);
        const headers = this.buildAuthHeaders(auth);
        this.injectTraceparentHeaders(headers);
        const trajectory = [];
        const rawEvents = [];
        const converter = new AGUIToTrajectoryConverter();
        this.debug('Executing AG-UI streaming request');
        await consumeSSEStream(endpoint, payload, (event) => {
            // Capture raw event for debugging
            rawEvents.push(event);
            onRawEvent?.(event);
            // Convert to trajectory steps
            const steps = converter.processEvent(event);
            steps.forEach(step => {
                trajectory.push(step);
                onProgress?.(step);
            });
        }, headers);
        const runId = converter.getRunId();
        this.debug('Stream completed. RunId:', runId, 'Steps:', trajectory.length);
        return {
            trajectory,
            runId,
            rawEvents,
            metadata: {
                threadId: converter.getThreadId(),
            },
        };
    }
    /**
     * Parse raw AG-UI events into trajectory steps
     * Used for re-processing stored raw events
     */
    parseResponse(rawEvents) {
        return computeTrajectoryFromRawEvents(rawEvents);
    }
    /**
     * Health check for AG-UI endpoint
     * Tries to connect without sending a full request
     */
    async healthCheck(endpoint, auth) {
        try {
            const headers = this.buildAuthHeaders(auth);
            // For AG-UI endpoints, we can't really do a health check without
            // making a full request, so just check if the endpoint is reachable
            const response = await fetch(endpoint, {
                method: 'OPTIONS',
                headers,
            });
            // Accept any response that isn't a network error
            return true;
        }
        catch (error) {
            this.error('Health check failed:', error);
            return false;
        }
    }
}
/**
 * Default instance for convenience
 */
export const aguiStreamingConnector = new AGUIStreamingConnector();
//# sourceMappingURL=AGUIStreamingConnector.js.map