export async function proxyAgentRequest(agent, agentPath, request, reply, options = {}) {
    const targetUrl = `${agent.url}/api/agent${agentPath}`;
    const headers = {
        Authorization: `Bearer ${agent.token}`
    };
    const contentType = request.headers['content-type'];
    if (contentType) {
        headers['Content-Type'] = contentType;
    }
    let body = null;
    if (request.method !== 'GET' && request.method !== 'DELETE' && request.body !== undefined) {
        body = JSON.stringify(request.body);
        headers['Content-Type'] = 'application/json';
    }
    let response;
    try {
        response = await fetch(targetUrl, {
            method: request.method,
            headers,
            body,
            redirect: 'manual',
            signal: AbortSignal.timeout(options.timeoutMs ?? 30_000)
        });
    }
    catch {
        return reply.code(502).send({ error: 'agent_unreachable' });
    }
    const responseContentType = response.headers.get('content-type') ?? '';
    if (responseContentType.includes('application/octet-stream') || responseContentType.includes('image/') || responseContentType.includes('application/pdf')) {
        const buffer = await response.arrayBuffer();
        const lengthHeader = response.headers.get('content-length');
        if (lengthHeader)
            reply.header('Content-Length', lengthHeader);
        return reply.code(response.status).type(responseContentType).send(Buffer.from(buffer));
    }
    if (response.status === 204 || response.headers.get('content-length') === '0') {
        return reply.code(response.status).send();
    }
    if (!responseContentType.includes('application/json')) {
        return reply.code(502).send({ error: 'agent_unexpected_response' });
    }
    let json;
    try {
        json = await response.json();
    }
    catch {
        return reply.code(502).send({ error: 'agent_invalid_json' });
    }
    if (response.status === 404 &&
        options.unavailableFallback !== undefined &&
        hasUnavailableTranscriptError(json)) {
        return reply.code(200).send(options.unavailableFallback);
    }
    if (options.transformJson) {
        json = await options.transformJson(json, response.status);
    }
    return reply.code(options.mapStatus?.(response.status, json) ?? response.status).send(json);
}
function hasUnavailableTranscriptError(value) {
    if (!value || typeof value !== 'object' || !('error' in value)) {
        return false;
    }
    const error = value.error;
    return error === 'terminal_transcript_source_unavailable' || error === 'terminal_transcript_history_unavailable';
}
//# sourceMappingURL=agentProxy.js.map