openai_router.rs 175 KB
Newer Older
1
//! OpenAI router implementation
2
3
4

use crate::config::CircuitBreakerConfig;
use crate::core::{CircuitBreaker, CircuitBreakerConfig as CoreCircuitBreakerConfig};
5
use crate::data_connector::{
6
7
8
9
    Conversation, ConversationId, ConversationItemsListParams, ConversationItemsSortOrder,
    ConversationMetadata, NewConversationItem as DCNewConversationItem, ResponseId,
    SharedConversationItemStorage, SharedConversationStorage, SharedResponseStorage,
    StoredResponse,
10
};
11
use crate::protocols::spec::{
12
13
    ChatCompletionRequest, CompletionRequest, EmbeddingRequest, GenerateRequest, RerankRequest,
    ResponseContentPart, ResponseInput, ResponseInputOutputItem, ResponseOutputItem,
14
15
    ResponseStatus, ResponseTextFormat, ResponseTool, ResponseToolType, ResponsesGetParams,
    ResponsesRequest, ResponsesResponse, TextFormatType,
16
};
17
use crate::routers::header_utils::{apply_request_headers, preserve_response_headers};
18
19
20
21
22
23
use async_trait::async_trait;
use axum::{
    body::Body,
    extract::Request,
    http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
24
    Json,
25
};
26
use bytes::Bytes;
27
use futures_util::StreamExt;
28
use serde_json::{json, to_value, Value};
29
30
31
32
33
34
35
use std::{
    any::Any,
    borrow::Cow,
    collections::HashMap,
    io,
    sync::{atomic::AtomicBool, Arc},
};
36
37
38
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tracing::{error, info, warn};
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
// SSE Event Type Constants - single source of truth for event type strings
mod event_types {
    // Response lifecycle events
    pub const RESPONSE_CREATED: &str = "response.created";
    pub const RESPONSE_IN_PROGRESS: &str = "response.in_progress";
    pub const RESPONSE_COMPLETED: &str = "response.completed";

    // Output item events
    pub const OUTPUT_ITEM_ADDED: &str = "response.output_item.added";
    pub const OUTPUT_ITEM_DONE: &str = "response.output_item.done";
    pub const OUTPUT_ITEM_DELTA: &str = "response.output_item.delta";

    // Function call events
    pub const FUNCTION_CALL_ARGUMENTS_DELTA: &str = "response.function_call_arguments.delta";
    pub const FUNCTION_CALL_ARGUMENTS_DONE: &str = "response.function_call_arguments.done";

    // MCP call events
    pub const MCP_CALL_ARGUMENTS_DELTA: &str = "response.mcp_call_arguments.delta";
    pub const MCP_CALL_ARGUMENTS_DONE: &str = "response.mcp_call_arguments.done";
    pub const MCP_CALL_IN_PROGRESS: &str = "response.mcp_call.in_progress";
    pub const MCP_CALL_COMPLETED: &str = "response.mcp_call.completed";
    pub const MCP_LIST_TOOLS_IN_PROGRESS: &str = "response.mcp_list_tools.in_progress";
    pub const MCP_LIST_TOOLS_COMPLETED: &str = "response.mcp_list_tools.completed";

    // Item types
    pub const ITEM_TYPE_FUNCTION_CALL: &str = "function_call";
    pub const ITEM_TYPE_FUNCTION_TOOL_CALL: &str = "function_tool_call";
    pub const ITEM_TYPE_MCP_CALL: &str = "mcp_call";
    pub const ITEM_TYPE_FUNCTION: &str = "function";
    pub const ITEM_TYPE_MCP_LIST_TOOLS: &str = "mcp_list_tools";
}

72
73
74
75
76
77
78
79
80
81
/// Router for OpenAI backend
pub struct OpenAIRouter {
    /// HTTP client for upstream OpenAI-compatible API
    client: reqwest::Client,
    /// Base URL for identification (no trailing slash)
    base_url: String,
    /// Circuit breaker
    circuit_breaker: CircuitBreaker,
    /// Health status
    healthy: AtomicBool,
82
83
    /// Response storage for managing conversation history
    response_storage: SharedResponseStorage,
84
85
    /// Conversation storage backend
    conversation_storage: SharedConversationStorage,
86
87
    /// Conversation item storage backend
    conversation_item_storage: SharedConversationItemStorage,
88
89
    /// Optional MCP manager (enabled via config presence)
    mcp_manager: Option<Arc<crate::mcp::McpClientManager>>,
90
91
92
93
94
95
96
97
98
}

impl std::fmt::Debug for OpenAIRouter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenAIRouter")
            .field("base_url", &self.base_url)
            .field("healthy", &self.healthy)
            .finish()
    }
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
/// Configuration for MCP tool calling loops
#[derive(Debug, Clone)]
struct McpLoopConfig {
    /// Maximum iterations as safety limit (internal only, default: 10)
    /// Prevents infinite loops when max_tool_calls is not set
    max_iterations: usize,
}

impl Default for McpLoopConfig {
    fn default() -> Self {
        Self { max_iterations: 10 }
    }
}

/// State for tracking multi-turn tool calling loop
struct ToolLoopState {
    /// Current iteration number (starts at 0, increments with each tool call)
    iteration: usize,
    /// Total number of tool calls executed
    total_calls: usize,
    /// Conversation history (function_call and function_call_output items)
    conversation_history: Vec<Value>,
    /// Original user input (preserved for building resume payloads)
    original_input: ResponseInput,
}

impl ToolLoopState {
    fn new(original_input: ResponseInput) -> Self {
        Self {
            iteration: 0,
            total_calls: 0,
            conversation_history: Vec::new(),
            original_input,
        }
    }

    /// Record a tool call in the loop state
    fn record_call(
        &mut self,
        call_id: String,
        tool_name: String,
        args_json_str: String,
        output_str: String,
    ) {
        // Add function_call item to history
        let func_item = json!({
147
            "type": event_types::ITEM_TYPE_FUNCTION_CALL,
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
            "call_id": call_id,
            "name": tool_name,
            "arguments": args_json_str
        });
        self.conversation_history.push(func_item);

        // Add function_call_output item to history
        let output_item = json!({
            "type": "function_call_output",
            "call_id": call_id,
            "output": output_str
        });
        self.conversation_history.push(output_item);
    }
}

164
165
166
167
168
169
170
171
172
173
174
175
176
177
/// Helper that parses SSE frames from the OpenAI responses stream and
/// accumulates enough information to persist the final response locally.
struct StreamingResponseAccumulator {
    /// The initial `response.created` payload (if emitted).
    initial_response: Option<Value>,
    /// The final `response.completed` payload (if emitted).
    completed_response: Option<Value>,
    /// Collected output items keyed by the upstream output index, used when
    /// a final response payload is absent and we need to synthesize one.
    output_items: Vec<(usize, Value)>,
    /// Captured error payload (if the upstream stream fails midway).
    encountered_error: Option<Value>,
}

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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/// Represents a function call being accumulated across delta events
#[derive(Debug, Clone)]
struct FunctionCallInProgress {
    call_id: String,
    name: String,
    arguments_buffer: String,
    output_index: usize,
    last_obfuscation: Option<String>,
    assigned_output_index: Option<usize>,
}

impl FunctionCallInProgress {
    fn new(call_id: String, output_index: usize) -> Self {
        Self {
            call_id,
            name: String::new(),
            arguments_buffer: String::new(),
            output_index,
            last_obfuscation: None,
            assigned_output_index: None,
        }
    }

    fn is_complete(&self) -> bool {
        // A tool call is complete if it has a name
        !self.name.is_empty()
    }

    fn effective_output_index(&self) -> usize {
        self.assigned_output_index.unwrap_or(self.output_index)
    }
}

#[derive(Debug, Default)]
struct OutputIndexMapper {
    next_index: usize,
    // Map upstream output_index -> remapped output_index
    assigned: HashMap<usize, usize>,
}

impl OutputIndexMapper {
    fn with_start(next_index: usize) -> Self {
        Self {
            next_index,
            assigned: HashMap::new(),
        }
    }

    fn ensure_mapping(&mut self, upstream_index: usize) -> usize {
        *self.assigned.entry(upstream_index).or_insert_with(|| {
            let assigned = self.next_index;
            self.next_index += 1;
            assigned
        })
    }

    fn lookup(&self, upstream_index: usize) -> Option<usize> {
        self.assigned.get(&upstream_index).copied()
    }

    fn allocate_synthetic(&mut self) -> usize {
        let assigned = self.next_index;
        self.next_index += 1;
        assigned
    }

    fn next_index(&self) -> usize {
        self.next_index
    }
}

/// Action to take based on streaming event processing
#[derive(Debug)]
enum StreamAction {
    Forward,      // Pass event to client
    Buffer,       // Accumulate for tool execution
    ExecuteTools, // Function call complete, execute now
}

/// Handles streaming responses with MCP tool call interception
struct StreamingToolHandler {
    /// Accumulator for response persistence
    accumulator: StreamingResponseAccumulator,
    /// Function calls being built from deltas
    pending_calls: Vec<FunctionCallInProgress>,
    /// Track if we're currently in a function call
    in_function_call: bool,
    /// Manage output_index remapping so they increment per item
    output_index_mapper: OutputIndexMapper,
    /// Original response id captured from the first response.created event
    original_response_id: Option<String>,
}

impl StreamingToolHandler {
    fn with_starting_index(start: usize) -> Self {
        Self {
            accumulator: StreamingResponseAccumulator::new(),
            pending_calls: Vec::new(),
            in_function_call: false,
            output_index_mapper: OutputIndexMapper::with_start(start),
            original_response_id: None,
        }
    }

    fn ensure_output_index(&mut self, upstream_index: usize) -> usize {
        self.output_index_mapper.ensure_mapping(upstream_index)
    }

    fn mapped_output_index(&self, upstream_index: usize) -> Option<usize> {
        self.output_index_mapper.lookup(upstream_index)
    }

    fn allocate_synthetic_output_index(&mut self) -> usize {
        self.output_index_mapper.allocate_synthetic()
    }

    fn next_output_index(&self) -> usize {
        self.output_index_mapper.next_index()
    }

    fn original_response_id(&self) -> Option<&str> {
        self.original_response_id
            .as_deref()
            .or_else(|| self.accumulator.original_response_id())
    }

    fn snapshot_final_response(&self) -> Option<Value> {
        self.accumulator.snapshot_final_response()
    }

    /// Process an SSE event and determine what action to take
    fn process_event(&mut self, event_name: Option<&str>, data: &str) -> StreamAction {
        // Always feed to accumulator for storage
        self.accumulator.ingest_block(&format!(
            "{}data: {}",
            event_name
                .map(|n| format!("event: {}\n", n))
                .unwrap_or_default(),
            data
        ));

        let parsed: Value = match serde_json::from_str(data) {
            Ok(v) => v,
            Err(_) => return StreamAction::Forward,
        };

        let event_type = event_name
            .map(|s| s.to_string())
            .or_else(|| {
                parsed
                    .get("type")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
            })
            .unwrap_or_default();

        match event_type.as_str() {
            event_types::RESPONSE_CREATED => {
                if self.original_response_id.is_none() {
                    if let Some(response_obj) = parsed.get("response").and_then(|v| v.as_object()) {
                        if let Some(id) = response_obj.get("id").and_then(|v| v.as_str()) {
                            self.original_response_id = Some(id.to_string());
                        }
                    }
                }
                StreamAction::Forward
            }
            event_types::RESPONSE_COMPLETED => StreamAction::Forward,
            event_types::OUTPUT_ITEM_ADDED => {
                if let Some(idx) = parsed.get("output_index").and_then(|v| v.as_u64()) {
                    self.ensure_output_index(idx as usize);
                }

                // Check if this is a function_call item being added
                if let Some(item) = parsed.get("item") {
                    if let Some(item_type) = item.get("type").and_then(|v| v.as_str()) {
                        if item_type == event_types::ITEM_TYPE_FUNCTION_CALL
                            || item_type == event_types::ITEM_TYPE_FUNCTION_TOOL_CALL
                        {
                            match parsed.get("output_index").and_then(|v| v.as_u64()) {
                                Some(idx) => {
                                    let output_index = idx as usize;
                                    let assigned_index = self.ensure_output_index(output_index);
                                    let call_id =
                                        item.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
                                    let name =
                                        item.get("name").and_then(|v| v.as_str()).unwrap_or("");

                                    // Create or update the function call
                                    let call = self.get_or_create_call(output_index, item);
                                    call.call_id = call_id.to_string();
                                    call.name = name.to_string();
                                    call.assigned_output_index = Some(assigned_index);

                                    self.in_function_call = true;
                                }
                                None => {
                                    tracing::warn!(
                                        "Missing output_index in function_call added event, \
                                         forwarding without processing for tool execution"
                                    );
                                }
                            }
                        }
                    }
                }
                StreamAction::Forward
            }
            event_types::FUNCTION_CALL_ARGUMENTS_DELTA => {
                // Accumulate arguments for the function call
                if let Some(output_index) = parsed
                    .get("output_index")
                    .and_then(|v| v.as_u64())
                    .map(|v| v as usize)
                {
                    let assigned_index = self.ensure_output_index(output_index);
                    if let Some(delta) = parsed.get("delta").and_then(|v| v.as_str()) {
                        if let Some(call) = self
                            .pending_calls
                            .iter_mut()
                            .find(|c| c.output_index == output_index)
                        {
                            call.arguments_buffer.push_str(delta);
                            if let Some(obfuscation) =
                                parsed.get("obfuscation").and_then(|v| v.as_str())
                            {
                                call.last_obfuscation = Some(obfuscation.to_string());
                            }
                            if call.assigned_output_index.is_none() {
                                call.assigned_output_index = Some(assigned_index);
                            }
                        }
                    }
                }
                StreamAction::Forward
            }
            event_types::FUNCTION_CALL_ARGUMENTS_DONE => {
                // Function call arguments complete - check if ready to execute
                if let Some(output_index) = parsed
                    .get("output_index")
                    .and_then(|v| v.as_u64())
                    .map(|v| v as usize)
                {
                    let assigned_index = self.ensure_output_index(output_index);
                    if let Some(call) = self
                        .pending_calls
                        .iter_mut()
                        .find(|c| c.output_index == output_index)
                    {
                        if call.assigned_output_index.is_none() {
                            call.assigned_output_index = Some(assigned_index);
                        }
                    }
                }

                if self.has_complete_calls() {
                    StreamAction::ExecuteTools
                } else {
                    StreamAction::Forward
                }
            }
            event_types::OUTPUT_ITEM_DELTA => self.process_output_delta(&parsed),
            event_types::OUTPUT_ITEM_DONE => {
                // Check if we have complete function calls ready to execute
                if let Some(output_index) = parsed
                    .get("output_index")
                    .and_then(|v| v.as_u64())
                    .map(|v| v as usize)
                {
                    self.ensure_output_index(output_index);
                }

                if self.has_complete_calls() {
                    StreamAction::ExecuteTools
                } else {
                    StreamAction::Forward
                }
            }
            _ => StreamAction::Forward,
        }
    }

    /// Process output delta events to detect and accumulate function calls
    fn process_output_delta(&mut self, event: &Value) -> StreamAction {
        let output_index = event
            .get("output_index")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or(0);

        let assigned_index = self.ensure_output_index(output_index);

        let delta = match event.get("delta") {
            Some(d) => d,
            None => return StreamAction::Forward,
        };

        // Check if this is a function call delta
        let item_type = delta.get("type").and_then(|v| v.as_str());

        if item_type == Some(event_types::ITEM_TYPE_FUNCTION_TOOL_CALL)
            || item_type == Some(event_types::ITEM_TYPE_FUNCTION_CALL)
        {
            self.in_function_call = true;

            // Get or create function call for this output index
            let call = self.get_or_create_call(output_index, delta);
            call.assigned_output_index = Some(assigned_index);

            // Accumulate call_id if present
            if let Some(call_id) = delta.get("call_id").and_then(|v| v.as_str()) {
                call.call_id = call_id.to_string();
            }

            // Accumulate name if present
            if let Some(name) = delta.get("name").and_then(|v| v.as_str()) {
                call.name.push_str(name);
            }

            // Accumulate arguments if present
            if let Some(args) = delta.get("arguments").and_then(|v| v.as_str()) {
                call.arguments_buffer.push_str(args);
            }

            if let Some(obfuscation) = delta.get("obfuscation").and_then(|v| v.as_str()) {
                call.last_obfuscation = Some(obfuscation.to_string());
            }

            // Buffer this event, don't forward to client
            return StreamAction::Buffer;
        }

        // Forward non-function-call events
        StreamAction::Forward
    }

    fn get_or_create_call(
        &mut self,
        output_index: usize,
        delta: &Value,
    ) -> &mut FunctionCallInProgress {
        // Find existing call for this output index
        // Note: We use position() + index instead of iter_mut().find() because we need
        // to potentially mutate pending_calls after the early return, which causes
        // borrow checker issues with the iter_mut approach
        if let Some(pos) = self
            .pending_calls
            .iter()
            .position(|c| c.output_index == output_index)
        {
            return &mut self.pending_calls[pos];
        }

        // Create new call
        let call_id = delta
            .get("call_id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let mut call = FunctionCallInProgress::new(call_id, output_index);
        if let Some(obfuscation) = delta.get("obfuscation").and_then(|v| v.as_str()) {
            call.last_obfuscation = Some(obfuscation.to_string());
        }

        self.pending_calls.push(call);
        self.pending_calls
            .last_mut()
            .expect("Just pushed to pending_calls, must have at least one element")
    }

    fn has_complete_calls(&self) -> bool {
        !self.pending_calls.is_empty() && self.pending_calls.iter().all(|c| c.is_complete())
    }

    fn take_pending_calls(&mut self) -> Vec<FunctionCallInProgress> {
        std::mem::take(&mut self.pending_calls)
    }
}

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
impl StreamingResponseAccumulator {
    fn new() -> Self {
        Self {
            initial_response: None,
            completed_response: None,
            output_items: Vec::new(),
            encountered_error: None,
        }
    }

    /// Feed the accumulator with the next SSE chunk.
    fn ingest_block(&mut self, block: &str) {
        if block.trim().is_empty() {
            return;
        }
        self.process_block(block);
    }

    /// Consume the accumulator and produce the best-effort final response value.
    fn into_final_response(mut self) -> Option<Value> {
        if self.completed_response.is_some() {
            return self.completed_response;
        }

        self.build_fallback_response()
    }

    fn encountered_error(&self) -> Option<&Value> {
        self.encountered_error.as_ref()
    }
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

    fn original_response_id(&self) -> Option<&str> {
        self.initial_response
            .as_ref()
            .and_then(|response| response.get("id"))
            .and_then(|id| id.as_str())
    }

    fn snapshot_final_response(&self) -> Option<Value> {
        if let Some(resp) = &self.completed_response {
            return Some(resp.clone());
        }
        self.build_fallback_response_snapshot()
    }

    fn build_fallback_response_snapshot(&self) -> Option<Value> {
        let mut response = self.initial_response.clone()?;

        if let Some(obj) = response.as_object_mut() {
            obj.insert("status".to_string(), Value::String("completed".to_string()));

            let mut output_items = self.output_items.clone();
            output_items.sort_by_key(|(index, _)| *index);
            let outputs: Vec<Value> = output_items.into_iter().map(|(_, item)| item).collect();
            obj.insert("output".to_string(), Value::Array(outputs));
        }

        Some(response)
    }

618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
    fn process_block(&mut self, block: &str) {
        let trimmed = block.trim();
        if trimmed.is_empty() {
            return;
        }

        let mut event_name: Option<String> = None;
        let mut data_lines: Vec<String> = Vec::new();

        for line in trimmed.lines() {
            if let Some(rest) = line.strip_prefix("event:") {
                event_name = Some(rest.trim().to_string());
            } else if let Some(rest) = line.strip_prefix("data:") {
                data_lines.push(rest.trim_start().to_string());
            }
        }

        let data_payload = data_lines.join("\n");
        if data_payload.is_empty() {
            return;
        }

        self.handle_event(event_name.as_deref(), &data_payload);
    }

    fn handle_event(&mut self, event_name: Option<&str>, data_payload: &str) {
        let parsed: Value = match serde_json::from_str(data_payload) {
            Ok(value) => value,
            Err(err) => {
                warn!("Failed to parse streaming event JSON: {}", err);
                return;
            }
        };

        let event_type = event_name
            .map(|s| s.to_string())
            .or_else(|| {
                parsed
                    .get("type")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
            })
            .unwrap_or_default();

        match event_type.as_str() {
663
664
665
666
667
            event_types::RESPONSE_CREATED => {
                if self.initial_response.is_none() {
                    if let Some(response) = parsed.get("response") {
                        self.initial_response = Some(response.clone());
                    }
668
669
                }
            }
670
            event_types::RESPONSE_COMPLETED => {
671
672
673
674
                if let Some(response) = parsed.get("response") {
                    self.completed_response = Some(response.clone());
                }
            }
675
            event_types::OUTPUT_ITEM_DONE => {
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
                if let (Some(index), Some(item)) = (
                    parsed
                        .get("output_index")
                        .and_then(|v| v.as_u64())
                        .map(|v| v as usize),
                    parsed.get("item"),
                ) {
                    self.output_items.push((index, item.clone()));
                }
            }
            "response.error" => {
                self.encountered_error = Some(parsed);
            }
            _ => {}
        }
    }

    fn build_fallback_response(&mut self) -> Option<Value> {
        let mut response = self.initial_response.clone()?;

        if let Some(obj) = response.as_object_mut() {
            obj.insert("status".to_string(), Value::String("completed".to_string()));

            self.output_items.sort_by_key(|(index, _)| *index);
            let outputs: Vec<Value> = self
                .output_items
                .iter()
                .map(|(_, item)| item.clone())
                .collect();
            obj.insert("output".to_string(), Value::Array(outputs));
        }

        Some(response)
    }
}

712
impl OpenAIRouter {
713
714
    // Maximum number of conversation items to attach as input when a conversation is provided
    const MAX_CONVERSATION_HISTORY_ITEMS: usize = 100;
715
716
717
718
    /// Create a new OpenAI router
    pub async fn new(
        base_url: String,
        circuit_breaker_config: Option<CircuitBreakerConfig>,
719
        response_storage: SharedResponseStorage,
720
        conversation_storage: SharedConversationStorage,
721
        conversation_item_storage: SharedConversationItemStorage,
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
    ) -> Result<Self, String> {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(300))
            .build()
            .map_err(|e| format!("Failed to create HTTP client: {}", e))?;

        let base_url = base_url.trim_end_matches('/').to_string();

        // Convert circuit breaker config
        let core_cb_config = circuit_breaker_config
            .map(|cb| CoreCircuitBreakerConfig {
                failure_threshold: cb.failure_threshold,
                success_threshold: cb.success_threshold,
                timeout_duration: std::time::Duration::from_secs(cb.timeout_duration_secs),
                window_duration: std::time::Duration::from_secs(cb.window_duration_secs),
            })
            .unwrap_or_default();

        let circuit_breaker = CircuitBreaker::with_config(core_cb_config);

742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        // Optional MCP manager activation via env var path (config-driven gate)
        let mcp_manager = match std::env::var("SGLANG_MCP_CONFIG").ok() {
            Some(path) if !path.trim().is_empty() => {
                match crate::mcp::McpConfig::from_file(&path).await {
                    Ok(cfg) => match crate::mcp::McpClientManager::new(cfg).await {
                        Ok(mgr) => Some(Arc::new(mgr)),
                        Err(err) => {
                            warn!("Failed to initialize MCP manager: {}", err);
                            None
                        }
                    },
                    Err(err) => {
                        warn!("Failed to load MCP config from '{}': {}", path, err);
                        None
                    }
                }
            }
            _ => None,
        };

762
763
764
765
766
        Ok(Self {
            client,
            base_url,
            circuit_breaker,
            healthy: AtomicBool::new(true),
767
            response_storage,
768
            conversation_storage,
769
            conversation_item_storage,
770
            mcp_manager,
771
772
        })
    }
773
774
775
776
777

    async fn handle_non_streaming_response(
        &self,
        url: String,
        headers: Option<&HeaderMap>,
778
        mut payload: Value,
779
780
781
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<String>,
    ) -> Response {
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
        // Request-scoped MCP: build from request tools if provided; otherwise fall back to router-level MCP
        let req_mcp_manager = Self::mcp_manager_from_request_tools(&original_body.tools).await;
        let active_mcp = req_mcp_manager.as_ref().or(self.mcp_manager.as_ref());

        // If the client requested MCP but we couldn't initialize it, fail early with a clear error
        let requested_mcp = original_body
            .tools
            .iter()
            .any(|t| matches!(t.r#type, ResponseToolType::Mcp));
        if requested_mcp && active_mcp.is_none() {
            return (
                StatusCode::BAD_GATEWAY,
                json!({
                    "error": {
                        "message": "MCP server unavailable or failed to initialize from request tools",
                        "type": "mcp_unavailable",
                        "param": "tools",
                    }
                })
                .to_string(),
            )
                .into_response();
        }

        // If MCP is active, mirror one function tool into the outgoing payload
        if let Some(mcp) = active_mcp {
            if let Some(obj) = payload.as_object_mut() {
                // Remove any non-function tools (e.g., custom "mcp" items) from outgoing payload
                if let Some(v) = obj.get_mut("tools") {
                    if let Some(arr) = v.as_array_mut() {
                        arr.retain(|item| {
                            item.get("type")
                                .and_then(|v| v.as_str())
                                .map(|s| s == "function")
                                .unwrap_or(false)
                        });
                        if arr.is_empty() {
                            obj.remove("tools");
                            obj.insert(
                                "tool_choice".to_string(),
                                Value::String("none".to_string()),
                            );
                        }
                    }
                }
                // Build function tools for all discovered MCP tools
                let mut tools_json = Vec::new();
                let tools = mcp.list_tools();
                for t in tools {
                    let parameters = t.parameters.clone().unwrap_or(serde_json::json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    }));
                    let tool = serde_json::json!({
                        "type": "function",
                        "name": t.name,
                        "description": t.description,
                        "parameters": parameters
                    });
                    tools_json.push(tool);
                }
                if !tools_json.is_empty() {
                    obj.insert("tools".to_string(), Value::Array(tools_json));
                    // Ensure tool_choice auto to allow model planning
                    obj.insert("tool_choice".to_string(), Value::String("auto".to_string()));
                }
            }
        }
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        let request_builder = self.client.post(&url).json(&payload);

        // Apply headers with filtering
        let request_builder = if let Some(headers) = headers {
            apply_request_headers(headers, request_builder, true)
        } else {
            request_builder
        };

        match request_builder.send().await {
            Ok(response) => {
                let status = response.status();
                if !status.is_success() {
                    let error_text = response
                        .text()
                        .await
                        .unwrap_or_else(|e| format!("Failed to get error body: {}", e));
                    return (status, error_text).into_response();
                }

                // Parse the response
                match response.json::<Value>().await {
                    Ok(mut openai_response_json) => {
                        if let Some(prev_id) = original_previous_response_id {
                            if let Some(obj) = openai_response_json.as_object_mut() {
                                let should_insert = obj
                                    .get("previous_response_id")
                                    .map(|v| v.is_null())
                                    .unwrap_or(true);
                                if should_insert {
                                    obj.insert(
                                        "previous_response_id".to_string(),
                                        Value::String(prev_id),
                                    );
                                }
                            }
                        }

                        if let Some(obj) = openai_response_json.as_object_mut() {
                            if !obj.contains_key("instructions") {
                                if let Some(instructions) = &original_body.instructions {
                                    obj.insert(
                                        "instructions".to_string(),
                                        Value::String(instructions.clone()),
                                    );
                                }
                            }

                            if !obj.contains_key("metadata") {
                                if let Some(metadata) = &original_body.metadata {
                                    let metadata_map: serde_json::Map<String, Value> = metadata
                                        .iter()
                                        .map(|(k, v)| (k.clone(), v.clone()))
                                        .collect();
                                    obj.insert("metadata".to_string(), Value::Object(metadata_map));
                                }
                            }

                            // Reflect the client's requested store preference in the response body
                            obj.insert("store".to_string(), Value::Bool(original_body.store));
                        }

913
914
915
916
917
                        // If MCP is active and we detect a function call, enter the tool loop
                        let mut final_response_json = if let Some(mcp) = active_mcp {
                            if Self::extract_function_call(&openai_response_json).is_some() {
                                // Use the loop to handle potentially multiple tool calls
                                let loop_config = McpLoopConfig::default();
918
                                match self
919
920
                                    .execute_tool_loop(
                                        &url,
921
                                        headers,
922
                                        payload.clone(),
923
                                        original_body,
924
925
926
                                        mcp,
                                        &loop_config,
                                    )
927
928
                                    .await
                                {
929
                                    Ok(loop_result) => loop_result,
930
                                    Err(err) => {
931
                                        warn!("Tool loop failed: {}", err);
932
933
                                        let error_body = json!({
                                            "error": {
934
                                                "message": format!("Tool loop failed: {}", err),
935
936
937
938
939
940
941
942
943
944
945
946
947
                                                "type": "internal_error",
                                            }
                                        })
                                        .to_string();
                                        return (
                                            StatusCode::INTERNAL_SERVER_ERROR,
                                            [("content-type", "application/json")],
                                            error_body,
                                        )
                                            .into_response();
                                    }
                                }
                            } else {
948
949
                                // No function call detected, use response as-is
                                openai_response_json
950
                            }
951
952
953
                        } else {
                            openai_response_json
                        };
954

955
                        // Mask tools back to MCP format for client
956
                        Self::mask_tools_as_mcp(&mut final_response_json, original_body);
957
958
959
960
961
962
                        // Attach conversation id for client response if present (not forwarded upstream)
                        if let Some(conv_id) = original_body.conversation.clone() {
                            if let Some(obj) = final_response_json.as_object_mut() {
                                obj.insert("conversation".to_string(), json!({"id": conv_id}));
                            }
                        }
963
964
                        if original_body.store {
                            if let Err(e) = self
965
                                .store_response_internal(&final_response_json, original_body)
966
967
968
969
970
                                .await
                            {
                                warn!("Failed to store response: {}", e);
                            }
                        }
971
972
973
974
975
976
977
978
979
980
981
982
                        if let Some(conv_id) = original_body.conversation.clone() {
                            if let Err(err) = self
                                .persist_conversation_items(
                                    &conv_id,
                                    original_body,
                                    &final_response_json,
                                )
                                .await
                            {
                                warn!("Failed to persist conversation items: {}", err);
                            }
                        }
983

984
                        match serde_json::to_string(&final_response_json) {
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
                            Ok(json_str) => (
                                StatusCode::OK,
                                [("content-type", "application/json")],
                                json_str,
                            )
                                .into_response(),
                            Err(e) => {
                                error!("Failed to serialize response: {}", e);
                                (
                                    StatusCode::INTERNAL_SERVER_ERROR,
                                    json!({"error": {"message": "Failed to serialize response", "type": "internal_error"}}).to_string(),
                                )
                                    .into_response()
                            }
                        }
                    }
                    Err(e) => {
                        error!("Failed to parse OpenAI response: {}", e);
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to parse response: {}", e),
                        )
                            .into_response()
                    }
                }
            }
            Err(e) => (
                StatusCode::BAD_GATEWAY,
                format!("Failed to forward request to OpenAI: {}", e),
            )
                .into_response(),
        }
    }

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
    async fn persist_conversation_items(
        &self,
        conversation_id: &str,
        original_body: &ResponsesRequest,
        final_response_json: &Value,
    ) -> Result<(), String> {
        persist_items_with_storages(
            self.conversation_storage.clone(),
            self.conversation_item_storage.clone(),
            conversation_id.to_string(),
            original_body.clone(),
            final_response_json.clone(),
        )
        .await
    }

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
    /// Build a request-scoped MCP manager from request tools, if present.
    async fn mcp_manager_from_request_tools(
        tools: &[ResponseTool],
    ) -> Option<Arc<crate::mcp::McpClientManager>> {
        let tool = tools
            .iter()
            .find(|t| matches!(t.r#type, ResponseToolType::Mcp) && t.server_url.is_some())?;
        let server_url = tool.server_url.as_ref()?.trim().to_string();
        if !(server_url.starts_with("http://") || server_url.starts_with("https://")) {
            warn!(
                "Ignoring MCP server_url with unsupported scheme: {}",
                server_url
            );
            return None;
        }
        let name = tool
            .server_label
            .clone()
            .unwrap_or_else(|| "request-mcp".to_string());
        let token = tool.authorization.clone();
        let transport = if server_url.contains("/sse") {
            crate::mcp::McpTransport::Sse {
                url: server_url,
                token,
            }
        } else {
            crate::mcp::McpTransport::Streamable {
                url: server_url,
                token,
            }
        };
        let cfg = crate::mcp::McpConfig {
            servers: vec![crate::mcp::McpServerConfig { name, transport }],
        };
        match crate::mcp::McpClientManager::new(cfg).await {
            Ok(mgr) => Some(Arc::new(mgr)),
            Err(err) => {
                warn!("Failed to initialize request-scoped MCP manager: {}", err);
                None
            }
        }
    }

1078
1079
    async fn handle_streaming_response(
        &self,
1080
1081
1082
1083
1084
        url: String,
        headers: Option<&HeaderMap>,
        payload: Value,
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<String>,
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
    ) -> Response {
        // Check if MCP is active for this request
        let req_mcp_manager = Self::mcp_manager_from_request_tools(&original_body.tools).await;
        let active_mcp = req_mcp_manager.as_ref().or(self.mcp_manager.as_ref());

        // If no MCP is active, use simple pass-through streaming
        if active_mcp.is_none() {
            return self
                .handle_simple_streaming_passthrough(
                    url,
                    headers,
                    payload,
                    original_body,
                    original_previous_response_id,
                )
                .await;
        }

        let active_mcp = active_mcp.unwrap();

        // MCP is active - transform tools and set up interception
        self.handle_streaming_with_tool_interception(
            url,
            headers,
            payload,
            original_body,
            original_previous_response_id,
            active_mcp,
        )
        .await
    }

    /// Simple pass-through streaming without MCP interception
    async fn handle_simple_streaming_passthrough(
        &self,
        url: String,
        headers: Option<&HeaderMap>,
        payload: Value,
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<String>,
1125
    ) -> Response {
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
        let mut request_builder = self.client.post(&url).json(&payload);

        if let Some(headers) = headers {
            request_builder = apply_request_headers(headers, request_builder, true);
        }

        request_builder = request_builder.header("Accept", "text/event-stream");

        let response = match request_builder.send().await {
            Ok(resp) => resp,
            Err(err) => {
                self.circuit_breaker.record_failure();
                return (
                    StatusCode::BAD_GATEWAY,
                    format!("Failed to forward request to OpenAI: {}", err),
                )
                    .into_response();
            }
        };

        let status = response.status();
        let status_code =
            StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

        if !status.is_success() {
            self.circuit_breaker.record_failure();
            let error_body = match response.text().await {
                Ok(body) => body,
                Err(err) => format!("Failed to read upstream error body: {}", err),
            };
            return (status_code, error_body).into_response();
        }

        self.circuit_breaker.record_success();

        let preserved_headers = preserve_response_headers(response.headers());
        let mut upstream_stream = response.bytes_stream();

        let (tx, rx) = mpsc::unbounded_channel::<Result<Bytes, io::Error>>();

        let should_store = original_body.store;
        let storage = self.response_storage.clone();
1168
1169
        let conv_storage = self.conversation_storage.clone();
        let conv_item_storage = self.conversation_item_storage.clone();
1170
        let original_request = original_body.clone();
1171
        let persist_needed = original_request.conversation.is_some();
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
        let previous_response_id = original_previous_response_id.clone();

        tokio::spawn(async move {
            let mut accumulator = StreamingResponseAccumulator::new();
            let mut upstream_failed = false;
            let mut receiver_connected = true;
            let mut pending = String::new();

            while let Some(chunk_result) = upstream_stream.next().await {
                match chunk_result {
                    Ok(chunk) => {
                        let chunk_text = match std::str::from_utf8(&chunk) {
                            Ok(text) => Cow::Borrowed(text),
                            Err(_) => Cow::Owned(String::from_utf8_lossy(&chunk).to_string()),
                        };

                        pending.push_str(&chunk_text.replace("\r\n", "\n"));

                        while let Some(pos) = pending.find("\n\n") {
                            let raw_block = pending[..pos].to_string();
                            pending.drain(..pos + 2);

                            if raw_block.trim().is_empty() {
                                continue;
                            }

                            let block_cow = if let Some(modified) = Self::rewrite_streaming_block(
                                raw_block.as_str(),
                                &original_request,
                                previous_response_id.as_deref(),
                            ) {
                                Cow::Owned(modified)
                            } else {
                                Cow::Borrowed(raw_block.as_str())
                            };

1208
                            if should_store || persist_needed {
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
                                accumulator.ingest_block(block_cow.as_ref());
                            }

                            if receiver_connected {
                                let chunk_to_send = format!("{}\n\n", block_cow);
                                if tx.send(Ok(Bytes::from(chunk_to_send))).is_err() {
                                    receiver_connected = false;
                                }
                            }

                            if !receiver_connected && !should_store {
                                break;
                            }
                        }

                        if !receiver_connected && !should_store {
                            break;
                        }
                    }
                    Err(err) => {
                        upstream_failed = true;
                        let io_err = io::Error::other(err);
                        let _ = tx.send(Err(io_err));
                        break;
                    }
                }
            }

1237
            if (should_store || persist_needed) && !upstream_failed {
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
                if !pending.trim().is_empty() {
                    accumulator.ingest_block(&pending);
                }
                let encountered_error = accumulator.encountered_error().cloned();
                if let Some(mut response_json) = accumulator.into_final_response() {
                    Self::patch_streaming_response_json(
                        &mut response_json,
                        &original_request,
                        previous_response_id.as_deref(),
                    );

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
                    if should_store {
                        if let Err(err) =
                            Self::store_response_impl(&storage, &response_json, &original_request)
                                .await
                        {
                            warn!("Failed to store streaming response: {}", err);
                        }
                    }
                    if persist_needed {
                        if let Some(conv_id) = original_request.conversation.clone() {
                            if let Err(err) = persist_items_with_storages(
                                conv_storage.clone(),
                                conv_item_storage.clone(),
                                conv_id,
                                original_request.clone(),
                                response_json.clone(),
                            )
                            .await
                            {
                                warn!("Failed to persist conversation items (stream): {}", err);
                            }
                        }
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
                    }
                } else if let Some(error_payload) = encountered_error {
                    warn!("Upstream streaming error payload: {}", error_payload);
                } else {
                    warn!("Streaming completed without a final response payload");
                }
            }
        });

        let body_stream = UnboundedReceiverStream::new(rx);
        let mut response = Response::new(Body::from_stream(body_stream));
        *response.status_mut() = status_code;

        let headers_mut = response.headers_mut();
        for (name, value) in preserved_headers.iter() {
            headers_mut.insert(name, value.clone());
        }

        if !headers_mut.contains_key(CONTENT_TYPE) {
            headers_mut.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
        }

        response
1294
1295
    }

1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
    /// Apply all transformations to event data in-place (rewrite + transform)
    /// Optimized to parse JSON only once instead of multiple times
    /// Returns true if any changes were made
    fn apply_event_transformations_inplace(
        parsed_data: &mut Value,
        server_label: &str,
        original_request: &ResponsesRequest,
        previous_response_id: Option<&str>,
    ) -> bool {
        let mut changed = false;

        // 1. Apply rewrite_streaming_block logic (store, previous_response_id, tools masking)
        let event_type = parsed_data
            .get("type")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_default();

        let should_patch = matches!(
            event_type.as_str(),
            event_types::RESPONSE_CREATED
                | event_types::RESPONSE_IN_PROGRESS
                | event_types::RESPONSE_COMPLETED
        );

        if should_patch {
            if let Some(response_obj) = parsed_data
                .get_mut("response")
                .and_then(|v| v.as_object_mut())
            {
                let desired_store = Value::Bool(original_request.store);
                if response_obj.get("store") != Some(&desired_store) {
                    response_obj.insert("store".to_string(), desired_store);
                    changed = true;
                }

                if let Some(prev_id) = previous_response_id {
                    let needs_previous = response_obj
                        .get("previous_response_id")
                        .map(|v| v.is_null() || v.as_str().map(|s| s.is_empty()).unwrap_or(false))
                        .unwrap_or(true);

                    if needs_previous {
                        response_obj.insert(
                            "previous_response_id".to_string(),
                            Value::String(prev_id.to_string()),
                        );
                        changed = true;
                    }
                }

                // Mask tools from function to MCP format (optimized without cloning)
                if response_obj.get("tools").is_some() {
                    let requested_mcp = original_request
                        .tools
                        .iter()
                        .any(|t| matches!(t.r#type, ResponseToolType::Mcp));

                    if requested_mcp {
                        if let Some(mcp_tools) = Self::build_mcp_tools_value(original_request) {
                            response_obj.insert("tools".to_string(), mcp_tools);
                            response_obj
                                .entry("tool_choice".to_string())
                                .or_insert(Value::String("auto".to_string()));
                            changed = true;
                        }
                    }
                }
            }
1365
1366
        }

1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
        // 2. Apply transform_streaming_event logic (function_call → mcp_call)
        match event_type.as_str() {
            event_types::OUTPUT_ITEM_ADDED | event_types::OUTPUT_ITEM_DONE => {
                if let Some(item) = parsed_data.get_mut("item") {
                    if let Some(item_type) = item.get("type").and_then(|v| v.as_str()) {
                        if item_type == event_types::ITEM_TYPE_FUNCTION_CALL
                            || item_type == event_types::ITEM_TYPE_FUNCTION_TOOL_CALL
                        {
                            item["type"] = json!(event_types::ITEM_TYPE_MCP_CALL);
                            item["server_label"] = json!(server_label);

                            // Transform ID from fc_* to mcp_*
                            if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
                                if let Some(stripped) = id.strip_prefix("fc_") {
                                    let new_id = format!("mcp_{}", stripped);
                                    item["id"] = json!(new_id);
                                }
                            }

                            changed = true;
                        }
                    }
                }
1390
            }
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
            event_types::FUNCTION_CALL_ARGUMENTS_DONE => {
                parsed_data["type"] = json!(event_types::MCP_CALL_ARGUMENTS_DONE);

                // Transform item_id from fc_* to mcp_*
                if let Some(item_id) = parsed_data.get("item_id").and_then(|v| v.as_str()) {
                    if let Some(stripped) = item_id.strip_prefix("fc_") {
                        let new_id = format!("mcp_{}", stripped);
                        parsed_data["item_id"] = json!(new_id);
                    }
                }

                changed = true;
            }
            _ => {}
1405
        }
1406
1407

        changed
1408
1409
    }

1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
    /// Forward and transform a streaming event to the client
    /// Returns false if client disconnected
    #[allow(clippy::too_many_arguments)]
    fn forward_streaming_event(
        raw_block: &str,
        event_name: Option<&str>,
        data: &str,
        handler: &mut StreamingToolHandler,
        tx: &mpsc::UnboundedSender<Result<Bytes, io::Error>>,
        server_label: &str,
        original_request: &ResponsesRequest,
        previous_response_id: Option<&str>,
        sequence_number: &mut u64,
    ) -> bool {
        // Skip individual function_call_arguments.delta events - we'll send them as one
        if event_name == Some(event_types::FUNCTION_CALL_ARGUMENTS_DELTA) {
            return true;
        }

        // Parse JSON data once (optimized!)
        let mut parsed_data: Value = match serde_json::from_str(data) {
            Ok(v) => v,
            Err(_) => {
                // If parsing fails, forward raw block as-is
                let chunk_to_send = format!("{}\n\n", raw_block);
                return tx.send(Ok(Bytes::from(chunk_to_send))).is_ok();
            }
1437
1438
        };

1439
1440
1441
        let event_type = event_name
            .or_else(|| parsed_data.get("type").and_then(|v| v.as_str()))
            .unwrap_or("");
1442

1443
1444
1445
        if event_type == event_types::RESPONSE_COMPLETED {
            return true;
        }
1446

1447
1448
        // Check if this is function_call_arguments.done - need to send buffered args first
        let mut mapped_output_index: Option<usize> = None;
1449

1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
        if event_name == Some(event_types::FUNCTION_CALL_ARGUMENTS_DONE) {
            if let Some(output_index) = parsed_data
                .get("output_index")
                .and_then(|v| v.as_u64())
                .map(|v| v as usize)
            {
                let assigned_index = handler
                    .mapped_output_index(output_index)
                    .unwrap_or(output_index);
                mapped_output_index = Some(assigned_index);

                if let Some(call) = handler
                    .pending_calls
                    .iter()
                    .find(|c| c.output_index == output_index)
                {
                    let arguments_value = if call.arguments_buffer.is_empty() {
                        "{}".to_string()
                    } else {
                        call.arguments_buffer.clone()
                    };
1471

1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
                    // Make sure the done event carries full arguments
                    parsed_data["arguments"] = Value::String(arguments_value.clone());

                    // Get item_id and transform it
                    let item_id = parsed_data
                        .get("item_id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    let mcp_item_id = if let Some(stripped) = item_id.strip_prefix("fc_") {
                        format!("mcp_{}", stripped)
                    } else {
                        item_id.to_string()
                    };

                    // Emit a synthetic MCP arguments delta event before the done event
                    let mut delta_event = json!({
                        "type": event_types::MCP_CALL_ARGUMENTS_DELTA,
                        "sequence_number": *sequence_number,
                        "output_index": assigned_index,
                        "item_id": mcp_item_id,
                        "delta": arguments_value,
                    });

                    if let Some(obfuscation) = call.last_obfuscation.as_ref() {
                        if let Some(obj) = delta_event.as_object_mut() {
                            obj.insert(
                                "obfuscation".to_string(),
                                Value::String(obfuscation.clone()),
                            );
                        }
                    } else if let Some(obfuscation) = parsed_data.get("obfuscation").cloned() {
                        if let Some(obj) = delta_event.as_object_mut() {
                            obj.insert("obfuscation".to_string(), obfuscation);
                        }
                    }

                    let delta_block = format!(
                        "event: {}\ndata: {}\n\n",
                        event_types::MCP_CALL_ARGUMENTS_DELTA,
                        delta_event
                    );
                    if tx.send(Ok(Bytes::from(delta_block))).is_err() {
                        return false;
                    }

                    *sequence_number += 1;
                }
            }
        }

        // Remap output_index (if present) so downstream sees sequential indices
        if mapped_output_index.is_none() {
            if let Some(output_index) = parsed_data
                .get("output_index")
                .and_then(|v| v.as_u64())
                .map(|v| v as usize)
            {
                mapped_output_index = handler.mapped_output_index(output_index);
            }
        }

        if let Some(mapped) = mapped_output_index {
            parsed_data["output_index"] = json!(mapped);
        }

        // Apply all transformations in-place (single parse/serialize!)
        Self::apply_event_transformations_inplace(
            &mut parsed_data,
            server_label,
            original_request,
            previous_response_id,
        );

        if let Some(response_obj) = parsed_data
            .get_mut("response")
            .and_then(|v| v.as_object_mut())
        {
            if let Some(original_id) = handler.original_response_id() {
                response_obj.insert("id".to_string(), Value::String(original_id.to_string()));
            }
        }

        // Update sequence number if present in the event
        if parsed_data.get("sequence_number").is_some() {
            parsed_data["sequence_number"] = json!(*sequence_number);
            *sequence_number += 1;
        }

        // Serialize once
        let final_data = match serde_json::to_string(&parsed_data) {
            Ok(s) => s,
            Err(_) => {
                // Serialization failed, forward original
                let chunk_to_send = format!("{}\n\n", raw_block);
                return tx.send(Ok(Bytes::from(chunk_to_send))).is_ok();
            }
        };

        // Rebuild SSE block with potentially transformed event name
        let mut final_block = String::new();
        if let Some(evt) = event_name {
            // Update event name for function_call_arguments events
            if evt == event_types::FUNCTION_CALL_ARGUMENTS_DELTA {
                final_block.push_str(&format!(
                    "event: {}\n",
                    event_types::MCP_CALL_ARGUMENTS_DELTA
                ));
            } else if evt == event_types::FUNCTION_CALL_ARGUMENTS_DONE {
                final_block.push_str(&format!(
                    "event: {}\n",
                    event_types::MCP_CALL_ARGUMENTS_DONE
                ));
            } else {
                final_block.push_str(&format!("event: {}\n", evt));
            }
        }
        final_block.push_str(&format!("data: {}", final_data));

        let chunk_to_send = format!("{}\n\n", final_block);
        if tx.send(Ok(Bytes::from(chunk_to_send))).is_err() {
            return false;
        }

        // After sending output_item.added for mcp_call, inject mcp_call.in_progress event
        if event_name == Some(event_types::OUTPUT_ITEM_ADDED) {
            if let Some(item) = parsed_data.get("item") {
                if item.get("type").and_then(|v| v.as_str())
                    == Some(event_types::ITEM_TYPE_MCP_CALL)
                {
                    // Already transformed to mcp_call
                    if let (Some(item_id), Some(output_index)) = (
                        item.get("id").and_then(|v| v.as_str()),
                        parsed_data.get("output_index").and_then(|v| v.as_u64()),
                    ) {
                        let in_progress_event = json!({
                            "type": event_types::MCP_CALL_IN_PROGRESS,
                            "sequence_number": *sequence_number,
                            "output_index": output_index,
                            "item_id": item_id
                        });
                        *sequence_number += 1;
                        let in_progress_block = format!(
                            "event: {}\ndata: {}\n\n",
                            event_types::MCP_CALL_IN_PROGRESS,
                            in_progress_event
                        );
                        if tx.send(Ok(Bytes::from(in_progress_block))).is_err() {
                            return false;
                        }
                    }
                }
            }
        }

        true
    }

    /// Execute detected tool calls and send completion events to client
    /// Returns false if client disconnected during execution
    async fn execute_streaming_tool_calls(
        pending_calls: Vec<FunctionCallInProgress>,
        active_mcp: &Arc<crate::mcp::McpClientManager>,
        tx: &mpsc::UnboundedSender<Result<Bytes, io::Error>>,
        state: &mut ToolLoopState,
        server_label: &str,
        sequence_number: &mut u64,
    ) -> bool {
        // Execute all pending tool calls (sequential, as PR3 is skipped)
        for call in pending_calls {
            // Skip if name is empty (invalid call)
            if call.name.is_empty() {
                warn!(
                    "Skipping incomplete tool call: name is empty, args_len={}",
                    call.arguments_buffer.len()
                );
                continue;
            }

            info!(
                "Executing tool call during streaming: {} ({})",
                call.name, call.call_id
            );

            // Use empty JSON object if arguments_buffer is empty
            let args_str = if call.arguments_buffer.is_empty() {
                "{}"
            } else {
                &call.arguments_buffer
            };

            let call_result = Self::execute_mcp_call(active_mcp, &call.name, args_str).await;
            let (output_str, success, error_msg) = match call_result {
                Ok((_, output)) => (output, true, None),
                Err(err) => {
                    warn!("Tool execution failed during streaming: {}", err);
                    (json!({ "error": &err }).to_string(), false, Some(err))
                }
            };

            // Send mcp_call completion event to client
            if !OpenAIRouter::send_mcp_call_completion_events_with_error(
                tx,
                &call,
                &output_str,
                server_label,
                success,
                error_msg.as_deref(),
                sequence_number,
            ) {
                // Client disconnected, no point continuing tool execution
                return false;
            }

            // Record the call
            state.record_call(call.call_id, call.name, call.arguments_buffer, output_str);
        }
        true
    }

    /// Transform payload to replace MCP tools with function tools for streaming
    fn prepare_mcp_payload_for_streaming(
        payload: &mut Value,
        active_mcp: &Arc<crate::mcp::McpClientManager>,
    ) {
        if let Some(obj) = payload.as_object_mut() {
            // Remove any non-function tools from outgoing payload
            if let Some(v) = obj.get_mut("tools") {
                if let Some(arr) = v.as_array_mut() {
                    arr.retain(|item| {
                        item.get("type")
                            .and_then(|v| v.as_str())
                            .map(|s| s == event_types::ITEM_TYPE_FUNCTION)
                            .unwrap_or(false)
                    });
                }
            }

            // Build function tools for all discovered MCP tools
            let mut tools_json = Vec::new();
            let tools = active_mcp.list_tools();
            for t in tools {
                let parameters = t.parameters.clone().unwrap_or(serde_json::json!({
                    "type": "object",
                    "properties": {},
                    "additionalProperties": false
                }));
                let tool = serde_json::json!({
                    "type": event_types::ITEM_TYPE_FUNCTION,
                    "name": t.name,
                    "description": t.description,
                    "parameters": parameters
                });
                tools_json.push(tool);
            }
            if !tools_json.is_empty() {
                obj.insert("tools".to_string(), Value::Array(tools_json));
                obj.insert("tool_choice".to_string(), Value::String("auto".to_string()));
            }
        }
    }

    /// Handle streaming WITH MCP tool call interception and execution
    async fn handle_streaming_with_tool_interception(
        &self,
        url: String,
        headers: Option<&HeaderMap>,
        mut payload: Value,
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<String>,
        active_mcp: &Arc<crate::mcp::McpClientManager>,
    ) -> Response {
        // Transform MCP tools to function tools in payload
        Self::prepare_mcp_payload_for_streaming(&mut payload, active_mcp);

        let (tx, rx) = mpsc::unbounded_channel::<Result<Bytes, io::Error>>();
        let should_store = original_body.store;
        let storage = self.response_storage.clone();
1749
1750
        let conv_storage = self.conversation_storage.clone();
        let conv_item_storage = self.conversation_item_storage.clone();
1751
        let original_request = original_body.clone();
1752
        let persist_needed = original_request.conversation.is_some();
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
        let previous_response_id = original_previous_response_id.clone();

        let client = self.client.clone();
        let url_clone = url.clone();
        let headers_opt = headers.cloned();
        let payload_clone = payload.clone();
        let active_mcp_clone = Arc::clone(active_mcp);

        // Spawn the streaming loop task
        tokio::spawn(async move {
            let mut state = ToolLoopState::new(original_request.input.clone());
            let loop_config = McpLoopConfig::default();
            let max_tool_calls = original_request.max_tool_calls.map(|n| n as usize);
            let tools_json = payload_clone.get("tools").cloned().unwrap_or(json!([]));
            let base_payload = payload_clone.clone();
            let mut current_payload = payload_clone;
            let mut mcp_list_tools_sent = false;
            let mut is_first_iteration = true;
            let mut sequence_number: u64 = 0; // Track global sequence number across all iterations
            let mut next_output_index: usize = 0;
            let mut preserved_response_id: Option<String> = None;

            let server_label = original_request
                .tools
                .iter()
                .find(|t| matches!(t.r#type, ResponseToolType::Mcp))
                .and_then(|t| t.server_label.as_deref())
                .unwrap_or("mcp");

            loop {
                // Make streaming request
                let mut request_builder = client.post(&url_clone).json(&current_payload);
                if let Some(ref h) = headers_opt {
                    request_builder = apply_request_headers(h, request_builder, true);
                }
                request_builder = request_builder.header("Accept", "text/event-stream");

                let response = match request_builder.send().await {
                    Ok(r) => r,
                    Err(e) => {
                        let error_event = format!(
                            "event: error\ndata: {{\"error\": {{\"message\": \"{}\"}}}}\n\n",
                            e
                        );
                        let _ = tx.send(Ok(Bytes::from(error_event)));
                        return;
                    }
                };

                if !response.status().is_success() {
                    let status = response.status();
                    let body = response.text().await.unwrap_or_default();
                    let error_event = format!("event: error\ndata: {{\"error\": {{\"message\": \"Upstream error {}: {}\"}}}}\n\n", status, body);
                    let _ = tx.send(Ok(Bytes::from(error_event)));
                    return;
                }

                // Stream events and check for tool calls
                let mut upstream_stream = response.bytes_stream();
                let mut handler = StreamingToolHandler::with_starting_index(next_output_index);
                if let Some(ref id) = preserved_response_id {
                    handler.original_response_id = Some(id.clone());
                }
                let mut pending = String::new();
                let mut tool_calls_detected = false;
                let mut seen_in_progress = false;

                while let Some(chunk_result) = upstream_stream.next().await {
                    match chunk_result {
                        Ok(chunk) => {
                            let chunk_text = match std::str::from_utf8(&chunk) {
                                Ok(text) => Cow::Borrowed(text),
                                Err(_) => Cow::Owned(String::from_utf8_lossy(&chunk).to_string()),
                            };

                            pending.push_str(&chunk_text.replace("\r\n", "\n"));

                            while let Some(pos) = pending.find("\n\n") {
                                let raw_block = pending[..pos].to_string();
                                pending.drain(..pos + 2);

                                if raw_block.trim().is_empty() {
                                    continue;
                                }

                                // Parse event
                                let (event_name, data) = Self::parse_sse_block(&raw_block);

                                if data.is_empty() {
                                    continue;
                                }

                                // Process through handler
                                let action = handler.process_event(event_name, data.as_ref());

                                match action {
                                    StreamAction::Forward => {
                                        // Skip response.created and response.in_progress on subsequent iterations
                                        // Do NOT consume their sequence numbers - we want continuous numbering
                                        let should_skip = if !is_first_iteration {
                                            if let Ok(parsed) =
                                                serde_json::from_str::<Value>(data.as_ref())
                                            {
                                                matches!(
                                                    parsed.get("type").and_then(|v| v.as_str()),
                                                    Some(event_types::RESPONSE_CREATED)
                                                        | Some(event_types::RESPONSE_IN_PROGRESS)
                                                )
                                            } else {
                                                false
                                            }
                                        } else {
                                            false
                                        };

                                        if !should_skip {
                                            // Forward the event
                                            if !Self::forward_streaming_event(
                                                &raw_block,
                                                event_name,
                                                data.as_ref(),
                                                &mut handler,
                                                &tx,
                                                server_label,
                                                &original_request,
                                                previous_response_id.as_deref(),
                                                &mut sequence_number,
                                            ) {
                                                // Client disconnected
                                                return;
                                            }
                                        }

                                        // After forwarding response.in_progress, send mcp_list_tools events (once)
                                        if !seen_in_progress {
                                            if let Ok(parsed) =
                                                serde_json::from_str::<Value>(data.as_ref())
                                            {
                                                if parsed.get("type").and_then(|v| v.as_str())
                                                    == Some(event_types::RESPONSE_IN_PROGRESS)
                                                {
                                                    seen_in_progress = true;
                                                    if !mcp_list_tools_sent {
                                                        let list_tools_index = handler
                                                            .allocate_synthetic_output_index();
                                                        if !OpenAIRouter::send_mcp_list_tools_events(
                                                            &tx,
                                                            &active_mcp_clone,
                                                            server_label,
                                                            list_tools_index,
                                                            &mut sequence_number,
                                                        ) {
                                                            // Client disconnected
                                                            return;
                                                        }
                                                        mcp_list_tools_sent = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    StreamAction::Buffer => {
                                        // Don't forward, just buffer
                                    }
                                    StreamAction::ExecuteTools => {
                                        if !Self::forward_streaming_event(
                                            &raw_block,
                                            event_name,
                                            data.as_ref(),
                                            &mut handler,
                                            &tx,
                                            server_label,
                                            &original_request,
                                            previous_response_id.as_deref(),
                                            &mut sequence_number,
                                        ) {
                                            // Client disconnected
                                            return;
                                        }
                                        tool_calls_detected = true;
                                        break; // Exit stream processing to execute tools
                                    }
                                }
                            }

                            if tool_calls_detected {
                                break;
                            }
                        }
                        Err(e) => {
                            let error_event = format!("event: error\ndata: {{\"error\": {{\"message\": \"Stream error: {}\"}}}}\n\n", e);
                            let _ = tx.send(Ok(Bytes::from(error_event)));
                            return;
                        }
                    }
                }

                next_output_index = handler.next_output_index();
                if let Some(id) = handler.original_response_id().map(|s| s.to_string()) {
                    preserved_response_id = Some(id);
                }

                // If no tool calls, we're done - stream is complete
                if !tool_calls_detected {
                    if !Self::send_final_response_event(
                        &handler,
                        &tx,
                        &mut sequence_number,
                        &state,
                        Some(&active_mcp_clone),
                        &original_request,
                        previous_response_id.as_deref(),
                        server_label,
                    ) {
                        return;
                    }

1970
1971
1972
1973
1974
                    let final_response_json = if should_store || persist_needed {
                        handler.accumulator.into_final_response()
                    } else {
                        None
                    };
1975

1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
                    if let Some(mut response_json) = final_response_json {
                        if let Some(ref id) = preserved_response_id {
                            if let Some(obj) = response_json.as_object_mut() {
                                obj.insert("id".to_string(), Value::String(id.clone()));
                            }
                        }
                        Self::inject_mcp_metadata_streaming(
                            &mut response_json,
                            &state,
                            &active_mcp_clone,
                            server_label,
                        );
1988

1989
1990
1991
1992
1993
1994
                        Self::mask_tools_as_mcp(&mut response_json, &original_request);
                        Self::patch_streaming_response_json(
                            &mut response_json,
                            &original_request,
                            previous_response_id.as_deref(),
                        );
1995

1996
                        if should_store {
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
                            if let Err(err) = Self::store_response_impl(
                                &storage,
                                &response_json,
                                &original_request,
                            )
                            .await
                            {
                                warn!("Failed to store streaming response: {}", err);
                            }
                        }
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025

                        if persist_needed {
                            if let Some(conv_id) = original_request.conversation.clone() {
                                if let Err(err) = persist_items_with_storages(
                                    conv_storage.clone(),
                                    conv_item_storage.clone(),
                                    conv_id,
                                    original_request.clone(),
                                    response_json.clone(),
                                )
                                .await
                                {
                                    warn!(
                                        "Failed to persist conversation items (stream + MCP): {}",
                                        err
                                    );
                                }
                            }
                        }
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
                    }

                    let _ = tx.send(Ok(Bytes::from("data: [DONE]\n\n")));
                    return;
                }

                // Execute tools
                let pending_calls = handler.take_pending_calls();

                // Check iteration limit
                state.iteration += 1;
                state.total_calls += pending_calls.len();

                let effective_limit = match max_tool_calls {
                    Some(user_max) => user_max.min(loop_config.max_iterations),
                    None => loop_config.max_iterations,
                };

                if state.total_calls > effective_limit {
                    warn!(
                        "Reached tool call limit during streaming: {}",
                        effective_limit
                    );
                    let error_event = "event: error\ndata: {\"error\": {\"message\": \"Exceeded max_tool_calls limit\"}}\n\n".to_string();
                    let _ = tx.send(Ok(Bytes::from(error_event)));
                    let _ = tx.send(Ok(Bytes::from("data: [DONE]\n\n")));
                    return;
                }

                // Execute all pending tool calls
                if !Self::execute_streaming_tool_calls(
                    pending_calls,
                    &active_mcp_clone,
                    &tx,
                    &mut state,
                    server_label,
                    &mut sequence_number,
                )
                .await
                {
                    // Client disconnected during tool execution
                    return;
                }

                // Build resume payload
                match Self::build_resume_payload(
                    &base_payload,
                    &state.conversation_history,
                    &state.original_input,
                    &tools_json,
                    true, // is_streaming = true
                ) {
                    Ok(resume_payload) => {
                        current_payload = resume_payload;
                        // Mark that we're no longer on the first iteration
                        is_first_iteration = false;
                        // Continue loop to make next streaming request
                    }
                    Err(e) => {
                        let error_event = format!("event: error\ndata: {{\"error\": {{\"message\": \"Failed to build resume payload: {}\"}}}}\n\n", e);
                        let _ = tx.send(Ok(Bytes::from(error_event)));
                        let _ = tx.send(Ok(Bytes::from("data: [DONE]\n\n")));
                        return;
                    }
                }
            }
        });

        let body_stream = UnboundedReceiverStream::new(rx);
        let mut response = Response::new(Body::from_stream(body_stream));
        *response.status_mut() = StatusCode::OK;
        response
            .headers_mut()
            .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
        response
    }

    /// Parse an SSE block into event name and data
    ///
    /// Returns borrowed strings when possible to avoid allocations in hot paths.
    /// Only allocates when multiple data lines need to be joined.
2107
    fn parse_sse_block(block: &str) -> (Option<&str>, Cow<'_, str>) {
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
        let mut event_name: Option<&str> = None;
        let mut data_lines: Vec<&str> = Vec::new();

        for line in block.lines() {
            if let Some(rest) = line.strip_prefix("event:") {
                event_name = Some(rest.trim());
            } else if let Some(rest) = line.strip_prefix("data:") {
                data_lines.push(rest.trim_start());
            }
        }

        let data = if data_lines.len() == 1 {
2120
            Cow::Borrowed(data_lines[0])
2121
        } else {
2122
            Cow::Owned(data_lines.join("\n"))
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
        };

        (event_name, data)
    }

    // Note: transform_streaming_event has been replaced by apply_event_transformations_inplace
    // which is more efficient (parses JSON only once instead of twice)

    /// Send mcp_list_tools events to client at the start of streaming
    /// Returns false if client disconnected
    fn send_mcp_list_tools_events(
        tx: &mpsc::UnboundedSender<Result<Bytes, io::Error>>,
        mcp: &Arc<crate::mcp::McpClientManager>,
        server_label: &str,
        output_index: usize,
        sequence_number: &mut u64,
    ) -> bool {
        let tools_item_full = Self::build_mcp_list_tools_item(mcp, server_label);
        let item_id = tools_item_full
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        // Create empty tools version for the initial added event
        let mut tools_item_empty = tools_item_full.clone();
        if let Some(obj) = tools_item_empty.as_object_mut() {
            obj.insert("tools".to_string(), json!([]));
        }

        // Event 1: response.output_item.added with empty tools
        let event1_payload = json!({
            "type": event_types::OUTPUT_ITEM_ADDED,
            "sequence_number": *sequence_number,
            "output_index": output_index,
            "item": tools_item_empty
        });
        *sequence_number += 1;
        let event1 = format!(
            "event: {}\ndata: {}\n\n",
            event_types::OUTPUT_ITEM_ADDED,
            event1_payload
        );
        if tx.send(Ok(Bytes::from(event1))).is_err() {
            return false; // Client disconnected
        }

        // Event 2: response.mcp_list_tools.in_progress
        let event2_payload = json!({
            "type": event_types::MCP_LIST_TOOLS_IN_PROGRESS,
            "sequence_number": *sequence_number,
            "output_index": output_index,
            "item_id": item_id
        });
        *sequence_number += 1;
        let event2 = format!(
            "event: {}\ndata: {}\n\n",
            event_types::MCP_LIST_TOOLS_IN_PROGRESS,
            event2_payload
        );
        if tx.send(Ok(Bytes::from(event2))).is_err() {
            return false;
        }

        // Event 3: response.mcp_list_tools.completed
        let event3_payload = json!({
            "type": event_types::MCP_LIST_TOOLS_COMPLETED,
            "sequence_number": *sequence_number,
            "output_index": output_index,
            "item_id": item_id
        });
        *sequence_number += 1;
        let event3 = format!(
            "event: {}\ndata: {}\n\n",
            event_types::MCP_LIST_TOOLS_COMPLETED,
            event3_payload
        );
        if tx.send(Ok(Bytes::from(event3))).is_err() {
            return false;
        }

        // Event 4: response.output_item.done with full tools list
        let event4_payload = json!({
            "type": event_types::OUTPUT_ITEM_DONE,
            "sequence_number": *sequence_number,
            "output_index": output_index,
            "item": tools_item_full
        });
        *sequence_number += 1;
        let event4 = format!(
            "event: {}\ndata: {}\n\n",
            event_types::OUTPUT_ITEM_DONE,
            event4_payload
        );
        tx.send(Ok(Bytes::from(event4))).is_ok()
    }

    /// Send mcp_call completion events after tool execution
    /// Returns false if client disconnected
    fn send_mcp_call_completion_events_with_error(
        tx: &mpsc::UnboundedSender<Result<Bytes, io::Error>>,
        call: &FunctionCallInProgress,
        output: &str,
        server_label: &str,
        success: bool,
        error_msg: Option<&str>,
        sequence_number: &mut u64,
    ) -> bool {
        let effective_output_index = call.effective_output_index();

        // Build mcp_call item (reuse existing function)
        let mcp_call_item = Self::build_mcp_call_item(
            &call.name,
            &call.arguments_buffer,
            output,
            server_label,
            success,
            error_msg,
        );

        // Get the mcp_call item_id
        let item_id = mcp_call_item
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        // Event 1: response.mcp_call.completed
        let completed_payload = json!({
            "type": event_types::MCP_CALL_COMPLETED,
            "sequence_number": *sequence_number,
            "output_index": effective_output_index,
            "item_id": item_id
        });
        *sequence_number += 1;

        let completed_event = format!(
            "event: {}\ndata: {}\n\n",
            event_types::MCP_CALL_COMPLETED,
            completed_payload
        );
        if tx.send(Ok(Bytes::from(completed_event))).is_err() {
            return false;
        }

        // Event 2: response.output_item.done (with completed mcp_call)
        let done_payload = json!({
            "type": event_types::OUTPUT_ITEM_DONE,
            "sequence_number": *sequence_number,
            "output_index": effective_output_index,
            "item": mcp_call_item
        });
        *sequence_number += 1;

        let done_event = format!(
            "event: {}\ndata: {}\n\n",
            event_types::OUTPUT_ITEM_DONE,
            done_payload
        );
        tx.send(Ok(Bytes::from(done_event))).is_ok()
    }

    #[allow(clippy::too_many_arguments)]
    fn send_final_response_event(
        handler: &StreamingToolHandler,
        tx: &mpsc::UnboundedSender<Result<Bytes, io::Error>>,
        sequence_number: &mut u64,
        state: &ToolLoopState,
        active_mcp: Option<&Arc<crate::mcp::McpClientManager>>,
        original_request: &ResponsesRequest,
        previous_response_id: Option<&str>,
        server_label: &str,
    ) -> bool {
        let mut final_response = match handler.snapshot_final_response() {
            Some(resp) => resp,
            None => {
                warn!("Final response snapshot unavailable; skipping synthetic completion event");
                return true;
            }
        };

        if let Some(original_id) = handler.original_response_id() {
            if let Some(obj) = final_response.as_object_mut() {
                obj.insert("id".to_string(), Value::String(original_id.to_string()));
            }
        }

        if let Some(mcp) = active_mcp {
            Self::inject_mcp_metadata_streaming(&mut final_response, state, mcp, server_label);
        }

        Self::mask_tools_as_mcp(&mut final_response, original_request);
        Self::patch_streaming_response_json(
            &mut final_response,
            original_request,
            previous_response_id,
        );

        if let Some(obj) = final_response.as_object_mut() {
            obj.insert("status".to_string(), Value::String("completed".to_string()));
        }

        let completed_payload = json!({
            "type": event_types::RESPONSE_COMPLETED,
            "sequence_number": *sequence_number,
            "response": final_response
        });
        *sequence_number += 1;

        let completed_event = format!(
            "event: {}\ndata: {}\n\n",
            event_types::RESPONSE_COMPLETED,
            completed_payload
        );
        tx.send(Ok(Bytes::from(completed_event))).is_ok()
    }

    /// Inject MCP metadata into a streaming response
    fn inject_mcp_metadata_streaming(
        response: &mut Value,
        state: &ToolLoopState,
        mcp: &Arc<crate::mcp::McpClientManager>,
        server_label: &str,
    ) {
        if let Some(output_array) = response.get_mut("output").and_then(|v| v.as_array_mut()) {
            output_array.retain(|item| {
                item.get("type").and_then(|t| t.as_str())
                    != Some(event_types::ITEM_TYPE_MCP_LIST_TOOLS)
            });

            let list_tools_item = Self::build_mcp_list_tools_item(mcp, server_label);
            output_array.insert(0, list_tools_item);

            let mcp_call_items =
                Self::build_executed_mcp_call_items(&state.conversation_history, server_label);
            let mut insert_pos = 1;
            for item in mcp_call_items {
                output_array.insert(insert_pos, item);
                insert_pos += 1;
            }
        } else if let Some(obj) = response.as_object_mut() {
            let mut output_items = Vec::new();
            output_items.push(Self::build_mcp_list_tools_item(mcp, server_label));
            output_items.extend(Self::build_executed_mcp_call_items(
                &state.conversation_history,
                server_label,
            ));
            obj.insert("output".to_string(), Value::Array(output_items));
        }
    }

    async fn store_response_internal(
        &self,
        response_json: &Value,
        original_body: &ResponsesRequest,
    ) -> Result<(), String> {
        if !original_body.store {
            return Ok(());
        }

        match Self::store_response_impl(&self.response_storage, response_json, original_body).await
        {
            Ok(response_id) => {
                info!(response_id = %response_id.0, "Stored response locally");
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    async fn store_response_impl(
        response_storage: &SharedResponseStorage,
        response_json: &Value,
        original_body: &ResponsesRequest,
    ) -> Result<ResponseId, String> {
        let input_text = match &original_body.input {
            ResponseInput::Text(text) => text.clone(),
            ResponseInput::Items(_) => "complex input".to_string(),
        };

        let output_text = Self::extract_primary_output_text(response_json).unwrap_or_default();

        let mut stored_response = StoredResponse::new(input_text, output_text, None);

        stored_response.instructions = response_json
            .get("instructions")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .or_else(|| original_body.instructions.clone());

        stored_response.model = response_json
            .get("model")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .or_else(|| original_body.model.clone());

        stored_response.user = response_json
            .get("user")
2419
2420
2421
2422
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .or_else(|| original_body.user.clone());

2423
2424
2425
2426
2427
        // Set conversation id from request if provided
        if let Some(conv_id) = original_body.conversation.clone() {
            stored_response.conversation_id = Some(conv_id);
        }

2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
        stored_response.metadata = response_json
            .get("metadata")
            .and_then(|v| v.as_object())
            .map(|m| {
                m.iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect::<HashMap<_, _>>()
            })
            .unwrap_or_else(|| original_body.metadata.clone().unwrap_or_default());

        stored_response.previous_response_id = response_json
            .get("previous_response_id")
            .and_then(|v| v.as_str())
2441
            .map(ResponseId::from)
2442
2443
2444
2445
            .or_else(|| {
                original_body
                    .previous_response_id
                    .as_ref()
2446
                    .map(|id| ResponseId::from(id.as_str()))
2447
2448
2449
            });

        if let Some(id_str) = response_json.get("id").and_then(|v| v.as_str()) {
2450
            stored_response.id = ResponseId::from(id_str);
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
        }

        stored_response.raw_response = response_json.clone();

        response_storage
            .store_response(stored_response)
            .await
            .map_err(|e| format!("Failed to store response: {}", e))
    }

2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
    fn patch_streaming_response_json(
        response_json: &mut Value,
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<&str>,
    ) {
        if let Some(obj) = response_json.as_object_mut() {
            if let Some(prev_id) = original_previous_response_id {
                let should_insert = obj
                    .get("previous_response_id")
                    .map(|v| v.is_null() || v.as_str().map(|s| s.is_empty()).unwrap_or(false))
                    .unwrap_or(true);
                if should_insert {
                    obj.insert(
                        "previous_response_id".to_string(),
                        Value::String(prev_id.to_string()),
                    );
                }
            }

            if !obj.contains_key("instructions")
                || obj
                    .get("instructions")
                    .map(|v| v.is_null())
                    .unwrap_or(false)
            {
                if let Some(instructions) = &original_body.instructions {
                    obj.insert(
                        "instructions".to_string(),
                        Value::String(instructions.clone()),
                    );
                }
            }

            if !obj.contains_key("metadata")
                || obj.get("metadata").map(|v| v.is_null()).unwrap_or(false)
            {
                if let Some(metadata) = &original_body.metadata {
                    let metadata_map: serde_json::Map<String, Value> = metadata
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect();
                    obj.insert("metadata".to_string(), Value::Object(metadata_map));
                }
            }

            obj.insert("store".to_string(), Value::Bool(original_body.store));

            if obj
                .get("model")
                .and_then(|v| v.as_str())
                .map(|s| s.is_empty())
                .unwrap_or(true)
            {
                if let Some(model) = &original_body.model {
                    obj.insert("model".to_string(), Value::String(model.clone()));
                }
            }

            if obj.get("user").map(|v| v.is_null()).unwrap_or(false) {
                if let Some(user) = &original_body.user {
                    obj.insert("user".to_string(), Value::String(user.clone()));
                }
            }
2524
2525
2526
2527
2528

            // Attach conversation id for client response if present (final aggregated JSON)
            if let Some(conv_id) = original_body.conversation.clone() {
                obj.insert("conversation".to_string(), json!({"id": conv_id}));
            }
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
        }
    }

    fn rewrite_streaming_block(
        block: &str,
        original_body: &ResponsesRequest,
        original_previous_response_id: Option<&str>,
    ) -> Option<String> {
        let trimmed = block.trim();
        if trimmed.is_empty() {
            return None;
        }

        let mut data_lines: Vec<String> = Vec::new();

        for line in trimmed.lines() {
            if line.starts_with("data:") {
                data_lines.push(line.trim_start_matches("data:").trim_start().to_string());
            }
        }

        if data_lines.is_empty() {
            return None;
        }

        let payload = data_lines.join("\n");
        let mut parsed: Value = match serde_json::from_str(&payload) {
            Ok(value) => value,
            Err(err) => {
                warn!("Failed to parse streaming JSON payload: {}", err);
                return None;
            }
        };

        let event_type = parsed
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or_default();

        let should_patch = matches!(
            event_type,
2570
2571
2572
            event_types::RESPONSE_CREATED
                | event_types::RESPONSE_IN_PROGRESS
                | event_types::RESPONSE_COMPLETED
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
        );

        if !should_patch {
            return None;
        }

        let mut changed = false;
        if let Some(response_obj) = parsed.get_mut("response").and_then(|v| v.as_object_mut()) {
            let desired_store = Value::Bool(original_body.store);
            if response_obj.get("store") != Some(&desired_store) {
                response_obj.insert("store".to_string(), desired_store);
                changed = true;
            }

            if let Some(prev_id) = original_previous_response_id {
                let needs_previous = response_obj
                    .get("previous_response_id")
                    .map(|v| v.is_null() || v.as_str().map(|s| s.is_empty()).unwrap_or(false))
                    .unwrap_or(true);

                if needs_previous {
                    response_obj.insert(
                        "previous_response_id".to_string(),
                        Value::String(prev_id.to_string()),
                    );
                    changed = true;
                }
            }
2601
2602
2603
2604
2605
2606

            // Attach conversation id into streaming event response content with ordering
            if let Some(conv_id) = original_body.conversation.clone() {
                response_obj.insert("conversation".to_string(), json!({"id": conv_id}));
                changed = true;
            }
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
        }

        if !changed {
            return None;
        }

        let new_payload = match serde_json::to_string(&parsed) {
            Ok(json) => json,
            Err(err) => {
                warn!("Failed to serialize modified streaming payload: {}", err);
                return None;
            }
        };

        let mut rebuilt_lines = Vec::new();
        let mut data_written = false;
        for line in trimmed.lines() {
            if line.starts_with("data:") {
                if !data_written {
                    rebuilt_lines.push(format!("data: {}", new_payload));
                    data_written = true;
                }
            } else {
                rebuilt_lines.push(line.to_string());
            }
        }

        if !data_written {
            rebuilt_lines.push(format!("data: {}", new_payload));
        }

        Some(rebuilt_lines.join("\n"))
    }
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
    fn extract_primary_output_text(response_json: &Value) -> Option<String> {
        if let Some(items) = response_json.get("output").and_then(|v| v.as_array()) {
            for item in items {
                if let Some(content) = item.get("content").and_then(|v| v.as_array()) {
                    for part in content {
                        if part
                            .get("type")
                            .and_then(|v| v.as_str())
                            .map(|t| t == "output_text")
                            .unwrap_or(false)
                        {
                            if let Some(text) = part.get("text").and_then(|v| v.as_str()) {
                                return Some(text.to_string());
                            }
                        }
                    }
                }
            }
        }

        None
    }
2662
2663
}

2664
2665
2666
2667
2668
2669
impl OpenAIRouter {
    fn extract_function_call(resp: &Value) -> Option<(String, String, String)> {
        let output = resp.get("output")?.as_array()?;
        for item in output {
            let obj = item.as_object()?;
            let t = obj.get("type")?.as_str()?;
2670
2671
2672
            if t == event_types::ITEM_TYPE_FUNCTION_TOOL_CALL
                || t == event_types::ITEM_TYPE_FUNCTION_CALL
            {
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
                let call_id = obj
                    .get("call_id")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .or_else(|| {
                        obj.get("id")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                    })?;
                let name = obj.get("name")?.as_str()?.to_string();
                let arguments = obj.get("arguments")?.as_str()?.to_string();
                return Some((call_id, name, arguments));
            }
        }
        None
    }

    /// Replace returned tools with the original request's MCP tool block (if present) so
    /// external clients see MCP semantics rather than internal function tools.
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
    /// Build MCP tools array value without cloning entire response object
    fn build_mcp_tools_value(original_body: &ResponsesRequest) -> Option<Value> {
        let mcp_tool = original_body
            .tools
            .iter()
            .find(|t| matches!(t.r#type, ResponseToolType::Mcp) && t.server_url.is_some())?;

        let mut m = serde_json::Map::new();
        m.insert("type".to_string(), Value::String("mcp".to_string()));
        if let Some(label) = &mcp_tool.server_label {
            m.insert("server_label".to_string(), Value::String(label.clone()));
        }
        if let Some(url) = &mcp_tool.server_url {
            m.insert("server_url".to_string(), Value::String(url.clone()));
        }
        if let Some(desc) = &mcp_tool.server_description {
            m.insert(
                "server_description".to_string(),
                Value::String(desc.clone()),
            );
        }
        if let Some(req) = &mcp_tool.require_approval {
            m.insert("require_approval".to_string(), Value::String(req.clone()));
        }
        if let Some(allowed) = &mcp_tool.allowed_tools {
            m.insert(
                "allowed_tools".to_string(),
                Value::Array(allowed.iter().map(|s| Value::String(s.clone())).collect()),
            );
        }

        Some(Value::Array(vec![Value::Object(m)]))
    }

2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
    fn mask_tools_as_mcp(resp: &mut Value, original_body: &ResponsesRequest) {
        let mcp_tool = original_body
            .tools
            .iter()
            .find(|t| matches!(t.r#type, ResponseToolType::Mcp) && t.server_url.is_some());
        let Some(t) = mcp_tool else {
            return;
        };

        let mut m = serde_json::Map::new();
        m.insert("type".to_string(), Value::String("mcp".to_string()));
        if let Some(label) = &t.server_label {
            m.insert("server_label".to_string(), Value::String(label.clone()));
        }
        if let Some(url) = &t.server_url {
            m.insert("server_url".to_string(), Value::String(url.clone()));
        }
        if let Some(desc) = &t.server_description {
            m.insert(
                "server_description".to_string(),
                Value::String(desc.clone()),
            );
        }
        if let Some(req) = &t.require_approval {
            m.insert("require_approval".to_string(), Value::String(req.clone()));
        }
        if let Some(allowed) = &t.allowed_tools {
            m.insert(
                "allowed_tools".to_string(),
                Value::Array(allowed.iter().map(|s| Value::String(s.clone())).collect()),
            );
        }

        if let Some(obj) = resp.as_object_mut() {
            obj.insert("tools".to_string(), Value::Array(vec![Value::Object(m)]));
            obj.entry("tool_choice")
                .or_insert(Value::String("auto".to_string()));
        }
    }

    async fn execute_mcp_call(
        mcp_mgr: &Arc<crate::mcp::McpClientManager>,
        tool_name: &str,
        args_json_str: &str,
    ) -> Result<(String, String), String> {
        let args_value: Value =
            serde_json::from_str(args_json_str).map_err(|e| format!("parse tool args: {}", e))?;
        let args_obj = args_value.as_object().cloned();

        let server_name = mcp_mgr
            .get_tool(tool_name)
            .map(|t| t.server)
            .ok_or_else(|| format!("tool not found: {}", tool_name))?;

        let result = mcp_mgr
            .call_tool(tool_name, args_obj)
            .await
            .map_err(|e| format!("tool call failed: {}", e))?;

        let output_str = serde_json::to_string(&result)
            .map_err(|e| format!("Failed to serialize tool result: {}", e))?;
        Ok((server_name, output_str))
    }

2790
2791
2792
2793
2794
2795
    /// Build a resume payload with conversation history
    fn build_resume_payload(
        base_payload: &Value,
        conversation_history: &[Value],
        original_input: &ResponseInput,
        tools_json: &Value,
2796
        is_streaming: bool,
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
    ) -> Result<Value, String> {
        // Clone the base payload which already has cleaned fields
        let mut payload = base_payload.clone();

        let obj = payload
            .as_object_mut()
            .ok_or_else(|| "payload not an object".to_string())?;

        // Build input array: start with original user input
        let mut input_array = Vec::new();

        // Add original user message
        // For structured input, serialize the original input items
        match original_input {
            ResponseInput::Text(text) => {
                let user_item = json!({
                    "type": "message",
                    "role": "user",
                    "content": [{ "type": "input_text", "text": text }]
                });
                input_array.push(user_item);
            }
            ResponseInput::Items(items) => {
                // Items are already structured ResponseInputOutputItem, convert to JSON
2821
                if let Ok(items_value) = to_value(items) {
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
                    if let Some(items_arr) = items_value.as_array() {
                        input_array.extend_from_slice(items_arr);
                    }
                }
            }
        }

        // Add all conversation history (function calls and outputs)
        input_array.extend_from_slice(conversation_history);

        obj.insert("input".to_string(), Value::Array(input_array));

        // Use the transformed tools (function tools, not MCP tools)
        if let Some(tools_arr) = tools_json.as_array() {
            if !tools_arr.is_empty() {
                obj.insert("tools".to_string(), tools_json.clone());
            }
        }

2841
2842
        // Set streaming mode based on caller's context
        obj.insert("stream".to_string(), Value::Bool(is_streaming));
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
        obj.insert("store".to_string(), Value::Bool(false));

        // Note: SGLang-specific fields were already removed from base_payload
        // before it was passed to execute_tool_loop (see route_responses lines 1935-1946)

        Ok(payload)
    }

    /// Helper function to build mcp_call items from executed tool calls in conversation history
    fn build_executed_mcp_call_items(
        conversation_history: &[Value],
        server_label: &str,
    ) -> Vec<Value> {
        let mut mcp_call_items = Vec::new();

        for item in conversation_history {
2859
2860
2861
            if item.get("type").and_then(|t| t.as_str())
                == Some(event_types::ITEM_TYPE_FUNCTION_CALL)
            {
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
                let call_id = item.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
                let tool_name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
                let args = item
                    .get("arguments")
                    .and_then(|v| v.as_str())
                    .unwrap_or("{}");

                // Find corresponding output
                let output_item = conversation_history.iter().find(|o| {
                    o.get("type").and_then(|t| t.as_str()) == Some("function_call_output")
                        && o.get("call_id").and_then(|c| c.as_str()) == Some(call_id)
                });

                let output_str = output_item
                    .and_then(|o| o.get("output").and_then(|v| v.as_str()))
                    .unwrap_or("{}");

                // Check if output contains error by parsing JSON
2880
                let is_error = serde_json::from_str::<Value>(output_str)
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
                    .map(|v| v.get("error").is_some())
                    .unwrap_or(false);

                let mcp_call_item = Self::build_mcp_call_item(
                    tool_name,
                    args,
                    output_str,
                    server_label,
                    !is_error,
                    if is_error {
                        Some("Tool execution failed")
                    } else {
                        None
                    },
                );
                mcp_call_items.push(mcp_call_item);
            }
        }

        mcp_call_items
    }

    /// Build an incomplete response when limits are exceeded
    fn build_incomplete_response(
        mut response: Value,
        state: ToolLoopState,
        reason: &str,
        active_mcp: &Arc<crate::mcp::McpClientManager>,
        original_body: &ResponsesRequest,
    ) -> Result<Value, String> {
        let obj = response
            .as_object_mut()
            .ok_or_else(|| "response not an object".to_string())?;

        // Set status to completed (not failed - partial success)
        obj.insert("status".to_string(), Value::String("completed".to_string()));

        // Set incomplete_details
        obj.insert(
            "incomplete_details".to_string(),
            json!({ "reason": reason }),
        );

        // Convert any function_call in output to mcp_call format
        if let Some(output_array) = obj.get_mut("output").and_then(|v| v.as_array_mut()) {
            let server_label = original_body
                .tools
                .iter()
                .find(|t| matches!(t.r#type, ResponseToolType::Mcp))
                .and_then(|t| t.server_label.as_deref())
                .unwrap_or("mcp");

            // Find any function_call items and convert them to mcp_call (incomplete)
            let mut mcp_call_items = Vec::new();
            for item in output_array.iter() {
2936
2937
2938
                if item.get("type").and_then(|t| t.as_str())
                    == Some(event_types::ITEM_TYPE_FUNCTION_TOOL_CALL)
                {
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
                    let tool_name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
                    let args = item
                        .get("arguments")
                        .and_then(|v| v.as_str())
                        .unwrap_or("{}");

                    // Mark as incomplete - not executed
                    let mcp_call_item = Self::build_mcp_call_item(
                        tool_name,
                        args,
                        "", // No output - wasn't executed
                        server_label,
                        false, // Not successful
                        Some("Not executed - response stopped due to limit"),
                    );
                    mcp_call_items.push(mcp_call_item);
                }
            }

            // Add mcp_list_tools and executed mcp_call items at the beginning
            if state.total_calls > 0 || !mcp_call_items.is_empty() {
                let list_tools_item = Self::build_mcp_list_tools_item(active_mcp, server_label);
                output_array.insert(0, list_tools_item);

                // Add mcp_call items for executed calls using helper
                let executed_items =
                    Self::build_executed_mcp_call_items(&state.conversation_history, server_label);

                let mut insert_pos = 1;
                for item in executed_items {
                    output_array.insert(insert_pos, item);
                    insert_pos += 1;
                }

                // Add incomplete mcp_call items
                for item in mcp_call_items {
                    output_array.insert(insert_pos, item);
                    insert_pos += 1;
                }
            }
        }

        // Add warning to metadata
        if let Some(metadata_val) = obj.get_mut("metadata") {
            if let Some(metadata_obj) = metadata_val.as_object_mut() {
                if let Some(mcp_val) = metadata_obj.get_mut("mcp") {
                    if let Some(mcp_obj) = mcp_val.as_object_mut() {
                        mcp_obj.insert(
                            "truncation_warning".to_string(),
                            Value::String(format!(
                                "Loop terminated at {} iterations, {} total calls (reason: {})",
                                state.iteration, state.total_calls, reason
                            )),
                        );
                    }
                }
            }
        }

        Ok(response)
    }

    /// Execute the tool calling loop
    async fn execute_tool_loop(
        &self,
        url: &str,
        headers: Option<&HeaderMap>,
        initial_payload: Value,
        original_body: &ResponsesRequest,
        active_mcp: &Arc<crate::mcp::McpClientManager>,
        config: &McpLoopConfig,
    ) -> Result<Value, String> {
        let mut state = ToolLoopState::new(original_body.input.clone());

        // Get max_tool_calls from request (None means no user-specified limit)
        let max_tool_calls = original_body.max_tool_calls.map(|n| n as usize);

        // Keep initial_payload as base template (already has fields cleaned)
        let base_payload = initial_payload.clone();
        let tools_json = base_payload.get("tools").cloned().unwrap_or(json!([]));
        let mut current_payload = initial_payload;

        info!(
            "Starting tool loop: max_tool_calls={:?}, max_iterations={}",
            max_tool_calls, config.max_iterations
        );

        loop {
            // Make request to upstream
            let request_builder = self.client.post(url).json(&current_payload);
            let request_builder = if let Some(headers) = headers {
                apply_request_headers(headers, request_builder, true)
            } else {
                request_builder
            };

            let response = request_builder
                .send()
                .await
                .map_err(|e| format!("upstream request failed: {}", e))?;

            if !response.status().is_success() {
                let status = response.status();
                let body = response.text().await.unwrap_or_default();
                return Err(format!("upstream error {}: {}", status, body));
            }

            let mut response_json = response
                .json::<Value>()
                .await
                .map_err(|e| format!("parse response: {}", e))?;

            // Check for function call
            if let Some((call_id, tool_name, args_json_str)) =
                Self::extract_function_call(&response_json)
            {
                state.iteration += 1;
                state.total_calls += 1;

                info!(
                    "Tool loop iteration {}: calling {} (call_id: {})",
                    state.iteration, tool_name, call_id
                );

                // Check combined limit: use minimum of user's max_tool_calls (if set) and safety max_iterations
                let effective_limit = match max_tool_calls {
                    Some(user_max) => user_max.min(config.max_iterations),
                    None => config.max_iterations,
                };

                if state.total_calls > effective_limit {
                    if let Some(user_max) = max_tool_calls {
                        if state.total_calls > user_max {
                            warn!("Reached user-specified max_tool_calls limit: {}", user_max);
                        } else {
                            warn!(
                                "Reached safety max_iterations limit: {}",
                                config.max_iterations
                            );
                        }
                    } else {
                        warn!(
                            "Reached safety max_iterations limit: {}",
                            config.max_iterations
                        );
                    }

                    return Self::build_incomplete_response(
                        response_json,
                        state,
                        "max_tool_calls",
                        active_mcp,
                        original_body,
                    );
                }

                // Execute tool
                let call_result =
                    Self::execute_mcp_call(active_mcp, &tool_name, &args_json_str).await;

                let output_str = match call_result {
                    Ok((_, output)) => output,
                    Err(err) => {
                        warn!("Tool execution failed: {}", err);
                        // Return error as output, let model decide how to proceed
                        json!({ "error": err }).to_string()
                    }
                };

                // Record the call
                state.record_call(call_id, tool_name, args_json_str, output_str);

                // Build resume payload
                current_payload = Self::build_resume_payload(
                    &base_payload,
                    &state.conversation_history,
                    &state.original_input,
                    &tools_json,
3117
                    false, // is_streaming = false (non-streaming tool loop)
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
                )?;
            } else {
                // No more tool calls, we're done
                info!(
                    "Tool loop completed: {} iterations, {} total calls",
                    state.iteration, state.total_calls
                );

                // Inject MCP output items if we executed any tools
                if state.total_calls > 0 {
                    let server_label = original_body
                        .tools
                        .iter()
                        .find(|t| matches!(t.r#type, ResponseToolType::Mcp))
                        .and_then(|t| t.server_label.as_deref())
                        .unwrap_or("mcp");

                    // Build mcp_list_tools item
                    let list_tools_item = Self::build_mcp_list_tools_item(active_mcp, server_label);

                    // Insert at beginning of output array
                    if let Some(output_array) = response_json
                        .get_mut("output")
                        .and_then(|v| v.as_array_mut())
                    {
                        output_array.insert(0, list_tools_item);

                        // Build mcp_call items using helper function
                        let mcp_call_items = Self::build_executed_mcp_call_items(
                            &state.conversation_history,
                            server_label,
                        );

                        // Insert mcp_call items after mcp_list_tools using mutable position
                        let mut insert_pos = 1;
                        for item in mcp_call_items {
                            output_array.insert(insert_pos, item);
                            insert_pos += 1;
                        }
                    }
                }

                return Ok(response_json);
            }
        }
    }

3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
    /// Generate a unique ID for MCP output items (similar to OpenAI format)
    fn generate_mcp_id(prefix: &str) -> String {
        use rand::RngCore;
        let mut rng = rand::rng();
        let mut bytes = [0u8; 30];
        rng.fill_bytes(&mut bytes);
        let hex_string: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
        format!("{}_{}", prefix, hex_string)
    }

    /// Build an mcp_list_tools output item
    fn build_mcp_list_tools_item(
        mcp: &Arc<crate::mcp::McpClientManager>,
        server_label: &str,
    ) -> Value {
        let tools = mcp.list_tools();
        let tools_json: Vec<Value> = tools
            .iter()
            .map(|t| {
                json!({
                    "name": t.name,
                    "description": t.description,
                    "input_schema": t.parameters.clone().unwrap_or_else(|| json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    })),
                    "annotations": {
                        "read_only": false
                    }
                })
            })
            .collect();

        json!({
            "id": Self::generate_mcp_id("mcpl"),
3201
            "type": event_types::ITEM_TYPE_MCP_LIST_TOOLS,
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
            "server_label": server_label,
            "tools": tools_json
        })
    }

    /// Build an mcp_call output item
    fn build_mcp_call_item(
        tool_name: &str,
        arguments: &str,
        output: &str,
        server_label: &str,
        success: bool,
        error: Option<&str>,
    ) -> Value {
        json!({
            "id": Self::generate_mcp_id("mcp"),
3218
            "type": event_types::ITEM_TYPE_MCP_CALL,
3219
3220
3221
3222
3223
3224
3225
3226
3227
            "status": if success { "completed" } else { "failed" },
            "approval_request_id": Value::Null,
            "arguments": arguments,
            "error": error,
            "name": tool_name,
            "output": output,
            "server_label": server_label
        })
    }
3228
3229
}

3230
3231
3232
3233
3234
3235
#[async_trait]
impl super::super::RouterTrait for OpenAIRouter {
    fn as_any(&self) -> &dyn Any {
        self
    }

3236
    async fn health_generate(&self, _req: Request<Body>) -> Response {
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
        // Simple upstream probe: GET {base}/v1/models without auth
        let url = format!("{}/v1/models", self.base_url);
        match self
            .client
            .get(&url)
            .timeout(std::time::Duration::from_secs(2))
            .send()
            .await
        {
            Ok(resp) => {
                let code = resp.status();
                // Treat success and auth-required as healthy (endpoint reachable)
                if code.is_success() || code.as_u16() == 401 || code.as_u16() == 403 {
                    (StatusCode::OK, "OK").into_response()
                } else {
                    (
                        StatusCode::SERVICE_UNAVAILABLE,
                        format!("Upstream status: {}", code),
                    )
                        .into_response()
                }
            }
            Err(e) => (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Upstream error: {}", e),
            )
                .into_response(),
        }
    }

    async fn get_server_info(&self, _req: Request<Body>) -> Response {
3268
        let info = json!({
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
            "router_type": "openai",
            "workers": 1,
            "base_url": &self.base_url
        });
        (StatusCode::OK, info.to_string()).into_response()
    }

    async fn get_models(&self, req: Request<Body>) -> Response {
        // Proxy to upstream /v1/models; forward Authorization header if provided
        let headers = req.headers();

        let mut upstream = self.client.get(format!("{}/v1/models", self.base_url));

        if let Some(auth) = headers
            .get("authorization")
            .or_else(|| headers.get("Authorization"))
        {
            upstream = upstream.header("Authorization", auth);
        }

        match upstream.send().await {
            Ok(res) => {
                let status = StatusCode::from_u16(res.status().as_u16())
                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                let content_type = res.headers().get(CONTENT_TYPE).cloned();
                match res.bytes().await {
                    Ok(body) => {
3296
                        let mut response = Response::new(Body::from(body));
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
                        *response.status_mut() = status;
                        if let Some(ct) = content_type {
                            response.headers_mut().insert(CONTENT_TYPE, ct);
                        }
                        response
                    }
                    Err(e) => (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to read upstream response: {}", e),
                    )
                        .into_response(),
                }
            }
            Err(e) => (
                StatusCode::BAD_GATEWAY,
                format!("Failed to contact upstream: {}", e),
            )
                .into_response(),
        }
    }

    async fn get_model_info(&self, _req: Request<Body>) -> Response {
        // Not directly supported without model param; return 501
        (
            StatusCode::NOT_IMPLEMENTED,
            "get_model_info not implemented for OpenAI router",
        )
            .into_response()
    }

    async fn route_generate(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &GenerateRequest,
3331
        _model_id: Option<&str>,
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
    ) -> Response {
        // Generate endpoint is SGLang-specific, not supported for OpenAI backend
        (
            StatusCode::NOT_IMPLEMENTED,
            "Generate endpoint not supported for OpenAI backend",
        )
            .into_response()
    }

    async fn route_chat(
        &self,
        headers: Option<&HeaderMap>,
        body: &ChatCompletionRequest,
3345
        _model_id: Option<&str>,
3346
3347
3348
3349
3350
3351
    ) -> Response {
        if !self.circuit_breaker.can_execute() {
            return (StatusCode::SERVICE_UNAVAILABLE, "Circuit breaker open").into_response();
        }

        // Serialize request body, removing SGLang-only fields
3352
        let mut payload = match to_value(body) {
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
            Ok(v) => v,
            Err(e) => {
                return (
                    StatusCode::BAD_REQUEST,
                    format!("Failed to serialize request: {}", e),
                )
                    .into_response();
            }
        };
        if let Some(obj) = payload.as_object_mut() {
            for key in [
                "top_k",
                "min_p",
                "min_tokens",
                "regex",
                "ebnf",
                "stop_token_ids",
                "no_stop_trim",
                "ignore_eos",
                "continue_final_message",
                "skip_special_tokens",
                "lora_path",
                "session_params",
                "separate_reasoning",
                "stream_reasoning",
                "chat_template_kwargs",
                "return_hidden_states",
                "repetition_penalty",
3381
                "sampling_seed",
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
            ] {
                obj.remove(key);
            }
        }

        let url = format!("{}/v1/chat/completions", self.base_url);
        let mut req = self.client.post(&url).json(&payload);

        // Forward Authorization header if provided
        if let Some(h) = headers {
            if let Some(auth) = h.get("authorization").or_else(|| h.get("Authorization")) {
                req = req.header("Authorization", auth);
            }
        }

        // Accept SSE when stream=true
        if body.stream {
            req = req.header("Accept", "text/event-stream");
        }

        let resp = match req.send().await {
            Ok(r) => r,
            Err(e) => {
                self.circuit_breaker.record_failure();
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("Failed to contact upstream: {}", e),
                )
                    .into_response();
            }
        };

        let status = StatusCode::from_u16(resp.status().as_u16())
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

        if !body.stream {
            // Capture Content-Type before consuming response body
            let content_type = resp.headers().get(CONTENT_TYPE).cloned();
            match resp.bytes().await {
                Ok(body) => {
                    self.circuit_breaker.record_success();
3423
                    let mut response = Response::new(Body::from(body));
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
                    *response.status_mut() = status;
                    if let Some(ct) = content_type {
                        response.headers_mut().insert(CONTENT_TYPE, ct);
                    }
                    response
                }
                Err(e) => {
                    self.circuit_breaker.record_failure();
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to read response: {}", e),
                    )
                        .into_response()
                }
            }
        } else {
            // Stream SSE bytes to client
            let stream = resp.bytes_stream();
3442
            let (tx, rx) = mpsc::unbounded_channel();
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
            tokio::spawn(async move {
                let mut s = stream;
                while let Some(chunk) = s.next().await {
                    match chunk {
                        Ok(bytes) => {
                            if tx.send(Ok(bytes)).is_err() {
                                break;
                            }
                        }
                        Err(e) => {
                            let _ = tx.send(Err(format!("Stream error: {}", e)));
                            break;
                        }
                    }
                }
            });
3459
            let mut response = Response::new(Body::from_stream(UnboundedReceiverStream::new(rx)));
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
            *response.status_mut() = status;
            response
                .headers_mut()
                .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
            response
        }
    }

    async fn route_completion(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &CompletionRequest,
3472
        _model_id: Option<&str>,
3473
3474
3475
3476
3477
3478
3479
3480
3481
    ) -> Response {
        // Completion endpoint not implemented for OpenAI backend
        (
            StatusCode::NOT_IMPLEMENTED,
            "Completion endpoint not implemented for OpenAI backend",
        )
            .into_response()
    }

3482
3483
    async fn route_responses(
        &self,
3484
3485
3486
        headers: Option<&HeaderMap>,
        body: &ResponsesRequest,
        model_id: Option<&str>,
3487
    ) -> Response {
3488
3489
3490
3491
3492
3493
3494
3495
        let url = format!("{}/v1/responses", self.base_url);

        info!(
            requested_store = body.store,
            is_streaming = body.stream,
            "openai_responses_request"
        );

3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
        // Validate mutually exclusive params: previous_response_id and conversation
        // TODO: this validation logic should move the right place, also we need a proper error message module
        if body.previous_response_id.is_some() && body.conversation.is_some() {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "error": {
                        "message": "Mutually exclusive parameters. Ensure you are only providing one of: 'previous_response_id' or 'conversation'.",
                        "type": "invalid_request_error",
                        "param": Value::Null,
                        "code": "mutually_exclusive_parameters"
                    }
                })),
            )
                .into_response();
        }

3513
3514
3515
3516
3517
        // Clone the body and override model if needed
        let mut request_body = body.clone();
        if let Some(model) = model_id {
            request_body.model = Some(model.to_string());
        }
3518
3519
        // Do not forward conversation field upstream; retain for local persistence only
        request_body.conversation = None;
3520
3521
3522
3523
3524
3525
3526

        // Store the original previous_response_id for the response
        let original_previous_response_id = request_body.previous_response_id.clone();

        // Handle previous_response_id by loading prior context
        let mut conversation_items: Option<Vec<ResponseInputOutputItem>> = None;
        if let Some(prev_id_str) = request_body.previous_response_id.clone() {
3527
            let prev_id = ResponseId::from(prev_id_str.as_str());
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
            match self
                .response_storage
                .get_response_chain(&prev_id, None)
                .await
            {
                Ok(chain) => {
                    if !chain.responses.is_empty() {
                        let mut items = Vec::new();
                        for stored in chain.responses.iter() {
                            let trimmed_id = stored.id.0.trim_start_matches("resp_");
                            if !stored.input.is_empty() {
                                items.push(ResponseInputOutputItem::Message {
                                    id: format!("msg_u_{}", trimmed_id),
                                    role: "user".to_string(),
                                    status: Some("completed".to_string()),
                                    content: vec![ResponseContentPart::InputText {
                                        text: stored.input.clone(),
                                    }],
                                });
                            }
                            if !stored.output.is_empty() {
                                items.push(ResponseInputOutputItem::Message {
                                    id: format!("msg_a_{}", trimmed_id),
                                    role: "assistant".to_string(),
                                    status: Some("completed".to_string()),
                                    content: vec![ResponseContentPart::OutputText {
                                        text: stored.output.clone(),
                                        annotations: vec![],
                                        logprobs: None,
                                    }],
                                });
                            }
                        }
                        conversation_items = Some(items);
                    } else {
                        info!(previous_response_id = %prev_id_str, "previous chain empty");
                    }
                }
                Err(err) => {
                    warn!(previous_response_id = %prev_id_str, %err, "failed to fetch previous response chain");
                }
            }
            // Clear previous_response_id from request since we're converting to conversation
            request_body.previous_response_id = None;
        }

3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
        // If conversation is provided, attach its items as input to upstream request
        if let Some(conv_id_str) = body.conversation.clone() {
            let conv_id: ConversationId = conv_id_str.as_str().into();
            let mut items: Vec<ResponseInputOutputItem> = Vec::new();
            // Fetch up to MAX_CONVERSATION_HISTORY_ITEMS items in ascending order
            let params = ConversationItemsListParams {
                limit: Self::MAX_CONVERSATION_HISTORY_ITEMS,
                order: ConversationItemsSortOrder::Asc,
                after: None,
            };
            match self
                .conversation_item_storage
                .list_items(&conv_id, params)
                .await
            {
                Ok(stored_items) => {
                    for it in stored_items {
                        match it.item_type.as_str() {
                            "message" => {
                                // content is expected to be an array of ResponseContentPart
                                let parts: Vec<ResponseContentPart> = match serde_json::from_value(
                                    it.content.clone(),
                                ) {
                                    Ok(parts) => parts,
                                    Err(e) => {
                                        warn!(
                                            item_id = %it.id.0,
                                            error = %e,
                                            "Failed to deserialize conversation item content; skipping message item"
                                        );
                                        continue;
                                    }
                                };
                                let role = it.role.unwrap_or_else(|| "user".to_string());
                                items.push(ResponseInputOutputItem::Message {
                                    id: it.id.0,
                                    role,
                                    content: parts,
                                    status: it.status,
                                });
                            }
                            _ => {
                                // Skip unsupported types for request input (e.g., MCP items)
                            }
                        }
                    }
                }
                Err(err) => {
                    warn!(conversation_id = %conv_id.0, error = %err.to_string(), "Failed to load conversation items for request input");
                }
            }

            // Append the current request input at the end
            match &request_body.input {
                ResponseInput::Text(text) => {
                    items.push(ResponseInputOutputItem::Message {
                        id: format!("msg_u_current_{}", items.len()),
                        role: "user".to_string(),
                        status: Some("completed".to_string()),
                        content: vec![ResponseContentPart::InputText { text: text.clone() }],
                    });
                }
                ResponseInput::Items(existing) => {
                    items.extend(existing.clone());
                }
            }
            request_body.input = ResponseInput::Items(items);
        }

3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
        if let Some(mut items) = conversation_items {
            match &request_body.input {
                ResponseInput::Text(text) => {
                    items.push(ResponseInputOutputItem::Message {
                        id: format!("msg_u_current_{}", items.len()),
                        role: "user".to_string(),
                        status: Some("completed".to_string()),
                        content: vec![ResponseContentPart::InputText { text: text.clone() }],
                    });
                }
                ResponseInput::Items(existing) => {
                    items.extend(existing.clone());
                }
            }
            request_body.input = ResponseInput::Items(items);
        }

        // Always set store=false for OpenAI (we store internally)
        request_body.store = false;

        // Convert to JSON payload and strip SGLang-specific fields before forwarding
        let mut payload = match to_value(&request_body) {
            Ok(value) => value,
            Err(err) => {
                return (
                    StatusCode::BAD_REQUEST,
                    format!("Failed to serialize responses request: {}", err),
                )
                    .into_response();
            }
        };
        if let Some(obj) = payload.as_object_mut() {
            for key in [
                "request_id",
                "priority",
                "frequency_penalty",
                "presence_penalty",
                "stop",
                "top_k",
                "min_p",
                "repetition_penalty",
3684
                "conversation",
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
            ] {
                obj.remove(key);
            }
        }

        // Check if streaming is requested
        if body.stream {
            // Handle streaming response
            self.handle_streaming_response(
                url,
                headers,
                payload,
                body,
                original_previous_response_id,
            )
            .await
        } else {
            // Handle non-streaming response
            self.handle_non_streaming_response(
                url,
                headers,
                payload,
                body,
                original_previous_response_id,
            )
            .await
        }
3712
3713
    }

3714
3715
3716
3717
3718
3719
    async fn get_response(
        &self,
        _headers: Option<&HeaderMap>,
        response_id: &str,
        params: &ResponsesGetParams,
    ) -> Response {
3720
        let stored_id = ResponseId::from(response_id);
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
        if let Ok(Some(stored_response)) = self.response_storage.get_response(&stored_id).await {
            let stream_requested = params.stream.unwrap_or(false);
            let raw_value = stored_response.raw_response.clone();

            if !raw_value.is_null() {
                if stream_requested {
                    return (
                        StatusCode::NOT_IMPLEMENTED,
                        "Streaming retrieval not yet implemented",
                    )
                        .into_response();
                }

                return (
                    StatusCode::OK,
                    [("content-type", "application/json")],
                    raw_value.to_string(),
                )
                    .into_response();
            }

            let openai_response = ResponsesResponse {
                id: stored_response.id.0.clone(),
                object: "response".to_string(),
                created_at: stored_response.created_at.timestamp(),
                status: ResponseStatus::Completed,
                error: None,
                incomplete_details: None,
                instructions: stored_response.instructions.clone(),
                max_output_tokens: None,
                model: stored_response
                    .model
                    .unwrap_or_else(|| "gpt-4o".to_string()),
                output: vec![ResponseOutputItem::Message {
                    id: format!("msg_{}", stored_response.id.0),
                    role: "assistant".to_string(),
                    status: "completed".to_string(),
                    content: vec![ResponseContentPart::OutputText {
                        text: stored_response.output,
                        annotations: vec![],
                        logprobs: None,
                    }],
                }],
                parallel_tool_calls: true,
                previous_response_id: stored_response.previous_response_id.map(|id| id.0),
                reasoning: None,
                store: true,
                temperature: Some(1.0),
                text: Some(ResponseTextFormat {
                    format: TextFormatType {
                        format_type: "text".to_string(),
                    },
                }),
                tool_choice: "auto".to_string(),
                tools: vec![],
                top_p: Some(1.0),
                truncation: Some("disabled".to_string()),
                usage: None,
                user: stored_response.user.clone(),
                metadata: stored_response.metadata.clone(),
            };

            if stream_requested {
                return (
                    StatusCode::NOT_IMPLEMENTED,
                    "Streaming retrieval not yet implemented",
                )
                    .into_response();
            }

            return (
                StatusCode::OK,
                [("content-type", "application/json")],
                serde_json::to_string(&openai_response).unwrap_or_else(|e| {
                    format!("{{\"error\": \"Failed to serialize response: {}\"}}", e)
                }),
            )
                .into_response();
        }

3801
        (
3802
3803
3804
3805
3806
            StatusCode::NOT_FOUND,
            format!(
                "Response with id '{}' not found in local storage",
                response_id
            ),
3807
3808
3809
3810
        )
            .into_response()
    }

3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
    async fn cancel_response(&self, headers: Option<&HeaderMap>, response_id: &str) -> Response {
        // Forward to OpenAI's cancel endpoint
        let url = format!("{}/v1/responses/{}/cancel", self.base_url, response_id);

        let request_builder = self.client.post(&url);

        // Apply headers with filtering (skip content headers for POST without body)
        let request_builder = if let Some(headers) = headers {
            apply_request_headers(headers, request_builder, true)
        } else {
            request_builder
        };

        match request_builder.send().await {
            Ok(response) => {
                let status = response.status();
                let headers = response.headers().clone();

                match response.text().await {
                    Ok(body_text) => {
                        let mut response = (status, body_text).into_response();
                        *response.headers_mut() = preserve_response_headers(&headers);
                        response
                    }
                    Err(e) => (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to read response body: {}", e),
                    )
                        .into_response(),
                }
            }
            Err(e) => (
                StatusCode::BAD_GATEWAY,
                format!("Failed to cancel response on OpenAI: {}", e),
            )
                .into_response(),
        }
3848
3849
    }

3850
3851
3852
    async fn route_embeddings(
        &self,
        _headers: Option<&HeaderMap>,
3853
        _body: &EmbeddingRequest,
3854
3855
        _model_id: Option<&str>,
    ) -> Response {
3856
        (
3857
3858
            StatusCode::FORBIDDEN,
            "Embeddings endpoint not supported for OpenAI backend",
3859
3860
3861
3862
        )
            .into_response()
    }

3863
3864
3865
3866
3867
3868
    async fn route_rerank(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &RerankRequest,
        _model_id: Option<&str>,
    ) -> Response {
3869
        (
3870
3871
            StatusCode::FORBIDDEN,
            "Rerank endpoint not supported for OpenAI backend",
3872
3873
3874
        )
            .into_response()
    }
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168

    async fn create_conversation(&self, _headers: Option<&HeaderMap>, body: &Value) -> Response {
        // TODO: move this spec validation to the right place
        let metadata = match body.get("metadata") {
            Some(Value::Object(map)) => {
                if map.len() > MAX_METADATA_PROPERTIES {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(json!({
                            "error": {
                                "message": format!(
                                    "Invalid 'metadata': too many properties. Max {}, got {}",
                                    MAX_METADATA_PROPERTIES, map.len()
                                ),
                                "type": "invalid_request_error",
                                "param": "metadata",
                                "code": "metadata_max_properties_exceeded"
                            }
                        })),
                    )
                        .into_response();
                }
                Some(map.clone())
            }
            Some(Value::Null) | None => None,
            Some(other) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": {
                            "message": format!(
                                "Invalid 'metadata': expected object or null but got {}",
                                other
                            ),
                            "type": "invalid_request_error",
                            "param": "metadata",
                            "code": "metadata_invalid_type"
                        }
                    })),
                )
                    .into_response();
            }
        };

        match self
            .conversation_storage
            .create_conversation(crate::data_connector::NewConversation { metadata })
            .await
        {
            Ok(conversation) => {
                (StatusCode::OK, Json(conversation_to_json(&conversation))).into_response()
            }
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": {
                        "message": err.to_string(),
                        "type": "internal_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
        }
    }

    async fn get_conversation(
        &self,
        _headers: Option<&HeaderMap>,
        conversation_id: &str,
    ) -> Response {
        let id: ConversationId = conversation_id.to_string().into();
        match self.conversation_storage.get_conversation(&id).await {
            Ok(Some(conv)) => (StatusCode::OK, Json(conversation_to_json(&conv))).into_response(),
            Ok(None) => (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": {
                        "message": format!("Conversation with id '{}' not found.", conversation_id),
                        "type": "invalid_request_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": {
                        "message": err.to_string(),
                        "type": "internal_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
        }
    }

    async fn update_conversation(
        &self,
        _headers: Option<&HeaderMap>,
        conversation_id: &str,
        body: &Value,
    ) -> Response {
        let id: ConversationId = conversation_id.to_string().into();
        let existing = match self.conversation_storage.get_conversation(&id).await {
            Ok(Some(c)) => c,
            Ok(None) => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(json!({
                        "error": {
                            "message": format!("Conversation with id '{}' not found.", conversation_id),
                            "type": "invalid_request_error",
                            "param": Value::Null,
                            "code": Value::Null
                        }
                    })),
                )
                    .into_response();
            }
            Err(err) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({
                        "error": {
                            "message": err.to_string(),
                            "type": "internal_error",
                            "param": Value::Null,
                            "code": Value::Null
                        }
                    })),
                )
                    .into_response();
            }
        };

        // Parse metadata patch
        enum Patch {
            NoChange,
            ClearAll,
            Merge(ConversationMetadata),
        }
        let patch = match body.get("metadata") {
            None => Patch::NoChange,
            Some(Value::Null) => Patch::ClearAll,
            Some(Value::Object(map)) => Patch::Merge(map.clone()),
            Some(other) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": {
                            "message": format!(
                                "Invalid 'metadata': expected object or null but got {}",
                                other
                            ),
                            "type": "invalid_request_error",
                            "param": "metadata",
                            "code": "metadata_invalid_type"
                        }
                    })),
                )
                    .into_response();
            }
        };

        let merged_metadata = match patch {
            Patch::NoChange => {
                return (StatusCode::OK, Json(conversation_to_json(&existing))).into_response();
            }
            Patch::ClearAll => None,
            Patch::Merge(upd) => {
                let mut merged = existing.metadata.clone().unwrap_or_default();
                let previous = merged.len();
                for (k, v) in upd.into_iter() {
                    if v.is_null() {
                        merged.remove(&k);
                    } else {
                        merged.insert(k, v);
                    }
                }
                let updated = merged.len();
                if updated > MAX_METADATA_PROPERTIES {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(json!({
                            "error": {
                                "message": format!(
                                    "Invalid 'metadata': too many properties after update. Max {} ({} -> {}).",
                                    MAX_METADATA_PROPERTIES, previous, updated
                                ),
                                "type": "invalid_request_error",
                                "param": "metadata",
                                "code": "metadata_max_properties_exceeded",
                                "extra": {
                                    "previous_property_count": previous,
                                    "updated_property_count": updated
                                }
                            }
                        })),
                    )
                        .into_response();
                }
                if merged.is_empty() {
                    None
                } else {
                    Some(merged)
                }
            }
        };

        match self
            .conversation_storage
            .update_conversation(&id, merged_metadata)
            .await
        {
            Ok(Some(conv)) => (StatusCode::OK, Json(conversation_to_json(&conv))).into_response(),
            Ok(None) => (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": {
                        "message": format!("Conversation with id '{}' not found.", conversation_id),
                        "type": "invalid_request_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": {
                        "message": err.to_string(),
                        "type": "internal_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
        }
    }

    async fn delete_conversation(
        &self,
        _headers: Option<&HeaderMap>,
        conversation_id: &str,
    ) -> Response {
        let id: ConversationId = conversation_id.to_string().into();
        match self.conversation_storage.delete_conversation(&id).await {
            Ok(true) => (
                StatusCode::OK,
                Json(json!({
                    "id": conversation_id,
                    "object": "conversation.deleted",
                    "deleted": true
                })),
            )
                .into_response(),
            Ok(false) => (
                StatusCode::NOT_FOUND,
                Json(json!({
                    "error": {
                        "message": format!("Conversation with id '{}' not found.", conversation_id),
                        "type": "invalid_request_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": {
                        "message": err.to_string(),
                        "type": "internal_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
        }
    }

    fn router_type(&self) -> &'static str {
        "openai"
    }
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275

    async fn list_conversation_items(
        &self,
        _headers: Option<&HeaderMap>,
        conversation_id: &str,
        limit: Option<usize>,
        order: Option<String>,
        after: Option<String>,
    ) -> Response {
        let id: ConversationId = conversation_id.into();
        match self.conversation_storage.get_conversation(&id).await {
            Ok(Some(_)) => {}
            Ok(None) => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(json!({
                        "error": {
                            "message": format!("Conversation with id '{}' not found.", conversation_id),
                            "type": "invalid_request_error",
                            "param": Value::Null,
                            "code": Value::Null
                        }
                    })),
                )
                    .into_response();
            }
            Err(err) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({
                        "error": {
                            "message": err.to_string(),
                            "type": "internal_error",
                            "param": Value::Null,
                            "code": Value::Null
                        }
                    })),
                )
                    .into_response();
            }
        }

        let lim = limit.unwrap_or(20).clamp(1, 100);
        let sort = match order.as_deref() {
            Some("asc") => ConversationItemsSortOrder::Asc,
            _ => ConversationItemsSortOrder::Desc,
        };
        let params = ConversationItemsListParams {
            limit: lim + 1,
            order: sort,
            after,
        };

        match self.conversation_item_storage.list_items(&id, params).await {
            Ok(mut items) => {
                let has_more = items.len() > lim;
                if has_more {
                    items.truncate(lim);
                }
                let data: Vec<Value> = items
                    .into_iter()
                    .map(|it| {
                        json!({
                            "id": it.id.0,
                            "type": it.item_type,
                            "status": it.status.unwrap_or_else(|| "completed".to_string()),
                            "content": it.content,
                            "role": it.role,
                        })
                    })
                    .collect();
                let first_id = data
                    .first()
                    .and_then(|v| v.get("id"))
                    .cloned()
                    .unwrap_or(Value::Null);
                let last_id = data
                    .last()
                    .and_then(|v| v.get("id"))
                    .cloned()
                    .unwrap_or(Value::Null);
                (
                    StatusCode::OK,
                    Json(json!({
                        "object": "list",
                        "data": data,
                        "first_id": first_id,
                        "last_id": last_id,
                        "has_more": has_more
                    })),
                )
                    .into_response()
            }
            Err(err) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({
                    "error": {
                        "message": err.to_string(),
                        "type": "internal_error",
                        "param": Value::Null,
                        "code": Value::Null
                    }
                })),
            )
                .into_response(),
        }
    }
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
}
// Maximum number of properties allowed in conversation metadata (align with server)
const MAX_METADATA_PROPERTIES: usize = 16;

fn conversation_to_json(conversation: &Conversation) -> Value {
    json!({
        "id": conversation.id.0,
        "object": "conversation",
        "created_at": conversation.created_at.timestamp(),
        "metadata": to_value(&conversation.metadata).unwrap_or(Value::Null),
    })
4287
}
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547

async fn persist_items_with_storages(
    conv_storage: SharedConversationStorage,
    item_storage: SharedConversationItemStorage,
    conversation_id: String,
    request: ResponsesRequest,
    response: Value,
) -> Result<(), String> {
    let conv_id: ConversationId = conversation_id.as_str().into();
    match conv_storage.get_conversation(&conv_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            warn!(conversation_id = %conv_id.0, "Conversation not found; skipping item persistence");
            return Ok(());
        }
        Err(err) => return Err(err.to_string()),
    }

    // Extract response_id once for attaching to both input and output items
    let response_id_opt = response
        .get("id")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Helper to ensure status defaults to completed
    async fn create_and_link_item(
        item_storage: &SharedConversationItemStorage,
        conv_id: &ConversationId,
        mut new_item: DCNewConversationItem,
    ) -> Result<(), String> {
        if new_item.status.is_none() {
            new_item.status = Some("completed".to_string());
        }
        let created = item_storage
            .create_item(new_item)
            .await
            .map_err(|e| e.to_string())?;
        item_storage
            .link_item(conv_id, &created.id, chrono::Utc::now())
            .await
            .map_err(|e| e.to_string())?;
        tracing::info!(conversation_id = %conv_id.0, item_id = %created.id.0, item_type = %created.item_type, "Persisted conversation item and link");
        Ok(())
    }

    match request.input.clone() {
        ResponseInput::Text(text) => {
            let new_item = DCNewConversationItem {
                id: None, // generate new message id for input
                response_id: response_id_opt.clone(),
                item_type: "message".to_string(),
                role: Some("user".to_string()),
                content: json!([{ "type": "input_text", "text": text }]),
                status: Some("completed".to_string()),
            };
            create_and_link_item(&item_storage, &conv_id, new_item).await?;
        }
        ResponseInput::Items(items) => {
            for input_item in items {
                match input_item {
                    ResponseInputOutputItem::Message {
                        role,
                        content,
                        status,
                        ..
                    } => {
                        let content_v =
                            serde_json::to_value(&content).map_err(|e| e.to_string())?;
                        let new_item = DCNewConversationItem {
                            id: None, // generate new id for input items
                            response_id: response_id_opt.clone(),
                            item_type: "message".to_string(),
                            role: Some(role),
                            content: content_v,
                            status,
                        };
                        create_and_link_item(&item_storage, &conv_id, new_item).await?;
                    }
                    ResponseInputOutputItem::Reasoning {
                        summary,
                        content,
                        status,
                        ..
                    } => {
                        let new_item = DCNewConversationItem {
                            id: None, // generate new id for input items
                            response_id: response_id_opt.clone(),
                            item_type: "reasoning".to_string(),
                            role: None,
                            content: json!({ "summary": summary, "content": content }),
                            status,
                        };
                        create_and_link_item(&item_storage, &conv_id, new_item).await?;
                    }
                    ResponseInputOutputItem::FunctionToolCall {
                        name,
                        arguments,
                        output,
                        status,
                        ..
                    } => {
                        let new_item = DCNewConversationItem {
                            id: None, // generate new id for input items
                            response_id: response_id_opt.clone(),
                            item_type: "function_tool_call".to_string(),
                            role: None,
                            content: json!({ "name": name, "arguments": arguments, "output": output }),
                            status,
                        };
                        create_and_link_item(&item_storage, &conv_id, new_item).await?;
                    }
                }
            }
        }
    }

    if let Some(output_array) = response.get("output").and_then(|v| v.as_array()) {
        for item in output_array {
            let item_type = match item.get("type").and_then(|v| v.as_str()) {
                Some(t) => t,
                None => continue,
            };

            match item_type {
                "message" => {
                    let id_in = item
                        .get("id")
                        .and_then(|v| v.as_str())
                        .map(|s| crate::data_connector::ConversationItemId(s.to_string()));
                    let role = item
                        .get("role")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let content_v = item
                        .get("content")
                        .cloned()
                        .unwrap_or_else(|| Value::Array(Vec::new()));
                    let status = item
                        .get("status")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let new_item = DCNewConversationItem {
                        id: id_in,
                        response_id: response_id_opt.clone(),
                        item_type: "message".to_string(),
                        role,
                        content: content_v,
                        status,
                    };
                    create_and_link_item(&item_storage, &conv_id, new_item).await?;
                }
                "reasoning" => {
                    let id_in = item
                        .get("id")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let summary_v = item
                        .get("summary")
                        .cloned()
                        .unwrap_or_else(|| Value::Array(Vec::new()));
                    let content_v = item
                        .get("content")
                        .cloned()
                        .unwrap_or_else(|| Value::Array(Vec::new()));
                    let status = item
                        .get("status")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let new_item = DCNewConversationItem {
                        id: id_in.map(crate::data_connector::ConversationItemId),
                        response_id: response_id_opt.clone(),
                        item_type: "reasoning".to_string(),
                        role: None,
                        content: json!({ "summary": summary_v, "content": content_v }),
                        status,
                    };
                    create_and_link_item(&item_storage, &conv_id, new_item).await?;
                }
                "function_tool_call" => {
                    let id_in = item
                        .get("id")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
                    let arguments = item.get("arguments").and_then(|v| v.as_str()).unwrap_or("");
                    let output_str = item.get("output").and_then(|v| v.as_str()).unwrap_or("");
                    let status = item
                        .get("status")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let new_item = DCNewConversationItem {
                        id: id_in.map(crate::data_connector::ConversationItemId),
                        response_id: response_id_opt.clone(),
                        item_type: "function_tool_call".to_string(),
                        role: None,
                        content: json!({
                            "name": name,
                            "arguments": arguments,
                            "output": output_str
                        }),
                        status,
                    };
                    create_and_link_item(&item_storage, &conv_id, new_item).await?;
                }
                "mcp_call" => {
                    let id_in = item
                        .get("id")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
                    let arguments = item.get("arguments").and_then(|v| v.as_str()).unwrap_or("");
                    let output_str = item.get("output").and_then(|v| v.as_str()).unwrap_or("");
                    let status = item
                        .get("status")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let content_v = json!({
                        "server_label": item.get("server_label").cloned().unwrap_or(Value::Null),
                        "name": name,
                        "arguments": arguments,
                        "output": output_str,
                        "error": item.get("error").cloned().unwrap_or(Value::Null),
                        "approval_request_id": item.get("approval_request_id").cloned().unwrap_or(Value::Null)
                    });
                    let new_item = DCNewConversationItem {
                        id: id_in.map(crate::data_connector::ConversationItemId),
                        response_id: response_id_opt.clone(),
                        item_type: "mcp_call".to_string(),
                        role: None,
                        content: content_v,
                        status,
                    };
                    create_and_link_item(&item_storage, &conv_id, new_item).await?;
                }
                "mcp_list_tools" => {
                    let id_in = item
                        .get("id")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let content_v = json!({
                        "server_label": item.get("server_label").cloned().unwrap_or(Value::Null),
                        "tools": item.get("tools").cloned().unwrap_or_else(|| Value::Array(Vec::new()))
                    });
                    let new_item = DCNewConversationItem {
                        id: id_in.map(crate::data_connector::ConversationItemId),
                        response_id: response_id_opt.clone(),
                        item_type: "mcp_list_tools".to_string(),
                        role: None,
                        content: content_v,
                        status: Some("completed".to_string()),
                    };
                    create_and_link_item(&item_storage, &conv_id, new_item).await?;
                }
                _ => {}
            }
        }
    }

    Ok(())
}