Open History to see the last commit
1import { EventType } from '@tanstack/ai'
2import { buildConverseUsage } from './usage'
3import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
4import type { ConverseStreamOutput } from '@aws-sdk/client-bedrock-runtime'
5
6/**
7 * Converse delivers server-side failures — throttling, request validation,
8 * mid-stream model faults, and service-unavailable — as in-band stream events
9 * rather than thrown exceptions. If they were ignored the iterator would simply
10 * end and the run would look like a clean, truncated success. Throw the
11 * underlying exception (these SDK members extend `Error`) so the adapter's
12 * `chatStream` / `structuredOutputStream` catch converts it into a `RUN_ERROR`.
13 */
14export function throwIfConverseStreamError(ev: ConverseStreamOutput): void {
15 if ('internalServerException' in ev && ev.internalServerException) {
16 throw ev.internalServerException
17 }
18 if ('modelStreamErrorException' in ev && ev.modelStreamErrorException) {
19 throw ev.modelStreamErrorException
20 }
21 if ('validationException' in ev && ev.validationException) {
22 throw ev.validationException
23 }
24 if ('throttlingException' in ev && ev.throttlingException) {
25 throw ev.throttlingException
26 }
27 if ('serviceUnavailableException' in ev && ev.serviceUnavailableException) {
28 throw ev.serviceUnavailableException
29 }
30}
31
32/** Map Converse blocks to run, text, reasoning, and tool events.
33 * Keep signatures and encrypted bytes separate for each contentBlockIndex.
34 * Finish after trailing usage events. The adapter handles thrown errors.
35 */
36export async function* processConverseStream(
37 stream: AsyncIterable<ConverseStreamOutput>,
38 newMessageId: () => string,
39 lifecycle: { threadId: string; parentRunId?: string; model?: string },
40): AsyncIterable<AdapterYieldChunk> {
41 const runId = newMessageId()
42 const { threadId, parentRunId, model } = lifecycle
43 const messageId = newMessageId()
44
45 let hasEmittedRunStarted = false
46
47 // Text lifecycle
48 let accumulatedContent = ''
49 let hasEmittedTextMessageStart = false
50
51 // Reasoning lifecycle
52 const reasoningByIndex = new Map<
53 number,
54 {
55 id: string
56 signature: string
57 bytes: Array<Uint8Array>
58 redacted: boolean
59 closed: boolean
60 encrypted?: string
61 }
62 >()
63
64 // Tool-call lifecycle, keyed by Converse contentBlockIndex. Converse opens a
65 // tool-use block with `contentBlockStart`, streams arg fragments via
66 // `contentBlockDelta`, and closes it with `contentBlockStop`.
67 const toolCallsByIndex = new Map<
68 number,
69 {
70 id: string
71 name: string
72 started: boolean
73 arguments: string
74 }
75 >()
76
77 // Usage + finish-reason are captured during iteration and folded into the
78 // single terminal RUN_FINISHED, matching openai-base's deferred-finish
79 // contract (usage may arrive after the finish signal).
80 let usage: TokenUsage | undefined
81 let finishReason: NonNullable<AdapterYieldChunk['finishReason']> | undefined
82
83 // Lazily emit RUN_STARTED exactly once, before the first content event.
84 function* ensureRunStarted(): Generator<AdapterYieldChunk> {
85 if (hasEmittedRunStarted) return
86 hasEmittedRunStarted = true
87 yield {
88 type: EventType.RUN_STARTED,
89 runId,
90 threadId,
91 parentRunId,
92 ...(model && { model }),
93 timestamp: Date.now(),
94 }
95 }
96
97 // Close an open reasoning message before text/tool content begins, mirroring
98 // openai-base which always emits REASONING_MESSAGE_END before TEXT_MESSAGE_START.
99 function* encryptedReasoning(index: number): Generator<AdapterYieldChunk> {
100 const reasoning = reasoningByIndex.get(index)
101 if (!reasoning) return
102 const encrypted = reasoning.redacted
103 ? Buffer.concat(reasoning.bytes).toString('base64')
104 : reasoning.signature
105 if (!encrypted || encrypted === reasoning.encrypted) return
106 reasoning.encrypted = encrypted
107 yield {
108 type: EventType.REASONING_ENCRYPTED_VALUE,
109 entityId: reasoning.id,
110 subtype: 'message',
111 encryptedValue: encrypted,
112 timestamp: Date.now(),
113 }
114 }
115
116 function* closeReasoning(index?: number): Generator<AdapterYieldChunk> {
117 for (const [blockIndex, reasoning] of reasoningByIndex) {
118 if (index !== undefined && index !== blockIndex) continue
119 yield* encryptedReasoning(blockIndex)
120 if (reasoning.closed) continue
121 reasoning.closed = true
122 yield {
123 type: EventType.REASONING_MESSAGE_END,
124 messageId: reasoning.id,
125 timestamp: Date.now(),
126 }
127 yield {
128 type: EventType.REASONING_END,
129 messageId: reasoning.id,
130 timestamp: Date.now(),
131 }
132 }
133 }
134
135 for await (const ev of stream) {
136 yield* ensureRunStarted()
137
138 // Surface in-band server/throttle/validation errors instead of dropping them.
139 throwIfConverseStreamError(ev)
140
141 // messageStart carries only the role; no AG-UI event maps to it.
142 if ('messageStart' in ev) continue
143
144 if ('contentBlockStart' in ev) {
145 const start = ev.contentBlockStart
146 const toolUse = start?.start?.toolUse
147 if (start && toolUse) {
148 yield* closeReasoning()
149 const id = toolUse.toolUseId ?? newMessageId()
150 const name = toolUse.name ?? ''
151 const index = start.contentBlockIndex ?? 0
152 toolCallsByIndex.set(index, {
153 id,
154 name,
155 started: true,
156 arguments: '',
157 })
158 yield {
159 type: EventType.TOOL_CALL_START,
160 toolCallId: id,
161 toolCallName: name,
162 timestamp: Date.now(),
163 index,
164 }
165 }
166 continue
167 }
168
169 if ('contentBlockDelta' in ev) {
170 const block = ev.contentBlockDelta
171 const delta = block?.delta
172 const index = block?.contentBlockIndex ?? 0
173
174 // Tool-call argument fragments (partial JSON).
175 if (delta && 'toolUse' in delta && delta.toolUse?.input !== undefined) {
176 const toolCall = toolCallsByIndex.get(index)
177 if (toolCall?.started) {
178 toolCall.arguments += delta.toolUse.input
179 yield {
180 type: EventType.TOOL_CALL_ARGS,
181 toolCallId: toolCall.id,
182 timestamp: Date.now(),
183 delta: delta.toolUse.input,
184 }
185 }
186 continue
187 }
188
189 if (delta && 'reasoningContent' in delta && delta.reasoningContent) {
190 const fragment = delta.reasoningContent
191 let reasoning = reasoningByIndex.get(index)
192 if (!reasoning) {
193 const redacted =
194 'redactedContent' in fragment &&
195 (fragment.redactedContent?.length ?? 0) > 0
196 reasoning = {
197 id: (redacted ? 'redacted_thinking-' : '') + newMessageId(),
198 signature: '',
199 bytes: [],
200 redacted,
201 closed: false,
202 }
203 reasoningByIndex.set(index, reasoning)
204 yield {
205 type: EventType.REASONING_MESSAGE_START,
206 messageId: reasoning.id,
207 role: 'reasoning',
208 timestamp: Date.now(),
209 }
210 }
211 if (
212 !reasoning.redacted &&
213 'text' in fragment &&
214 fragment.text !== undefined
215 ) {
216 yield {
217 type: EventType.REASONING_MESSAGE_CONTENT,
218 messageId: reasoning.id,
219 delta: fragment.text,
220 timestamp: Date.now(),
221 }
222 }
223 if (
224 !reasoning.redacted &&
225 'signature' in fragment &&
226 fragment.signature !== undefined
227 )
228 reasoning.signature += fragment.signature
229 if (
230 'redactedContent' in fragment &&
231 fragment.redactedContent &&
232 fragment.redactedContent.length > 0
233 ) {
234 if (!reasoning.redacted) reasoning.encrypted = undefined
235 reasoning.redacted = true
236 reasoning.signature = ''
237 reasoning.bytes.push(fragment.redactedContent)
238 yield* encryptedReasoning(index)
239 }
240 continue
241 }
242
243 // Text content.
244 if (delta && 'text' in delta && delta.text !== undefined) {
245 yield* closeReasoning()
246 if (!hasEmittedTextMessageStart) {
247 hasEmittedTextMessageStart = true
248 yield {
249 type: EventType.TEXT_MESSAGE_START,
250 messageId,
251 role: 'assistant',
252 timestamp: Date.now(),
253 }
254 }
255 accumulatedContent += delta.text
256 yield {
257 type: EventType.TEXT_MESSAGE_CONTENT,
258 messageId,
259 delta: delta.text,
260 content: accumulatedContent,
261 timestamp: Date.now(),
262 }
263 }
264 continue
265 }
266
267 if ('contentBlockStop' in ev) {
268 const stopIndex = ev.contentBlockStop?.contentBlockIndex ?? 0
269 yield* closeReasoning(stopIndex)
270 const toolCall = toolCallsByIndex.get(stopIndex)
271 if (toolCall?.started) {
272 yield {
273 type: EventType.TOOL_CALL_END,
274 toolCallId: toolCall.id,
275 args: toolCall.arguments,
276 toolCallName: toolCall.name,
277 timestamp: Date.now(),
278 }
279 toolCallsByIndex.delete(stopIndex)
280 }
281 continue
282 }
283
284 if ('messageStop' in ev) {
285 const stopReason = ev.messageStop?.stopReason
286 // Map Converse stopReason to AG-UI's narrower finishReason vocabulary.
287 finishReason =
288 stopReason === 'tool_use'
289 ? 'tool_calls'
290 : stopReason === 'max_tokens'
291 ? 'length'
292 : stopReason === 'content_filtered'
293 ? 'content_filter'
294 : 'stop'
295 continue
296 }
297
298 if ('metadata' in ev) {
299 const u = ev.metadata?.usage
300 if (u) {
301 usage = buildConverseUsage(u)
302 }
303 continue
304 }
305 }
306
307 // Stream ended (possibly without any content) — still emit RUN_STARTED so
308 // consumers always see a run lifecycle.
309 yield* ensureRunStarted()
310
311 // Drain any tool call that opened but never received contentBlockStop.
312 for (const [index, toolCall] of toolCallsByIndex) {
313 if (!toolCall.started) continue
314 yield {
315 type: EventType.TOOL_CALL_END,
316 toolCallId: toolCall.id,
317 args: toolCall.arguments,
318 toolCallName: toolCall.name,
319 timestamp: Date.now(),
320 }
321 toolCallsByIndex.delete(index)
322 }
323
324 // Close the text message lifecycle if it was opened.
325 if (hasEmittedTextMessageStart) {
326 yield {
327 type: EventType.TEXT_MESSAGE_END,
328 messageId,
329 timestamp: Date.now(),
330 }
331 }
332
333 // Close any reasoning lifecycle that text never closed.
334 yield* closeReasoning()
335
336 // Single terminal RUN_FINISHED. Conditional `usage` spread keeps the wire
337 // shape spec-compliant (AG-UI's `usage` is optional with no `| undefined`).
338 yield {
339 type: EventType.RUN_FINISHED,
340 runId,
341 threadId,
342 timestamp: Date.now(),
343 finishReason: finishReason ?? 'stop',
344 ...(usage && { usage }),
345 }
346}