using System; using System.IO; using System.Text; using System.Threading; using xCommons.Extensions; using xHttpService.Constants; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace xAiModels.Helpers { public static class XAiMcpSseReader { /// /// Read an SSE Event ... /// /// /// /// public static async IAsyncEnumerable ReadAsync( Stream stream, [EnumeratorCancellation] CancellationToken cancellationToken = default ) { // using var reader = new StreamReader(stream, Encoding.UTF8); var dataBuffer = new StringBuilder(); while (!reader.EndOfStream) { // var line = await reader.ReadLineAsync(); if (line is null) { break; } // if (cancellationToken.IsCancellationRequested) { yield break; } // // Empty Line equals End of an Event ... if (line.IsNullOrEmpty()) { // if (dataBuffer.Length > 0) { // yield return dataBuffer.ToString(); dataBuffer.Clear(); } // continue; } // if (line.StartsWith(XSSEConstants.DataIdentifier, StringComparison.OrdinalIgnoreCase)) { // var data = line .Substring(XSSEConstants.DataIdentifier.Length) .TrimStart(); // if (dataBuffer.Length > 0) { dataBuffer.Append('\n'); } // dataBuffer.Append(data); } } // if (dataBuffer.Length > 0) { yield return dataBuffer.ToString(); } } } }