export interface RelayResponse { reqId: string; status: number; headers: Record; body: string; // base64 — legacy single-shot } export type AgentMsg = | { type: 'res_start'; reqId: string; status: number; headers: Record } | { type: 'res_data'; reqId: string; chunk: string } // base64 | { type: 'res_end'; reqId: string } | RelayResponse; // legacy: no type field export interface StreamHandler { onStart: ( status: number, headers: Record ) => void; onData: ( chunk: Buffer ) => void; onEnd: () => void; } const pending = new Map(); export function addPending( reqId: string, handler: StreamHandler ): void { pending.set( reqId, handler ); } export function removePending( reqId: string ): void { pending.delete( reqId ); } export function dispatchAgentMsg( msg: AgentMsg ): void { const handler = pending.get( msg.reqId ); if ( !handler ) return; if ( 'type' in msg ) { if ( msg.type === 'res_start' ) { handler.onStart( msg.status, msg.headers ); } else if ( msg.type === 'res_data' ) { handler.onData( Buffer.from( msg.chunk, 'base64' ) ); } else if ( msg.type === 'res_end' ) { pending.delete( msg.reqId ); handler.onEnd(); } } else { // Legacy single-shot RelayResponse — forward as stream handler.onStart( msg.status, msg.headers ); handler.onData( Buffer.from( msg.body, 'base64' ) ); pending.delete( msg.reqId ); handler.onEnd(); } }