/** Gateway proxy mode — pipes SSE from a remote gateway */ import type { Request, Response } from 'express'; export async function proxyToGateway( req: Request, res: Response, gatewayUrl: string, ): Promise { const apiKey = process.env.GATEWAY_API_KEY || ''; try { const upstream = await fetch(`${gatewayUrl}/llm/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey, }, body: JSON.stringify({ ...req.body, stream: true }), }); if (!upstream.ok) { const text = await upstream.text(); res.status(upstream.status).json({ error: text }); return; } res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); const reader = upstream.body?.getReader(); if (!reader) { res.write(`data: ${JSON.stringify({ error: 'No response body' })}\n\n`); res.end(); return; } const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; res.write(decoder.decode(value, { stream: true })); } res.end(); } catch (error) { res.write(`data: ${JSON.stringify({ error: String(error) })}\n\n`); res.end(); } }