| 169 | * ``` |
| 170 | */ |
| 171 | export function toHttpStream( |
| 172 | stream: AsyncIterable<StreamChunk>, |
| 173 | abortController?: AbortController, |
| 174 | ): ReadableStream<Uint8Array> { |
| 175 | const encoder = new TextEncoder() |
| 176 | |
| 177 | return new ReadableStream({ |
| 178 | async start(controller) { |
| 179 | try { |
| 180 | for await (const chunk of stream) { |
| 181 | // Check if stream was cancelled/aborted |
| 182 | if (abortController?.signal.aborted) { |
| 183 | break |
| 184 | } |
| 185 | |
| 186 | // Send each chunk as newline-delimited JSON |
| 187 | controller.enqueue(encoder.encode(`${JSON.stringify(chunk)}\n`)) |
| 188 | } |
| 189 | |
| 190 | controller.close() |
| 191 | } catch (error: unknown) { |
| 192 | // Don't send error if aborted |
| 193 | if (abortController?.signal.aborted) { |
| 194 | controller.close() |
| 195 | return |
| 196 | } |
| 197 | |
| 198 | // Send error event (AG-UI RUN_ERROR) |
| 199 | controller.enqueue( |
| 200 | encoder.encode( |
| 201 | `${JSON.stringify({ |
| 202 | type: 'RUN_ERROR', |
| 203 | timestamp: Date.now(), |
| 204 | error: toRunErrorPayload(error), |
| 205 | })}\n`, |
| 206 | ), |
| 207 | ) |
| 208 | controller.close() |
| 209 | } |
| 210 | }, |
| 211 | cancel() { |
| 212 | // When the ReadableStream is cancelled (e.g., client disconnects), |
| 213 | // abort the underlying stream |
| 214 | if (abortController) { |
| 215 | abortController.abort() |
| 216 | } |
| 217 | }, |
| 218 | }) |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * Convert a StreamChunk async iterable to a Response in HTTP stream format (newline-delimited JSON) |