conversations.rs 44 KB
Newer Older
1
2
//! Conversation CRUD operations and persistence

3
4
5
6
7
8
use std::{collections::HashMap, sync::Arc};

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
9
10
11
};
use chrono::Utc;
use serde_json::{json, Value};
12
use tracing::{debug, info, warn};
13

14
use super::responses::build_stored_response;
15
16
17
use crate::{
    data_connector::{
        Conversation, ConversationId, ConversationItemId, ConversationItemStorage,
18
        ConversationStorage, ListParams, NewConversation, NewConversationItem, ResponseId,
19
        ResponseStorage, SortOrder,
20
    },
21
    protocols::responses::{generate_id, ResponseInput, ResponsesRequest},
22
};
23
24
25
26
27
28
29
30
31
32

/// Maximum number of properties allowed in conversation metadata
pub(crate) const MAX_METADATA_PROPERTIES: usize = 16;

// ============================================================================
// Conversation CRUD Operations
// ============================================================================

/// Create a new conversation
pub(super) async fn create_conversation(
33
    conversation_storage: &Arc<dyn ConversationStorage>,
34
35
36
37
38
39
40
41
42
    body: Value,
) -> Response {
    // TODO: The validation should be done in 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!({
43
44
45
46
47
                        "error":
                            format!(
                                "metadata cannot have more than {} properties",
                                MAX_METADATA_PROPERTIES
                            )
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
                    })),
                )
                    .into_response();
            }
            Some(map.clone())
        }
        Some(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "metadata must be an object"})),
            )
                .into_response();
        }
        None => None,
    };

64
65
66
67
    let new_conv = NewConversation {
        id: None, // Generate random ID (OpenAI behavior for POST /v1/conversations)
        metadata,
    };
68
69
70
71
72
73
74
75

    match conversation_storage.create_conversation(new_conv).await {
        Ok(conversation) => {
            info!(conversation_id = %conversation.id.0, "Created conversation");
            (StatusCode::OK, Json(conversation_to_json(&conversation))).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
76
77
78
            Json(json!({
                "error": format!("Failed to create conversation: {}", e)
            })),
79
80
81
82
83
84
85
        )
            .into_response(),
    }
}

/// Get a conversation by ID
pub(super) async fn get_conversation(
86
    conversation_storage: &Arc<dyn ConversationStorage>,
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    conv_id: &str,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);

    match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(conversation)) => {
            (StatusCode::OK, Json(conversation_to_json(&conversation))).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "Conversation not found"})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
105
106
107
            Json(json!({
                "error": format!("Failed to get conversation: {}", e)
            })),
108
109
110
111
112
113
114
        )
            .into_response(),
    }
}

/// Update a conversation's metadata
pub(super) async fn update_conversation(
115
    conversation_storage: &Arc<dyn ConversationStorage>,
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    conv_id: &str,
    body: Value,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);

    let current_meta = match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(meta)) => meta,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
136
137
138
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
            )
                .into_response();
        }
    };

    #[derive(Debug)]
    enum Patch {
        Set(String, Value),
        Delete(String),
    }

    let mut patches: Vec<Patch> = Vec::new();

    if let Some(metadata_val) = body.get("metadata") {
        if let Some(map) = metadata_val.as_object() {
            for (k, v) in map {
                if v.is_null() {
                    patches.push(Patch::Delete(k.clone()));
                } else {
                    patches.push(Patch::Set(k.clone(), v.clone()));
                }
            }
        } else {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "metadata must be an object"})),
            )
                .into_response();
        }
    }

    let mut new_metadata = current_meta.metadata.clone().unwrap_or_default();
    for patch in patches {
        match patch {
            Patch::Set(k, v) => {
                new_metadata.insert(k, v);
            }
            Patch::Delete(k) => {
                new_metadata.remove(&k);
            }
        }
    }

    if new_metadata.len() > MAX_METADATA_PROPERTIES {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({
186
187
188
189
190
                "error":
                    format!(
                        "metadata cannot have more than {} properties",
                        MAX_METADATA_PROPERTIES
                    )
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
            })),
        )
            .into_response();
    }

    let final_metadata = if new_metadata.is_empty() {
        None
    } else {
        Some(new_metadata)
    };

    match conversation_storage
        .update_conversation(&conversation_id, final_metadata)
        .await
    {
        Ok(Some(conversation)) => {
            info!(conversation_id = %conversation_id.0, "Updated conversation");
            (StatusCode::OK, Json(conversation_to_json(&conversation))).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "Conversation not found"})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
217
218
219
            Json(json!({
                "error": format!("Failed to update conversation: {}", e)
            })),
220
221
222
223
224
225
226
        )
            .into_response(),
    }
}

/// Delete a conversation
pub(super) async fn delete_conversation(
227
    conversation_storage: &Arc<dyn ConversationStorage>,
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    conv_id: &str,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);

    match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
247
248
249
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
            )
                .into_response();
        }
    }

    match conversation_storage
        .delete_conversation(&conversation_id)
        .await
    {
        Ok(_) => {
            info!(conversation_id = %conversation_id.0, "Deleted conversation");
            (
                StatusCode::OK,
                Json(json!({
                    "id": conversation_id.0,
                    "object": "conversation.deleted",
                    "deleted": true
                })),
            )
                .into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
273
274
275
            Json(json!({
                "error": format!("Failed to delete conversation: {}", e)
            })),
276
277
278
279
280
281
282
        )
            .into_response(),
    }
}

/// List items in a conversation with pagination
pub(super) async fn list_conversation_items(
283
284
    conversation_storage: &Arc<dyn ConversationStorage>,
    item_storage: &Arc<dyn ConversationItemStorage>,
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    conv_id: &str,
    query_params: HashMap<String, String>,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);

    match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
305
306
307
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
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
            )
                .into_response();
        }
    }

    let limit: usize = query_params
        .get("limit")
        .and_then(|s| s.parse().ok())
        .unwrap_or(100);

    let after = query_params.get("after").map(|s| s.to_string());

    // Default to descending order (most recent first)
    let order = query_params
        .get("order")
        .and_then(|s| match s.as_str() {
            "asc" => Some(SortOrder::Asc),
            "desc" => Some(SortOrder::Desc),
            _ => None,
        })
        .unwrap_or(SortOrder::Desc);

    let params = ListParams {
        limit,
        order,
        after,
    };

    match item_storage.list_items(&conversation_id, params).await {
        Ok(items) => {
            let item_values: Vec<Value> = items
                .iter()
                .map(|item| {
341
342
343
344
                    let mut item_json = item_to_json(item);
                    // Add created_at field for list view
                    if let Some(obj) = item_json.as_object_mut() {
                        obj.insert("created_at".to_string(), json!(item.created_at));
345
                    }
346
                    item_json
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
                })
                .collect();

            let has_more = items.len() == limit;
            let last_id = items.last().map(|item| item.id.0.clone());

            (
                StatusCode::OK,
                Json(json!({
                    "object": "list",
                    "data": item_values,
                    "has_more": has_more,
                    "first_id": items.first().map(|item| &item.id.0),
                    "last_id": last_id,
                })),
            )
                .into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
367
            Json(json!({ "error": format!("Failed to list items: {}", e) })),
368
369
370
371
372
        )
            .into_response(),
    }
}

373
374
375
376
377
378
379
380
381
382
383
384
385
386
// ============================================================================
// Conversation Item Operations
// ============================================================================

/// Supported item types for creation
/// Types marked as "implemented" are fully supported
/// Types marked as "accepted" are stored but return not-implemented warnings
const SUPPORTED_ITEM_TYPES: &[&str] = &[
    // Fully implemented types
    "message",
    "reasoning",
    "mcp_list_tools",
    "mcp_call",
    "item_reference",
387
    "function_call",
388
    "function_call_output",
389
    // Accepted but not yet implemented (stored, warning returned)
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
    "file_search_call",
    "computer_call",
    "computer_call_output",
    "web_search_call",
    "image_generation_call",
    "code_interpreter_call",
    "local_shell_call",
    "local_shell_call_output",
    "mcp_approval_request",
    "mcp_approval_response",
    "custom_tool_call",
    "custom_tool_call_output",
];

/// Item types that are fully implemented with business logic
const IMPLEMENTED_ITEM_TYPES: &[&str] = &[
    "message",
    "reasoning",
    "mcp_list_tools",
    "mcp_call",
    "item_reference",
];

/// Create items in a conversation (bulk operation)
pub(super) async fn create_conversation_items(
415
416
    conversation_storage: &Arc<dyn ConversationStorage>,
    item_storage: &Arc<dyn ConversationItemStorage>,
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    conv_id: &str,
    body: Value,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);

    // Verify conversation exists
    match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
438
439
440
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
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
            )
                .into_response();
        }
    }

    // Parse items array from request
    let items_array = match body.get("items").and_then(|v| v.as_array()) {
        Some(arr) => arr,
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "Missing or invalid 'items' field"})),
            )
                .into_response();
        }
    };

    // Validate limit (max 20 items per OpenAI spec)
    if items_array.len() > 20 {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "Cannot add more than 20 items at a time"})),
        )
            .into_response();
    }

    // Convert and create items
    let mut created_items = Vec::new();
    let mut warnings = Vec::new();
    let added_at = Utc::now();

    for item_val in items_array {
        let item_type = item_val
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("message");

        // Handle item_reference specially - link existing item instead of creating new
        if item_type == "item_reference" {
            let ref_id = match item_val.get("id").and_then(|v| v.as_str()) {
                Some(id) => id,
                None => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(json!({"error": "item_reference requires 'id' field"})),
                    )
                        .into_response();
                }
            };

            let existing_item_id = ConversationItemId::from(ref_id);

            // Retrieve the existing item
            let existing_item = match item_storage.get_item(&existing_item_id).await {
                Ok(Some(item)) => item,
                Ok(None) => {
                    return (
                        StatusCode::NOT_FOUND,
499
500
501
                        Json(json!({
                            "error": format!("Referenced item '{}' not found", ref_id)
                        })),
502
503
504
505
506
507
                    )
                        .into_response();
                }
                Err(e) => {
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
508
509
510
                        Json(json!({
                            "error": format!("Failed to get referenced item: {}", e)
                        })),
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
                    )
                        .into_response();
                }
            };

            // Link existing item to this conversation
            if let Err(e) = item_storage
                .link_item(&conversation_id, &existing_item.id, added_at)
                .await
            {
                warn!("Failed to link item {}: {}", existing_item.id.0, e);
            }

            created_items.push(item_to_json(&existing_item));
            continue;
        }

        // Check if user provided an ID
        let user_provided_id = item_val.get("id").and_then(|v| v.as_str());

        let item = if let Some(id_str) = user_provided_id {
            // User provided an ID - check if it already exists in DB
            let item_id = ConversationItemId::from(id_str);

            // First check if this item is already linked to this conversation
            let is_already_linked = match item_storage
                .is_item_linked(&conversation_id, &item_id)
                .await
            {
                Ok(linked) => linked,
                Err(e) => {
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
544
545
546
                        Json(json!({
                            "error": format!("Failed to check item link: {}", e)
                        })),
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
                    )
                        .into_response();
                }
            };

            if is_already_linked {
                // Item already linked to this conversation - return error
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": {
                            "message": "Item already in conversation",
                            "type": "invalid_request_error",
                            "param": "items",
                            "code": "item_already_in_conversation"
                        }
                    })),
                )
                    .into_response();
            }

            // Check if item exists in DB
            let existing_item = match item_storage.get_item(&item_id).await {
                Ok(Some(item)) => item,
                Ok(None) => {
                    // Item doesn't exist in DB, create new one with user-provided content
                    let (new_item, warning) = match parse_item_from_value(item_val) {
                        Ok((mut item, warn)) => {
                            // Use the user-provided ID
                            item.id = Some(item_id.clone());
                            (item, warn)
                        }
                        Err(e) => {
                            return (
                                StatusCode::BAD_REQUEST,
582
                                Json(json!({ "error": format!("Invalid item: {}", e) })),
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
                            )
                                .into_response();
                        }
                    };

                    // Collect warnings for not-implemented types
                    if let Some(w) = warning {
                        warnings.push(w);
                    }

                    // Create item with provided ID
                    match item_storage.create_item(new_item).await {
                        Ok(item) => item,
                        Err(e) => {
                            return (
                                StatusCode::INTERNAL_SERVER_ERROR,
599
                                Json(json!({ "error": format!("Failed to create item: {}", e) })),
600
601
602
603
604
605
606
607
                            )
                                .into_response();
                        }
                    }
                }
                Err(e) => {
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
608
609
610
                        Json(json!({
                            "error": format!("Failed to check item existence: {}", e)
                        })),
611
612
613
614
615
616
617
618
619
620
621
622
623
                    )
                        .into_response();
                }
            };

            existing_item
        } else {
            // No ID provided - parse and create new item normally
            let (new_item, warning) = match parse_item_from_value(item_val) {
                Ok((item, warn)) => (item, warn),
                Err(e) => {
                    return (
                        StatusCode::BAD_REQUEST,
624
                        Json(json!({ "error": format!("Invalid item: {}", e) })),
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
                    )
                        .into_response();
                }
            };

            // Collect warnings for not-implemented types
            if let Some(w) = warning {
                warnings.push(w);
            }

            // Create item
            match item_storage.create_item(new_item).await {
                Ok(item) => item,
                Err(e) => {
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
641
                        Json(json!({ "error": format!("Failed to create item: {}", e) })),
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
                    )
                        .into_response();
                }
            }
        };

        // Link to conversation
        if let Err(e) = item_storage
            .link_item(&conversation_id, &item.id, added_at)
            .await
        {
            warn!("Failed to link item {}: {}", item.id.0, e);
        }

        created_items.push(item_to_json(&item));
    }

    // Build response matching OpenAI format
    let first_id = created_items.first().and_then(|v| v.get("id"));
    let last_id = created_items.last().and_then(|v| v.get("id"));

    let mut response = json!({
        "object": "list",
        "data": created_items,
        "first_id": first_id,
        "last_id": last_id,
        "has_more": false
    });

    // Add warnings if any not-implemented types were used
    if !warnings.is_empty() {
        if let Some(obj) = response.as_object_mut() {
            obj.insert("warnings".to_string(), json!(warnings));
        }
    }

    (StatusCode::OK, Json(response)).into_response()
}

/// Get a single conversation item
/// Note: `include` query parameter is accepted but not yet implemented
pub(super) async fn get_conversation_item(
684
685
    conversation_storage: &Arc<dyn ConversationStorage>,
    item_storage: &Arc<dyn ConversationItemStorage>,
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
    conv_id: &str,
    item_id: &str,
    _include: Option<Vec<String>>, // Reserved for future use
) -> Response {
    let conversation_id = ConversationId::from(conv_id);
    let item_id = ConversationItemId::from(item_id);

    // Verify conversation exists
    match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
709
710
711
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
712
713
714
715
716
717
718
719
720
721
722
723
724
725
            )
                .into_response();
        }
    }

    // First check if the item is linked to this conversation
    let is_linked = match item_storage
        .is_item_linked(&conversation_id, &item_id)
        .await
    {
        Ok(linked) => linked,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
726
727
728
                Json(json!({
                    "error": format!("Failed to check item link: {}", e)
                })),
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
            )
                .into_response();
        }
    };

    if !is_linked {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "Item not found in this conversation"})),
        )
            .into_response();
    }

    // Get the item
    match item_storage.get_item(&item_id).await {
        Ok(Some(item)) => {
            // TODO: Process `include` parameter when implemented
            // Example: include=["metadata", "timestamps"]
            (StatusCode::OK, Json(item_to_json(&item))).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "Item not found"})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
756
            Json(json!({ "error": format!("Failed to get item: {}", e) })),
757
758
759
760
761
762
763
        )
            .into_response(),
    }
}

/// Delete a conversation item
pub(super) async fn delete_conversation_item(
764
765
    conversation_storage: &Arc<dyn ConversationStorage>,
    item_storage: &Arc<dyn ConversationItemStorage>,
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    conv_id: &str,
    item_id: &str,
) -> Response {
    let conversation_id = ConversationId::from(conv_id);
    let item_id = ConversationItemId::from(item_id);

    // Verify conversation exists and get it for response
    let conversation = match conversation_storage
        .get_conversation(&conversation_id)
        .await
    {
        Ok(Some(conv)) => conv,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": "Conversation not found"})),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
788
789
790
                Json(json!({
                    "error": format!("Failed to get conversation: {}", e)
                })),
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
            )
                .into_response();
        }
    };

    // Delete the item
    match item_storage.delete_item(&conversation_id, &item_id).await {
        Ok(_) => {
            info!(
                conversation_id = %conversation_id.0,
                item_id = %item_id.0,
                "Deleted conversation item"
            );

            // Return updated conversation object (per OpenAI spec)
            (StatusCode::OK, Json(conversation_to_json(&conversation))).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
810
            Json(json!({ "error": format!("Failed to delete item: {}", e) })),
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
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
        )
            .into_response(),
    }
}

/// Parse NewConversationItem from Value
/// Returns (NewConversationItem, Option<warning_message>)
/// Supports three top-level structures:
/// 1. Input message: {"type": "message", "role": "...", "content": [...]}
/// 2. Item: {"type": "message|function_tool_call|...", ...}
/// 3. Item reference: {"type": "item_reference", "id": "..."}
fn parse_item_from_value(
    item_val: &Value,
) -> Result<(NewConversationItem, Option<String>), String> {
    // Detect structure type
    let item_type = item_val
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("message");

    // Validate item type is supported
    if !SUPPORTED_ITEM_TYPES.contains(&item_type) {
        return Err(format!(
            "Unsupported item type '{}'. Supported types: {}",
            item_type,
            SUPPORTED_ITEM_TYPES.join(", ")
        ));
    }

    // Check if type is implemented or just accepted
    let warning = if !IMPLEMENTED_ITEM_TYPES.contains(&item_type) {
        Some(format!(
            "Item type '{}' is accepted but not yet implemented. \
             The item will be stored but may not function as expected.",
            item_type
        ))
    } else {
        None
    };

    // Parse common fields
    let role = item_val
        .get("role")
        .and_then(|v| v.as_str())
        .map(String::from);
    let status = item_val
        .get("status")
        .and_then(|v| v.as_str())
        .map(String::from)
        .or_else(|| Some("completed".to_string())); // Default status

    // Validate message types have role
    if item_type == "message" && role.is_none() {
        return Err("Message items require 'role' field".to_string());
    }

    // For special types (mcp_call, function_tool_call, etc.), store the entire item_val as content
    // For message types, use the content field directly
    let content = if item_type == "message" || item_type == "reasoning" {
        item_val.get("content").cloned().unwrap_or(json!([]))
    } else {
        // Store entire item for extraction later
        item_val.clone()
    };

    Ok((
        NewConversationItem {
            id: None,
            response_id: None,
            item_type: item_type.to_string(),
            role,
            content,
            status,
        },
        warning,
    ))
}

/// Convert ConversationItem to JSON response format
/// Extracts fields from content for special types (mcp_call, mcp_list_tools, etc.)
891
fn item_to_json(item: &crate::data_connector::ConversationItem) -> Value {
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
    let mut obj = serde_json::Map::new();
    obj.insert("id".to_string(), json!(item.id.0));
    obj.insert("type".to_string(), json!(item.item_type));

    if let Some(role) = &item.role {
        obj.insert("role".to_string(), json!(role));
    }

    // Handle special item types that need field extraction from content
    match item.item_type.as_str() {
        "mcp_call" => {
            // Extract mcp_call fields: name, arguments, output, server_label, approval_request_id, error
            if let Some(content_obj) = item.content.as_object() {
                if let Some(name) = content_obj.get("name") {
                    obj.insert("name".to_string(), name.clone());
                }
                if let Some(arguments) = content_obj.get("arguments") {
                    obj.insert("arguments".to_string(), arguments.clone());
                }
                if let Some(output) = content_obj.get("output") {
                    obj.insert("output".to_string(), output.clone());
                }
                if let Some(server_label) = content_obj.get("server_label") {
                    obj.insert("server_label".to_string(), server_label.clone());
                }
                if let Some(approval_request_id) = content_obj.get("approval_request_id") {
                    obj.insert(
                        "approval_request_id".to_string(),
                        approval_request_id.clone(),
                    );
                }
                if let Some(error) = content_obj.get("error") {
                    obj.insert("error".to_string(), error.clone());
                }
            }
        }
        "mcp_list_tools" => {
            // Extract mcp_list_tools fields: tools, server_label
            if let Some(content_obj) = item.content.as_object() {
                if let Some(tools) = content_obj.get("tools") {
                    obj.insert("tools".to_string(), tools.clone());
                }
                if let Some(server_label) = content_obj.get("server_label") {
                    obj.insert("server_label".to_string(), server_label.clone());
                }
            }
        }
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
        "function_call" => {
            // Extract function_call fields: call_id, name, arguments, output
            if let Some(content_obj) = item.content.as_object() {
                for field in ["call_id", "name", "arguments", "output"] {
                    if let Some(value) = content_obj.get(field) {
                        obj.insert(field.to_string(), value.clone());
                    }
                }
            }
        }
        "function_call_output" => {
            // Extract function_call_output fields: call_id, output
            if let Some(content_obj) = item.content.as_object() {
                for field in ["call_id", "output"] {
                    if let Some(value) = content_obj.get(field) {
                        obj.insert(field.to_string(), value.clone());
                    }
                }
            }
        }
959
960
961
962
963
964
965
966
967
968
969
970
971
        _ => {
            // For all other types (message, reasoning, etc.), keep content as-is
            obj.insert("content".to_string(), item.content.clone());
        }
    }

    if let Some(status) = &item.status {
        obj.insert("status".to_string(), json!(status));
    }

    Value::Object(obj)
}

972
973
974
975
976
// ============================================================================
// Persistence Operations
// ============================================================================

/// Persist conversation items (delegates to persist_items_with_storages)
977
pub async fn persist_conversation_items(
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
    conversation_storage: Arc<dyn ConversationStorage>,
    item_storage: Arc<dyn ConversationItemStorage>,
    response_storage: Arc<dyn ResponseStorage>,
    response_json: &Value,
    original_body: &ResponsesRequest,
) -> Result<(), String> {
    persist_items_with_storages(
        conversation_storage,
        item_storage,
        response_storage,
        response_json,
        original_body,
    )
    .await
}

994
995
/// Helper function to create and optionally link a conversation item
/// If conv_id is None, only creates the item without linking
996
997
async fn create_and_link_item(
    item_storage: &Arc<dyn ConversationItemStorage>,
998
    conv_id_opt: Option<&ConversationId>,
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
    mut new_item: NewConversationItem,
) -> Result<(), String> {
    // Set default status if not provided
    if new_item.status.is_none() {
        new_item.status = Some("completed".to_string());
    }

    // Step 1: Create the item
    let created = item_storage
        .create_item(new_item)
        .await
        .map_err(|e| format!("Failed to create item: {}", e))?;

1012
1013
1014
1015
1016
1017
    // Step 2: Link it to the conversation (if provided)
    if let Some(conv_id) = conv_id_opt {
        item_storage
            .link_item(conv_id, &created.id, Utc::now())
            .await
            .map_err(|e| format!("Failed to link item: {}", e))?;
1018

1019
        debug!(
1020
1021
1022
1023
1024
1025
            conversation_id = %conv_id.0,
            item_id = %created.id.0,
            item_type = %created.item_type,
            "Persisted conversation item and link"
        );
    } else {
1026
        debug!(
1027
1028
1029
1030
1031
            item_id = %created.id.0,
            item_type = %created.item_type,
            "Persisted conversation item (no conversation link)"
        );
    }
1032
1033
1034
1035
1036

    Ok(())
}

/// Persist conversation items with all storages
1037
1038
1039
1040
1041
1042
///
/// This function:
/// 1. Extracts and normalizes input items from the request
/// 2. Extracts output items from the response
/// 3. Stores ALL items in response storage (always)
/// 4. If conversation provided, also links items to conversation
1043
1044
1045
1046
1047
1048
1049
async fn persist_items_with_storages(
    conversation_storage: Arc<dyn ConversationStorage>,
    item_storage: Arc<dyn ConversationItemStorage>,
    response_storage: Arc<dyn ResponseStorage>,
    response_json: &Value,
    original_body: &ResponsesRequest,
) -> Result<(), String> {
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
    // Step 1: Extract response ID
    let response_id_str = response_json
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Response missing id field".to_string())?;
    let response_id = ResponseId::from(response_id_str);

    // Step 2: Parse and normalize input items from request
    let input_items = extract_input_items(&original_body.input)?;

    // Step 3: Parse output items from response
    let output_items = extract_output_items(response_json)?;

    // Step 4: Build StoredResponse with input and output as JSON arrays
    let mut stored_response = build_stored_response(response_json, original_body);
    stored_response.id = response_id.clone();
    stored_response.input = Value::Array(input_items.clone());
    stored_response.output = Value::Array(output_items.clone());

    // Step 5: Store response (ALWAYS, regardless of conversation)
    response_storage
        .store_response(stored_response)
        .await
        .map_err(|e| format!("Failed to store response: {}", e))?;

    // Step 6: Check if conversation is provided and validate it
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
    let conv_id_opt = match &original_body.conversation {
        Some(id) => {
            let conv_id = ConversationId::from(id.as_str());
            // Verify conversation exists
            if conversation_storage
                .get_conversation(&conv_id)
                .await
                .map_err(|e| format!("Failed to get conversation: {}", e))?
                .is_none()
            {
                warn!(conversation_id = %conv_id.0, "Conversation not found, skipping item linking");
1087
                None // Conversation doesn't exist, items already stored in response
1088
1089
1090
1091
            } else {
                Some(conv_id)
            }
        }
1092
        None => None, // No conversation provided, items already stored in response
1093
1094
    };

1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
    // Step 7: If conversation exists, link items to it
    if let Some(conv_id) = conv_id_opt {
        link_items_to_conversation(
            &item_storage,
            &conv_id,
            &input_items,
            &output_items,
            response_id_str,
        )
        .await?;
1105

1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
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
        info!(
            conversation_id = %conv_id.0,
            response_id = %response_id.0,
            input_count = input_items.len(),
            output_count = output_items.len(),
            "Persisted response and linked items to conversation"
        );
    } else {
        info!(
            response_id = %response_id.0,
            input_count = input_items.len(),
            output_count = output_items.len(),
            "Persisted response without conversation linking"
        );
    }

    Ok(())
}

/// Extract and normalize input items from ResponseInput
fn extract_input_items(input: &ResponseInput) -> Result<Vec<Value>, String> {
    use crate::protocols::responses::{ResponseInputOutputItem, StringOrContentParts};

    let items = match input {
        ResponseInput::Text(text) => {
            // Convert simple text to message item
            vec![json!({
                "id": generate_id("msg"),
                "type": "message",
                "role": "user",
                "content": [{"type": "input_text", "text": text}],
                "status": "completed"
            })]
        }
        ResponseInput::Items(items) => {
            // Process all item types and ensure IDs
            items
                .iter()
                .map(|item| {
                    match item {
                        ResponseInputOutputItem::SimpleInputMessage { content, role, .. } => {
                            // Convert SimpleInputMessage to standard message format with ID
                            let content_json = match content {
                                StringOrContentParts::String(s) => {
                                    json!([{"type": "input_text", "text": s}])
                                }
                                StringOrContentParts::Array(parts) => serde_json::to_value(parts)
                                    .map_err(|e| {
                                    format!("Failed to serialize content: {}", e)
                                })?,
1156
                            };
1157
1158
1159
1160
1161
1162
1163
1164

                            Ok(json!({
                                "id": generate_id("msg"),
                                "type": "message",
                                "role": role,
                                "content": content_json,
                                "status": "completed"
                            }))
1165
1166
                        }
                        _ => {
1167
                            // For other item types (Message, Reasoning, FunctionToolCall, FunctionCallOutput), serialize and ensure ID
1168
                            let mut value = serde_json::to_value(item)
1169
                                .map_err(|e| format!("Failed to serialize item: {}", e))?;
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179

                            // Ensure ID exists - generate if missing
                            if let Some(obj) = value.as_object_mut() {
                                if !obj.contains_key("id")
                                    || obj
                                        .get("id")
                                        .and_then(|v| v.as_str())
                                        .map(|s| s.is_empty())
                                        .unwrap_or(true)
                                {
1180
1181
1182
1183
1184
1185
1186
1187
1188
                                    // Generate ID with appropriate prefix based on type
                                    let item_type =
                                        obj.get("type").and_then(|v| v.as_str()).unwrap_or("item");
                                    let prefix = match item_type {
                                        "function_call" | "function_call_output" => "fc",
                                        "message" => "msg",
                                        _ => "item",
                                    };
                                    obj.insert("id".to_string(), json!(generate_id(prefix)));
1189
1190
1191
1192
                                }
                            }

                            Ok(value)
1193
                        }
1194
                    }
1195
1196
                })
                .collect::<Result<Vec<_>, String>>()?
1197
        }
1198
    };
1199

1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
    Ok(items)
}

/// Extract ALL output items from response JSON
fn extract_output_items(response_json: &Value) -> Result<Vec<Value>, String> {
    response_json
        .get("output")
        .and_then(|v| v.as_array())
        .cloned()
        .ok_or_else(|| "No output array in response".to_string())
}

/// Link ALL input and output items to a conversation
async fn link_items_to_conversation(
    item_storage: &Arc<dyn ConversationItemStorage>,
    conv_id: &ConversationId,
    input_items: &[Value],
    output_items: &[Value],
    response_id: &str,
) -> Result<(), String> {
    let response_id_opt = Some(response_id.to_string());

    // Link ALL input items (no filtering by type)
    for input_item_value in input_items {
        let item_type = input_item_value
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("message");
        let role = input_item_value
            .get("role")
            .and_then(|v| v.as_str())
            .map(String::from);
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243

        // For function_call and function_call_output, store the entire item as content
        // For message types, extract just the content field
        let content = if item_type == "function_call" || item_type == "function_call_output" {
            input_item_value.clone()
        } else {
            input_item_value
                .get("content")
                .cloned()
                .unwrap_or(json!([]))
        };

1244
1245
1246
1247
1248
        let status = input_item_value
            .get("status")
            .and_then(|v| v.as_str())
            .map(String::from);

1249
1250
1251
1252
1253
1254
        // Extract the original item ID from input if present
        let item_id = input_item_value
            .get("id")
            .and_then(|v| v.as_str())
            .map(ConversationItemId::from);

1255
        let new_item = NewConversationItem {
1256
            id: item_id, // Preserve ID if present
1257
1258
1259
1260
1261
1262
1263
1264
            response_id: response_id_opt.clone(),
            item_type: item_type.to_string(),
            role,
            content,
            status,
        };

        create_and_link_item(item_storage, Some(conv_id), new_item).await?;
1265
1266
    }

1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
    // Link ALL output items (no filtering by type)
    // Store reasoning, function_tool_call, mcp_call, and any other types
    for output_item_value in output_items {
        let item_type = output_item_value
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("message");
        let role = output_item_value
            .get("role")
            .and_then(|v| v.as_str())
            .map(String::from);
        let status = output_item_value
            .get("status")
            .and_then(|v| v.as_str())
            .map(String::from);
1282

1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
        // Extract the original item ID from the response
        let item_id = output_item_value
            .get("id")
            .and_then(|v| v.as_str())
            .map(ConversationItemId::from);

        // For non-message types, store the entire item as content
        // For message types, extract just the content field
        let content = if item_type == "message" {
            output_item_value
                .get("content")
                .cloned()
                .unwrap_or(json!([]))
        } else {
1297
            // For other types (reasoning, function_call, function_call_output, mcp_call, etc.)
1298
1299
1300
            // store the entire item structure
            output_item_value.clone()
        };
1301

1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
        let new_item = NewConversationItem {
            id: item_id, // Preserve ID if present
            response_id: response_id_opt.clone(),
            item_type: item_type.to_string(),
            role,
            content,
            status,
        };

        create_and_link_item(item_storage, Some(conv_id), new_item).await?;
1312
    }
1313
1314
1315
1316
1317
1318
1319
1320
1321

    Ok(())
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Convert conversation to JSON response
1322
pub(crate) fn conversation_to_json(conversation: &Conversation) -> Value {
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
    let mut response = json!({
        "id": conversation.id.0,
        "object": "conversation",
        "created_at": conversation.created_at.timestamp()
    });

    if let Some(metadata) = &conversation.metadata {
        if !metadata.is_empty() {
            if let Some(obj) = response.as_object_mut() {
                obj.insert("metadata".to_string(), Value::Object(metadata.clone()));
            }
        }
    }

    response
}