1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Native `ConverseStream` transport for the shared Bedrock adapter (#4426).
//!
//! Why: [`InferenceAdapter::chat_stream`](crate::inference::InferenceAdapter::chat_stream)
//! had no Bedrock override, so every `bedrock/*` turn fell back to the trait's
//! buffered default — the whole answer arrived as ONE delta after the model had
//! already finished. Real token streaming for Bedrock is not new work in this
//! workspace: `crate::chat::bedrock_impl::BedrockProvider::chat_stream` has
//! driven `ConverseStream` in production (trusty-agents' chat path) since #3767.
//! This module ports that proven event handling onto the `inference` side, which
//! is the convergence target (`chat::ChatProvider` is being retired — epic
//! #4429). It deliberately does NOT reuse
//! [`crate::inference::streaming::SseDecoder`]: `ConverseStream` is a BINARY AWS
//! event-stream framed and demultiplexed by the SDK's `EventReceiver`, not the
//! `data:`-line SSE grammar that decoder speaks, and its token accounting
//! arrives exactly once in a terminal `Metadata` event rather than in a
//! usage-only final chunk.
//! What: [`ConverseStreamDecoder`] — the pure, synchronous
//! `ConverseStreamOutput` → [`ChatStreamEvent`] fold (text deltas, tool-use
//! start/argument fragments, the `MessageStop` stop reason, and the `Metadata`
//! usage tally); [`ConverseEventSource`] — a one-method seam over the SDK's
//! `EventReceiver` so [`drive`] (which produces the real [`ChatStream`] the
//! adapter returns) is unit-testable against a scripted event sequence, since
//! `EventReceiver` has no public constructor outside a live HTTP response; and
//! [`SdkEventSource`], the live implementation of that seam.
//! Test: `super::tests::stream_*` — delta ordering, structural-event skipping,
//! tool-call fragment mapping, terminal usage/stop-reason carry-over, the
//! mid-stream-error contract, and a `StreamAssembly` round-trip proving a
//! streamed turn rebuilds into the same `ChatResponse` the buffered `chat()`
//! path returns; plus the `#[ignore]`-gated `live_bedrock_converse_stream`.
use HashMap;
use async_trait;
use ConverseStreamOutput as ConverseStreamResponse;
use ;
use DisplayErrorContext;
use stream;
use crateInferenceError;
use crate;
use crate;
/// A pull source of decoded `ConverseStream` events.
///
/// Why (#4426): the AWS SDK hands the streamed turn back as an
/// `EventReceiver<ConverseStreamOutput, _>`, which has NO public constructor —
/// it can only be obtained from a live HTTP response. Testing [`drive`] (the
/// function that turns those events into the [`ChatStream`] the adapter
/// actually returns) therefore requires a seam; without one the only coverage
/// possible would be of the decoder in isolation, leaving the stream plumbing —
/// event ordering, terminal emission, error termination — unproven. One
/// `recv`-shaped method is enough because that is the entire surface [`drive`]
/// consumes.
/// What: `recv` yields the next event, `Ok(None)` at a clean end of stream, or
/// an [`InferenceError`] for a mid-stream failure (a modeled exception such as
/// throttling, or a transport fault). `Send + 'static` so the produced stream
/// satisfies [`ChatStream`]'s bounds.
/// Test: [`SdkEventSource`] is the live impl; `super::tests::ScriptedEvents` is
/// the test impl driving every `stream_*` test.
pub
/// The live [`ConverseEventSource`]: the AWS SDK's `ConverseStream` response.
///
/// Why: wraps the SDK response so the SDK error type is mapped to
/// [`InferenceError`] in ONE place, and so [`drive`] never names an AWS type.
/// It holds the whole operation OUTPUT rather than just its `stream` field
/// because the field's `EventReceiver<..>` type is not publicly nameable from
/// outside the SDK crate (`aws_sdk_bedrockruntime::event_receiver` is private) —
/// keeping the public wrapper is the only way to store it without a generic
/// escape hatch. The model/region are carried purely to make a mid-stream
/// failure message actionable (which model, which region) — the same context
/// [`super::BedrockAdapter::chat`] puts on its non-streaming errors.
/// What: `recv` delegates to the receiver's `recv`, mapping any `SdkError` to
/// [`InferenceError::Provider`] with the full source chain via
/// `DisplayErrorContext` (an `SdkError`'s own `Display` omits its cause, which
/// is where the real reason lives).
/// Test: exercised by the `#[ignore]`-gated `live_bedrock_converse_stream`; the
/// offline `stream_*` tests use the scripted source instead.
pub
/// Folds `ConverseStream` events into the neutral streaming event model.
///
/// Why: this is the part of the port with real branching logic, so it is a
/// plain synchronous struct rather than being inlined into the async stream —
/// it can then be driven by a scripted event list in a unit test, exactly as
/// `chat::bedrock_impl::handle_stream_event` is. Converse spreads the terminal
/// summary across TWO events (`MessageStop` carries the stop reason,
/// `Metadata` carries usage) and neither is the last thing the receiver yields,
/// so the decoder must accumulate both and emit the single terminal
/// [`ChatStreamEvent::Done`] only at end of stream — the neutral contract's
/// "exactly one `Done`, always last".
/// What: [`Self::push`] maps one event to at most one [`ChatStreamEvent`] while
/// recording stop reason / usage / tool-call slots; [`Self::finish`] builds the
/// terminal event. Tool calls are re-indexed into DENSE slots (0, 1, 2 …) keyed
/// by Converse's `contentBlockIndex`, because that index counts every content
/// block (a leading text block makes the first tool block index 1) while
/// [`ToolCallDelta::index`] is the OpenAI-dialect call ordinal every consumer —
/// [`crate::inference::StreamAssembly`] included — accumulates by.
/// Test: `super::tests::stream_*`.
pub
/// Drive a [`ConverseEventSource`] into the neutral [`ChatStream`].
///
/// Why: the adapter's `chat_stream` must return a pollable, `Send`, boxed
/// stream — not an ad-hoc loop — so the caller keeps back-pressure and
/// cancellation (dropping the returned stream drops the source, which aborts
/// the underlying AWS request). Generic over the source so the entire
/// production path is exercised offline by the scripted tests.
/// What: pulls events, forwards whatever [`ConverseStreamDecoder::push`]
/// produces, and terminates on either a clean end of stream (emitting exactly
/// one [`ChatStreamEvent::Done`]) or a mid-stream error (emitting a terminal
/// `Err` and NO `Done` — a failed stream must never be mistakable for a
/// complete short answer, the same contract
/// [`crate::inference::streaming::decode_event_stream`] holds for the SSE lane).
/// Test: `super::tests::stream_forwards_text_deltas_in_order`,
/// `super::tests::stream_surfaces_mid_stream_error`,
/// `super::tests::stream_assembles_into_buffered_shaped_response`.
pub