11using Microsoft . AspNetCore . Http ;
22using System . Diagnostics ;
3- using System . IO . Pipelines ;
4- using System . Text ;
3+ using System . Net . ServerSentEvents ;
4+ using System . Text . Encodings . Web ;
55using System . Text . Json ;
66
77namespace A2A . AspNetCore ;
@@ -192,28 +192,15 @@ public async Task ExecuteAsync(HttpContext httpContext)
192192 httpContext . Response . ContentType = "text/event-stream" ;
193193 httpContext . Response . Headers . Append ( "Cache-Control" , "no-cache" ) ;
194194
195- await foreach ( var taskEvent in _events )
196- {
197- var sseItem = new A2ASseItem ( )
198- {
199- Data = JsonRpcResponse . CreateJsonRpcResponse ( requestId , taskEvent ) ,
200- } ;
201- await sseItem . WriteAsync ( httpContext . Response . BodyWriter ) ;
202- }
203- }
204- }
205-
206- public class A2ASseItem
207- {
208- public JsonRpcResponse ? Data { get ; set ; }
209-
210- public async Task WriteAsync ( PipeWriter writer )
211- {
212- if ( Data != null )
213- {
214- string json = JsonSerializer . Serialize ( Data , A2AJsonUtilities . DefaultOptions . GetTypeInfo ( typeof ( JsonRpcResponse ) ) ) ;
215- await writer . WriteAsync ( Encoding . UTF8 . GetBytes ( $ "data: { json } \n \n ") ) ;
216- await writer . FlushAsync ( ) ;
217- }
195+ var responseTypeInfo = A2AJsonUtilities . DefaultOptions . GetTypeInfo ( typeof ( JsonRpcResponse ) ) ;
196+ await SseFormatter . WriteAsync (
197+ _events . Select ( e => new SseItem < JsonRpcResponse > ( JsonRpcResponse . CreateJsonRpcResponse ( requestId , e ) ) ) ,
198+ httpContext . Response . Body ,
199+ ( item , writer ) =>
200+ {
201+ using Utf8JsonWriter json = new ( writer , new ( ) { Encoder = JavaScriptEncoder . UnsafeRelaxedJsonEscaping } ) ;
202+ JsonSerializer . Serialize ( json , item . Data , responseTypeInfo ) ;
203+ } ,
204+ httpContext . RequestAborted ) ;
218205 }
219206}
0 commit comments