@@ -49,40 +49,46 @@ impl std::fmt::Debug for InFlight {
4949}
5050
5151impl InFlight {
52- fn finalize ( self , output : & mut Vec < OutputItem > ) {
52+ fn finalize ( self ) -> OutputItem {
5353 match self {
5454 Self :: Reasoning { mut item, text } => {
5555 if !text. is_empty ( ) {
5656 item. content . push ( ReasoningTextContent :: new ( text) ) ;
5757 }
58- output . push ( OutputItem :: Reasoning ( item) ) ;
58+ OutputItem :: Reasoning ( item)
5959 }
6060 Self :: FunctionCall { mut item, arguments } => {
6161 if !arguments. is_empty ( ) && item. arguments . is_empty ( ) {
6262 item. arguments = arguments;
6363 }
6464 item. status = MessageStatus :: Completed ;
65- output . push ( OutputItem :: FunctionCall ( item) ) ;
65+ OutputItem :: FunctionCall ( item)
6666 }
6767 Self :: Message { mut item, text } => {
6868 if !text. is_empty ( ) {
6969 item. content . push ( OutputTextContent :: new ( text) ) ;
7070 }
7171 item. status = MessageStatus :: Completed ;
72- output . push ( OutputItem :: Message ( item) ) ;
72+ OutputItem :: Message ( item)
7373 }
7474 Self :: CustomToolCall { mut item, input } => {
7575 if item. input . is_empty ( ) {
7676 item. input = input;
7777 }
7878 item. status = Some ( MessageStatus :: Completed ) ;
79- output . push ( OutputItem :: CustomToolCall ( item) ) ;
79+ OutputItem :: CustomToolCall ( item)
8080 }
81- Self :: McpCall { item } => output . push ( OutputItem :: McpCall ( item) ) ,
81+ Self :: McpCall { item } => OutputItem :: McpCall ( item) ,
8282 }
8383 }
8484}
8585
86+ #[ derive( Debug ) ]
87+ struct InFlightEntry {
88+ output_index : u32 ,
89+ item : InFlight ,
90+ }
91+
8692/// Accumulates LLM response chunks from streaming or non-streaming sources.
8793#[ derive( Debug ) ]
8894pub struct ResponseAccumulator {
@@ -94,7 +100,9 @@ pub struct ResponseAccumulator {
94100 incomplete_details : Option < IncompleteDetails > ,
95101 error : Option < serde_json:: Value > ,
96102 /// In-flight output items keyed by `item_id`, in insertion order.
97- in_flight : IndexMap < String , InFlight > ,
103+ in_flight : IndexMap < String , InFlightEntry > ,
104+ /// Completed streaming items waiting to be emitted in `output_index` order.
105+ completed : Vec < ( u32 , OutputItem ) > ,
98106}
99107
100108impl ResponseAccumulator {
@@ -110,6 +118,7 @@ impl ResponseAccumulator {
110118 incomplete_details : None ,
111119 error : None ,
112120 in_flight : IndexMap :: new ( ) ,
121+ completed : Vec :: new ( ) ,
113122 }
114123 }
115124
@@ -150,6 +159,7 @@ impl ResponseAccumulator {
150159 incomplete_details,
151160 error,
152161 in_flight : IndexMap :: new ( ) ,
162+ completed : Vec :: new ( ) ,
153163 } )
154164 }
155165
@@ -219,11 +229,16 @@ impl ResponseAccumulator {
219229 acc
220230 }
221231
222- /// Finalizes all in-flight items in insertion order, pushing them to `output` .
232+ /// Finalizes all streaming items in upstream `output_index` order .
223233 pub ( crate ) fn finalize_all ( & mut self ) {
224- for ( _, entry) in self . in_flight . drain ( ..) {
225- entry. finalize ( & mut self . output ) ;
226- }
234+ self . completed . extend (
235+ self . in_flight
236+ . drain ( ..)
237+ . map ( |( _, entry) | ( entry. output_index , entry. item . finalize ( ) ) ) ,
238+ ) ;
239+ self . completed . sort_by_key ( |( output_index, _) | * output_index) ;
240+ self . output
241+ . extend ( self . completed . drain ( ..) . map ( |( _, output_item) | output_item) ) ;
227242 }
228243
229244 pub ( crate ) fn process_sse_line ( & mut self , line : & str ) -> Option < EventFrame > {
@@ -271,83 +286,68 @@ impl ResponseAccumulator {
271286 ( SSEEventType :: ResponseCreated , EventPayload :: Response { id, .. } ) if !id. is_empty ( ) => {
272287 self . response_id . clone_from ( id) ;
273288 }
274- ( SSEEventType :: OutputItemAdded , payload @ EventPayload :: OutputItemAdded { item_id, item_type, .. } ) => {
275- let entry = match item_type {
276- SSEItemType :: Reasoning => ReasoningOutput :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: Reasoning {
277- item,
278- text : String :: with_capacity ( 256 ) ,
279- } ) ,
280- SSEItemType :: FunctionCall => {
281- FunctionToolCall :: try_from ( payload)
282- . ok ( )
283- . map ( |item| InFlight :: FunctionCall {
284- item,
285- arguments : String :: with_capacity ( 128 ) ,
286- } )
287- }
288- SSEItemType :: CustomToolCall => {
289- CustomToolCall :: try_from ( payload)
290- . ok ( )
291- . map ( |item| InFlight :: CustomToolCall {
292- item,
293- input : String :: with_capacity ( 256 ) ,
294- } )
295- }
296- SSEItemType :: Message => OutputMessage :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: Message {
297- item,
298- text : String :: with_capacity ( 256 ) ,
299- } ) ,
300- SSEItemType :: WebSearchCall => None ,
301- SSEItemType :: McpCall => McpCall :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: McpCall { item } ) ,
302- } ;
303- if let Some ( inflight) = entry {
304- self . in_flight . insert ( item_id. clone ( ) , inflight) ;
305- }
289+ ( SSEEventType :: OutputItemAdded , payload @ EventPayload :: OutputItemAdded { .. } ) => {
290+ self . start_output_item ( payload) ;
306291 }
307292 (
308293 SSEEventType :: OutputItemDone ,
309294 EventPayload :: OutputItemDone {
310295 item_id,
311296 item_type : SSEItemType :: CustomToolCall ,
297+ output_index,
312298 item,
313299 ..
314300 } ,
315- ) => self . complete_custom_tool_call ( item_id, item) ,
301+ ) => self . complete_custom_tool_call ( item_id, * output_index , item) ,
316302 ( SSEEventType :: OutputItemDone , payload @ EventPayload :: OutputItemDone { .. } ) => {
317303 self . complete_call_item ( payload) ;
318304 }
319305 ( SSEEventType :: ReasoningTextDelta , EventPayload :: ReasoningDelta { delta, item_id } ) => {
320- if let Some ( InFlight :: Reasoning { text, .. } ) = self . in_flight . get_mut ( item_id) {
306+ if let Some ( InFlight :: Reasoning { text, .. } ) =
307+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
308+ {
321309 text. push_str ( delta) ;
322310 }
323311 }
324312 ( SSEEventType :: ReasoningTextDone , EventPayload :: ReasoningDone { item_id, .. } ) => {
325- if let Some ( InFlight :: Reasoning { item, text } ) = self . in_flight . get_mut ( item_id) {
313+ if let Some ( InFlight :: Reasoning { item, text } ) =
314+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
315+ {
326316 item. apply_done ( & frame. payload , text) ;
327317 }
328318 }
329319 ( SSEEventType :: FunctionCallArgumentsDelta , EventPayload :: FunctionCallArgsDelta { delta, item_id, .. } ) => {
330- if let Some ( InFlight :: FunctionCall { arguments, .. } ) = self . in_flight . get_mut ( item_id) {
320+ if let Some ( InFlight :: FunctionCall { arguments, .. } ) =
321+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
322+ {
331323 arguments. push_str ( delta) ;
332324 }
333325 }
334326 ( SSEEventType :: FunctionCallArgumentsDone , EventPayload :: FunctionCallArgsDone { item_id, .. } ) => {
335- if let Some ( InFlight :: FunctionCall { item, arguments } ) = self . in_flight . get_mut ( item_id) {
327+ if let Some ( InFlight :: FunctionCall { item, arguments } ) =
328+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
329+ {
336330 item. apply_done ( & frame. payload , arguments) ;
337331 }
338332 }
339333 ( SSEEventType :: CustomToolCallInputDelta , EventPayload :: CustomToolCallInputDelta { delta, item_id, .. } ) => {
340- if let Some ( InFlight :: CustomToolCall { input, .. } ) = self . in_flight . get_mut ( item_id) {
334+ if let Some ( InFlight :: CustomToolCall { input, .. } ) =
335+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
336+ {
341337 input. push_str ( delta) ;
342338 }
343339 }
344340 ( SSEEventType :: CustomToolCallInputDone , EventPayload :: CustomToolCallInputDone { item_id, .. } ) => {
345- if let Some ( InFlight :: CustomToolCall { item, input } ) = self . in_flight . get_mut ( item_id) {
341+ if let Some ( InFlight :: CustomToolCall { item, input } ) =
342+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
343+ {
346344 item. apply_done ( & frame. payload , input) ;
347345 }
348346 }
349347 ( SSEEventType :: OutputTextDelta , EventPayload :: TextDelta { delta, item_id, .. } ) => {
350- if let Some ( InFlight :: Message { text, .. } ) = self . in_flight . get_mut ( item_id) {
348+ if let Some ( InFlight :: Message { text, .. } ) =
349+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
350+ {
351351 text. push_str ( delta) ;
352352 }
353353 }
@@ -364,19 +364,68 @@ impl ResponseAccumulator {
364364 }
365365 }
366366
367+ fn start_output_item ( & mut self , payload : & EventPayload ) {
368+ let EventPayload :: OutputItemAdded {
369+ item_id,
370+ item_type,
371+ output_index,
372+ ..
373+ } = payload
374+ else {
375+ return ;
376+ } ;
377+ let item = match item_type {
378+ SSEItemType :: Reasoning => ReasoningOutput :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: Reasoning {
379+ item,
380+ text : String :: with_capacity ( 256 ) ,
381+ } ) ,
382+ SSEItemType :: FunctionCall => FunctionToolCall :: try_from ( payload)
383+ . ok ( )
384+ . map ( |item| InFlight :: FunctionCall {
385+ item,
386+ arguments : String :: with_capacity ( 128 ) ,
387+ } ) ,
388+ SSEItemType :: CustomToolCall => {
389+ CustomToolCall :: try_from ( payload)
390+ . ok ( )
391+ . map ( |item| InFlight :: CustomToolCall {
392+ item,
393+ input : String :: with_capacity ( 256 ) ,
394+ } )
395+ }
396+ SSEItemType :: Message => OutputMessage :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: Message {
397+ item,
398+ text : String :: with_capacity ( 256 ) ,
399+ } ) ,
400+ SSEItemType :: WebSearchCall => None ,
401+ SSEItemType :: McpCall => McpCall :: try_from ( payload) . ok ( ) . map ( |item| InFlight :: McpCall { item } ) ,
402+ } ;
403+ if let Some ( item) = item {
404+ self . in_flight . insert (
405+ item_id. clone ( ) ,
406+ InFlightEntry {
407+ output_index : * output_index,
408+ item,
409+ } ,
410+ ) ;
411+ }
412+ }
413+
367414 fn finish_response ( & mut self , status : ResponseStatus , usage : Option < ResponseUsage > ) {
368415 self . finalize_all ( ) ;
369416 self . status = status;
370417 self . usage = usage;
371418 }
372419
373- fn complete_custom_tool_call ( & mut self , item_id : & str , raw_item : & serde_json:: Value ) {
420+ fn complete_custom_tool_call ( & mut self , item_id : & str , output_index : u32 , raw_item : & serde_json:: Value ) {
374421 let Some ( OutputItem :: CustomToolCall ( mut call) ) = deserialize_from_value_opt :: < OutputItem > ( raw_item. clone ( ) )
375422 else {
376423 return ;
377424 } ;
378425
379- if let Some ( InFlight :: CustomToolCall { item, input } ) = self . in_flight . get_mut ( item_id) {
426+ if let Some ( InFlight :: CustomToolCall { item, input } ) =
427+ self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry. item )
428+ {
380429 if call. input . is_empty ( ) {
381430 call. input = if item. input . is_empty ( ) {
382431 std:: mem:: take ( input)
@@ -389,30 +438,31 @@ impl ResponseAccumulator {
389438 * item = call;
390439 } else {
391440 // Some Responses-compatible providers omit `output_item.added`.
392- self . output . push ( OutputItem :: CustomToolCall ( call) ) ;
441+ self . completed . push ( ( output_index , OutputItem :: CustomToolCall ( call) ) ) ;
393442 }
394443 }
395444
396445 fn complete_call_item ( & mut self , payload : & EventPayload ) {
397446 let EventPayload :: OutputItemDone {
398447 item_id,
399448 item_type,
449+ output_index,
400450 item : raw_item,
401451 ..
402452 } = payload
403453 else {
404454 return ;
405455 } ;
406456 if * item_type == SSEItemType :: McpCall {
407- if let Some ( InFlight :: McpCall { item } ) = self . in_flight . get_mut ( item_id) {
457+ if let Some ( InFlight :: McpCall { item } ) = self . in_flight . get_mut ( item_id) . map ( |entry| & mut entry . item ) {
408458 item. apply_done ( payload, & mut String :: new ( ) ) ;
409459 return ;
410460 }
411461 }
412462 if let Some ( output_item @ ( OutputItem :: WebSearchCall ( _) | OutputItem :: McpCall ( _) ) ) =
413463 deserialize_from_value_opt :: < OutputItem > ( raw_item. clone ( ) )
414464 {
415- self . output . push ( output_item) ;
465+ self . completed . push ( ( * output_index , output_item) ) ;
416466 }
417467 }
418468
@@ -666,6 +716,22 @@ mod tests {
666716 assert ! ( matches!( acc. output[ 1 ] , OutputItem :: McpCall ( _) ) ) ;
667717 }
668718
719+ #[ test]
720+ fn test_accumulator_reasoning_before_done_only_mcp_call_preserves_order ( ) {
721+ let lines = vec ! [
722+ r#"data: {"type":"response.created","response":{"id":"resp_abc"}}"# . to_string( ) ,
723+ r#"data: {"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","summary":[]}}"# . to_string( ) ,
724+ r#"data: {"type":"response.reasoning_text.done","text":"thinking...","item_id":"rs_1"}"# . to_string( ) ,
725+ r#"data: {"type":"response.output_item.done","output_index":1,"item":{"type":"mcp_call","id":"mcp_1","server_label":"counter","name":"increment","arguments":"{}","status":"completed","approval_request_id":null,"output":"1","error":null}}"# . to_string( ) ,
726+ r#"data: {"type":"response.done","response":{"id":"resp_abc","status":"completed","usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}"# . to_string( ) ,
727+ ] ;
728+
729+ let acc = ResponseAccumulator :: from_sse_lines ( lines, None ) ;
730+ assert_eq ! ( acc. output. len( ) , 2 ) ;
731+ assert ! ( matches!( acc. output[ 0 ] , OutputItem :: Reasoning ( _) ) ) ;
732+ assert ! ( matches!( acc. output[ 1 ] , OutputItem :: McpCall ( _) ) ) ;
733+ }
734+
669735 #[ test]
670736 fn test_unknown_mcp_call_error_shape_is_not_dropped ( ) {
671737 let lines = vec ! [
0 commit comments