clawft-core 0.3.1

Core engine for clawft (agent loop, message bus, context management)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
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
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
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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
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
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
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
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
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
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
1078
1079
1080
1081
1082
1083
1084
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
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
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
1208
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
//! OpenAI-compatible transport implementation.
//!
//! Provides two transport variants:
//!
//! - [`OpenAiCompatTransport::new()`] -- Stub that returns an error, used
//!   during early development or when no LLM provider is configured.
//!
//! - [`OpenAiCompatTransport::with_provider()`] -- Wraps any implementation
//!   of [`LlmProvider`] to make real HTTP calls to an LLM endpoint.
//!
//! Once the `clawft-llm` crate exposes its `Provider` trait and
//! `OpenAiCompatProvider`, callers create an adapter implementing
//! [`LlmProvider`] and pass it via `with_provider()`.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tracing::debug;

use clawft_types::error::ClawftError;
use clawft_types::provider::{ContentBlock, LlmResponse, StopReason, Usage};

use super::traits::LlmTransport;
#[cfg(feature = "native")]
use super::traits::StreamCallback;
use super::traits::TransportRequest;

/// An abstraction over the underlying LLM HTTP client.
///
/// This trait bridges the gap between the pipeline's `TransportRequest`
/// format and whatever HTTP client library the LLM provider uses. It
/// intentionally uses simple types (strings, JSON values) so that it
/// can be implemented without importing `clawft-llm` types directly.
///
/// Once `clawft-llm` fully exports its `Provider` trait, a blanket
/// adapter will be provided.
#[async_trait]
pub trait LlmProvider: Send + Sync {
    /// Execute a chat completion call and return the raw JSON response.
    ///
    /// The response must be a JSON object with at minimum:
    /// - `id` (string): response identifier
    /// - `choices` (array): list of completion choices
    /// - `choices[].message.role` (string): "assistant"
    /// - `choices[].message.content` (string): response text
    /// - `choices[].finish_reason` (string|null): "stop", "tool_calls", "length"
    ///
    /// Tool calls should appear in `choices[].message.tool_calls[]` with:
    /// - `id` (string): tool call identifier
    /// - `function.name` (string): tool name
    /// - `function.arguments` (string): JSON-encoded arguments
    async fn complete(
        &self,
        model: &str,
        messages: &[serde_json::Value],
        tools: &[serde_json::Value],
        max_tokens: Option<i32>,
        temperature: Option<f64>,
    ) -> Result<serde_json::Value, String>;

    /// Execute a streaming chat completion, sending text deltas to the channel.
    ///
    /// Each string sent is a text delta from the SSE stream. The function
    /// should return the final aggregated JSON response (same format as
    /// `complete()`) after the stream ends.
    ///
    /// The default implementation returns an error indicating streaming is
    /// not supported. Providers that support streaming should override this.
    ///
    /// Only available with the `native` feature (requires tokio channels).
    #[cfg(feature = "native")]
    async fn complete_stream(
        &self,
        _model: &str,
        _messages: &[serde_json::Value],
        _tools: &[serde_json::Value],
        _max_tokens: Option<i32>,
        _temperature: Option<f64>,
        _tx: tokio::sync::mpsc::Sender<String>,
    ) -> Result<serde_json::Value, String> {
        Err("streaming not supported by this provider".into())
    }
}

/// OpenAI-compatible transport for the pipeline.
///
/// Can operate in two modes:
/// - **Stub mode** (default): Returns an error indicating no provider is configured.
/// - **Provider mode**: Delegates to an injected [`LlmProvider`] for real calls.
pub struct OpenAiCompatTransport {
    provider: Option<Arc<dyn LlmProvider>>,
    /// Named providers for multi-provider routing (keyed by provider prefix).
    providers: HashMap<String, Arc<dyn LlmProvider>>,
}

impl OpenAiCompatTransport {
    /// Create a stub transport that returns an error on every call.
    ///
    /// Use this during development or when no LLM provider is available.
    pub fn new() -> Self {
        Self {
            provider: None,
            providers: HashMap::new(),
        }
    }

    /// Create a transport backed by a real LLM provider.
    ///
    /// The provider will be called for every `complete()` invocation,
    /// and its JSON response will be converted to the pipeline's
    /// [`LlmResponse`] type.
    pub fn with_provider(provider: Arc<dyn LlmProvider>) -> Self {
        Self {
            provider: Some(provider),
            providers: HashMap::new(),
        }
    }

    /// Create a transport backed by multiple named LLM providers.
    ///
    /// The `providers` map is keyed by provider prefix (e.g. `"gemini"`,
    /// `"openrouter"`, `"anthropic"`). When a [`TransportRequest`] arrives,
    /// the transport looks up `request.provider` in this map. If no match
    /// is found, it falls back to `fallback`.
    pub fn with_providers(
        providers: HashMap<String, Arc<dyn LlmProvider>>,
        fallback: Arc<dyn LlmProvider>,
    ) -> Self {
        Self {
            provider: Some(fallback),
            providers,
        }
    }

    /// Returns true if this transport has a configured provider.
    pub fn is_configured(&self) -> bool {
        self.provider.is_some() || !self.providers.is_empty()
    }
}

impl Default for OpenAiCompatTransport {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl LlmTransport for OpenAiCompatTransport {
    async fn complete(&self, request: &TransportRequest) -> clawft_types::Result<LlmResponse> {
        let provider = self
            .providers
            .get(&request.provider)
            .or(self.provider.as_ref())
            .ok_or_else(|| ClawftError::Provider {
                message: "transport not configured -- call with_provider()".into(),
            })?;

        // Convert pipeline messages to JSON values for the provider.
        // For assistant messages with tool_calls, use null content instead of ""
        // so Anthropic's API correctly associates the tool call IDs.
        let messages: Vec<serde_json::Value> = request
            .messages
            .iter()
            .map(|m| {
                let content_value = if m.content.is_empty() && m.tool_calls.is_some() {
                    serde_json::Value::Null
                } else {
                    serde_json::json!(m.content)
                };
                let mut msg = serde_json::json!({
                    "role": m.role,
                    "content": content_value,
                });
                if let Some(ref id) = m.tool_call_id {
                    msg["tool_call_id"] = serde_json::json!(id);
                }
                if let Some(ref tcs) = m.tool_calls {
                    msg["tool_calls"] = serde_json::json!(tcs);
                }
                msg
            })
            .collect();

        debug!(
            provider = %request.provider,
            model = %request.model,
            messages = messages.len(),
            "sending request via transport"
        );

        // Call the provider
        let raw_response = provider
            .complete(
                &request.model,
                &messages,
                &request.tools,
                request.max_tokens,
                request.temperature,
            )
            .await
            .map_err(|e| ClawftError::Provider { message: e })?;

        // Convert the raw JSON to our LlmResponse
        convert_response(raw_response)
    }

    #[cfg(feature = "native")]
    async fn complete_stream(
        &self,
        request: &TransportRequest,
        mut callback: StreamCallback,
    ) -> clawft_types::Result<LlmResponse> {
        let provider = self
            .providers
            .get(&request.provider)
            .or(self.provider.as_ref())
            .ok_or_else(|| ClawftError::Provider {
                message: "transport not configured -- call with_provider()".into(),
            })?;

        let messages: Vec<serde_json::Value> = request
            .messages
            .iter()
            .map(|m| {
                let content_value = if m.content.is_empty() && m.tool_calls.is_some() {
                    serde_json::Value::Null
                } else {
                    serde_json::json!(m.content)
                };
                let mut msg = serde_json::json!({
                    "role": m.role,
                    "content": content_value,
                });
                if let Some(ref id) = m.tool_call_id {
                    msg["tool_call_id"] = serde_json::json!(id);
                }
                if let Some(ref tcs) = m.tool_calls {
                    msg["tool_calls"] = serde_json::json!(tcs);
                }
                msg
            })
            .collect();

        debug!(
            provider = %request.provider,
            model = %request.model,
            messages = messages.len(),
            "sending streaming request via transport"
        );

        let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(64);

        let model = request.model.clone();
        let tools = request.tools.clone();
        let max_tokens = request.max_tokens;
        let temperature = request.temperature;
        let provider_clone = Arc::clone(provider);

        let stream_handle = tokio::spawn(async move {
            provider_clone
                .complete_stream(&model, &messages, &tools, max_tokens, temperature, tx)
                .await
        });

        let mut full_text = String::new();
        while let Some(text_delta) = rx.recv().await {
            full_text.push_str(&text_delta);
            if !callback(&text_delta) {
                break;
            }
        }

        let stream_result = stream_handle.await.map_err(|e| ClawftError::Provider {
            message: format!("stream task panicked: {e}"),
        })?;

        match stream_result {
            Ok(raw_response) => convert_response(raw_response),
            Err(e) => {
                if !full_text.is_empty() {
                    debug!(
                        "stream ended with error but collected {} chars, returning partial response",
                        full_text.len()
                    );
                    Ok(LlmResponse {
                        id: "stream-partial".into(),
                        content: vec![ContentBlock::Text { text: full_text }],
                        stop_reason: StopReason::EndTurn,
                        usage: Usage {
                            input_tokens: 0,
                            output_tokens: 0,
                            total_tokens: 0,
                        },
                        metadata: HashMap::new(),
                    })
                } else {
                    Err(ClawftError::Provider { message: e })
                }
            }
        }
    }
}

/// Convert a raw OpenAI-format JSON response to an [`LlmResponse`].
///
/// Handles both text responses and tool-call responses, extracting
/// content blocks, stop reason, and usage statistics.
fn convert_response(resp: serde_json::Value) -> clawft_types::Result<LlmResponse> {
    let id = resp
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let model = resp
        .get("model")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    // Extract the first choice
    let choice = resp
        .get("choices")
        .and_then(|v| v.as_array())
        .and_then(|arr| arr.first())
        .ok_or_else(|| ClawftError::Provider {
            message: "response has no choices".into(),
        })?;

    let message = choice.get("message").ok_or_else(|| ClawftError::Provider {
        message: "choice has no message".into(),
    })?;

    let finish_reason = choice
        .get("finish_reason")
        .and_then(|v| v.as_str())
        .unwrap_or("stop");

    // Build content blocks
    let mut content = Vec::new();

    // Extract text content
    if let Some(text) = message.get("content").and_then(|v| v.as_str())
        && !text.is_empty()
    {
        content.push(ContentBlock::Text {
            text: text.to_string(),
        });
    }

    // Extract tool calls
    if let Some(tool_calls) = message.get("tool_calls").and_then(|v| v.as_array()) {
        for tc in tool_calls {
            let tc_id = tc
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown")
                .to_string();
            let function = tc.get("function").cloned().unwrap_or_default();
            let name = function
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown")
                .to_string();
            let arguments = function
                .get("arguments")
                .and_then(|v| v.as_str())
                .unwrap_or("{}");

            let input: serde_json::Value =
                crate::json_repair::parse_with_repair(arguments).unwrap_or(serde_json::json!({}));

            content.push(ContentBlock::ToolUse {
                id: tc_id,
                name,
                input,
            });
        }
    }

    // Determine stop reason
    let stop_reason = match finish_reason {
        "stop" => StopReason::EndTurn,
        "tool_calls" => StopReason::ToolUse,
        "length" => StopReason::MaxTokens,
        "stop_sequence" => StopReason::StopSequence,
        _ => StopReason::EndTurn,
    };

    // Extract usage
    let usage_obj = resp.get("usage");
    let usage = Usage {
        input_tokens: usage_obj
            .and_then(|u| u.get("prompt_tokens"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32,
        output_tokens: usage_obj
            .and_then(|u| u.get("completion_tokens"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32,
        total_tokens: usage_obj
            .and_then(|u| u.get("total_tokens"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32,
    };

    let mut metadata = HashMap::new();
    metadata.insert("model".into(), serde_json::json!(model));

    Ok(LlmResponse {
        id,
        content,
        stop_reason,
        usage,
        metadata,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::traits::LlmMessage;
    use tokio::sync::mpsc;

    fn make_transport_request() -> TransportRequest {
        TransportRequest {
            provider: "openai".into(),
            model: "gpt-4o".into(),
            messages: vec![LlmMessage {
                role: "user".into(),
                content: "hello".into(),
                tool_call_id: None,
                tool_calls: None,
            }],
            tools: vec![],
            max_tokens: Some(1024),
            temperature: Some(0.7),
        }
    }

    // -- Stub mode tests --

    #[tokio::test]
    async fn stub_returns_error() {
        let transport = OpenAiCompatTransport::new();
        let result = transport.complete(&make_transport_request()).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("transport not configured"),
            "error should mention not configured: {msg}"
        );
    }

    #[tokio::test]
    async fn stub_returns_provider_error_variant() {
        let transport = OpenAiCompatTransport::new();
        let result = transport.complete(&make_transport_request()).await;
        match result {
            Err(ClawftError::Provider { message }) => {
                assert!(message.contains("with_provider"));
            }
            other => panic!("expected Provider error, got: {other:?}"),
        }
    }

    #[test]
    fn default_trait_impl() {
        let transport = OpenAiCompatTransport::default();
        assert!(!transport.is_configured());
    }

    #[test]
    fn new_is_not_configured() {
        let transport = OpenAiCompatTransport::new();
        assert!(!transport.is_configured());
    }

    // -- Provider mode tests --

    struct MockProvider {
        response: serde_json::Value,
    }

    impl MockProvider {
        fn text_response(text: &str) -> Self {
            Self {
                response: serde_json::json!({
                    "id": "resp-1",
                    "choices": [{
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": text
                        },
                        "finish_reason": "stop"
                    }],
                    "usage": {
                        "prompt_tokens": 10,
                        "completion_tokens": 5,
                        "total_tokens": 15
                    },
                    "model": "test-model"
                }),
            }
        }

        fn tool_call_response() -> Self {
            Self {
                response: serde_json::json!({
                    "id": "resp-2",
                    "choices": [{
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": "",
                            "tool_calls": [{
                                "id": "call_abc",
                                "type": "function",
                                "function": {
                                    "name": "get_weather",
                                    "arguments": "{\"city\":\"London\"}"
                                }
                            }]
                        },
                        "finish_reason": "tool_calls"
                    }],
                    "usage": {
                        "prompt_tokens": 15,
                        "completion_tokens": 8,
                        "total_tokens": 23
                    },
                    "model": "test-model"
                }),
            }
        }
    }

    #[async_trait]
    impl LlmProvider for MockProvider {
        async fn complete(
            &self,
            _model: &str,
            _messages: &[serde_json::Value],
            _tools: &[serde_json::Value],
            _max_tokens: Option<i32>,
            _temperature: Option<f64>,
        ) -> Result<serde_json::Value, String> {
            Ok(self.response.clone())
        }
    }

    struct FailingProvider;

    #[async_trait]
    impl LlmProvider for FailingProvider {
        async fn complete(
            &self,
            _model: &str,
            _messages: &[serde_json::Value],
            _tools: &[serde_json::Value],
            _max_tokens: Option<i32>,
            _temperature: Option<f64>,
        ) -> Result<serde_json::Value, String> {
            Err("mock network failure".into())
        }
    }

    #[test]
    fn with_provider_is_configured() {
        let provider = Arc::new(MockProvider::text_response("hi"));
        let transport = OpenAiCompatTransport::with_provider(provider);
        assert!(transport.is_configured());
    }

    #[tokio::test]
    async fn provider_text_response() {
        let provider = Arc::new(MockProvider::text_response("Hello from LLM!"));
        let transport = OpenAiCompatTransport::with_provider(provider);
        let result = transport.complete(&make_transport_request()).await.unwrap();

        assert_eq!(result.id, "resp-1");
        assert_eq!(result.stop_reason, StopReason::EndTurn);
        assert_eq!(result.content.len(), 1);
        match &result.content[0] {
            ContentBlock::Text { text } => assert_eq!(text, "Hello from LLM!"),
            _ => panic!("expected Text block"),
        }
        assert_eq!(result.usage.input_tokens, 10);
        assert_eq!(result.usage.output_tokens, 5);
    }

    #[tokio::test]
    async fn provider_tool_call_response() {
        let provider = Arc::new(MockProvider::tool_call_response());
        let transport = OpenAiCompatTransport::with_provider(provider);
        let result = transport.complete(&make_transport_request()).await.unwrap();

        assert_eq!(result.id, "resp-2");
        assert_eq!(result.stop_reason, StopReason::ToolUse);
        // Should have tool call block (empty text is skipped)
        assert_eq!(result.content.len(), 1);
        match &result.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call_abc");
                assert_eq!(name, "get_weather");
                assert_eq!(input["city"], "London");
            }
            _ => panic!("expected ToolUse block"),
        }
    }

    #[tokio::test]
    async fn provider_error_propagates() {
        let provider = Arc::new(FailingProvider);
        let transport = OpenAiCompatTransport::with_provider(provider);
        let result = transport.complete(&make_transport_request()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("mock network failure"));
    }

    // -- convert_response tests --

    #[test]
    fn convert_text_response() {
        let resp = serde_json::json!({
            "id": "test-id",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "hello world"
                },
                "finish_reason": "stop"
            }],
            "usage": {
                "prompt_tokens": 5,
                "completion_tokens": 3,
                "total_tokens": 8
            },
            "model": "gpt-4o"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.id, "test-id");
        assert_eq!(result.stop_reason, StopReason::EndTurn);
        match &result.content[0] {
            ContentBlock::Text { text } => assert_eq!(text, "hello world"),
            _ => panic!("expected Text"),
        }
    }

    #[test]
    fn convert_tool_call_response() {
        let resp = serde_json::json!({
            "id": "tc-resp",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": null,
                    "tool_calls": [{
                        "id": "call-1",
                        "type": "function",
                        "function": {
                            "name": "search",
                            "arguments": "{\"q\": \"rust\"}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "gpt-4o"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.stop_reason, StopReason::ToolUse);
        assert_eq!(result.content.len(), 1);
        match &result.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call-1");
                assert_eq!(name, "search");
                assert_eq!(input["q"], "rust");
            }
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_no_choices() {
        let resp = serde_json::json!({
            "id": "empty",
            "choices": [],
            "model": "test"
        });
        let result = convert_response(resp);
        assert!(result.is_err());
    }

    #[test]
    fn convert_response_max_tokens_stop() {
        let resp = serde_json::json!({
            "id": "len",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "truncated..."
                },
                "finish_reason": "length"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.stop_reason, StopReason::MaxTokens);
    }

    #[test]
    fn convert_response_missing_usage() {
        let resp = serde_json::json!({
            "id": "no-usage",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "ok"
                },
                "finish_reason": "stop"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.usage.input_tokens, 0);
        assert_eq!(result.usage.output_tokens, 0);
    }

    #[test]
    fn convert_response_mixed_text_and_tools() {
        let resp = serde_json::json!({
            "id": "mixed",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "Let me check that.",
                    "tool_calls": [{
                        "id": "call-2",
                        "type": "function",
                        "function": {
                            "name": "lookup",
                            "arguments": "{}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        // Should have both text and tool use blocks
        assert_eq!(result.content.len(), 2);
        assert!(matches!(&result.content[0], ContentBlock::Text { .. }));
        assert!(matches!(&result.content[1], ContentBlock::ToolUse { .. }));
    }

    #[tokio::test]
    async fn stub_ignores_request_fields() {
        let transport = OpenAiCompatTransport::new();

        let req1 = TransportRequest {
            provider: "anthropic".into(),
            model: "claude-opus-4-5".into(),
            messages: vec![],
            tools: vec![serde_json::json!({"type": "function"})],
            max_tokens: None,
            temperature: None,
        };
        let req2 = make_transport_request();

        let err1 = transport.complete(&req1).await.unwrap_err().to_string();
        let err2 = transport.complete(&req2).await.unwrap_err().to_string();
        assert_eq!(err1, err2);
    }

    #[test]
    fn convert_response_invalid_arguments_json() {
        let resp = serde_json::json!({
            "id": "bad-args",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "id": "call-bad",
                        "type": "function",
                        "function": {
                            "name": "test",
                            "arguments": "not valid json"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        // Should not fail -- invalid arguments default to empty object
        let result = convert_response(resp).unwrap();
        match &result.content[0] {
            ContentBlock::ToolUse { input, .. } => {
                assert_eq!(*input, serde_json::json!({}));
            }
            _ => panic!("expected ToolUse"),
        }
    }

    // ── GAP-17: Tool call parsing edge case tests ─────────────────────

    #[test]
    fn convert_response_missing_tool_use_id() {
        // Some providers may omit the tool call id entirely.
        let resp = serde_json::json!({
            "id": "missing-id",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "type": "function",
                        "function": {
                            "name": "read_file",
                            "arguments": "{\"path\":\"/tmp/test.txt\"}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.content.len(), 1);
        match &result.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "unknown", "missing id should default to 'unknown'");
                assert_eq!(name, "read_file");
                assert_eq!(input["path"], "/tmp/test.txt");
            }
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_empty_arguments_string() {
        // Provider returns empty string instead of valid JSON for arguments.
        let resp = serde_json::json!({
            "id": "empty-args",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "id": "call-empty",
                        "type": "function",
                        "function": {
                            "name": "list_dir",
                            "arguments": ""
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        match &result.content[0] {
            ContentBlock::ToolUse { name, input, .. } => {
                assert_eq!(name, "list_dir");
                // Empty string is not valid JSON, should default to {}
                assert_eq!(*input, serde_json::json!({}));
            }
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_nested_json_arguments() {
        // Arguments with deeply nested JSON objects.
        let resp = serde_json::json!({
            "id": "nested-args",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "id": "call-nested",
                        "type": "function",
                        "function": {
                            "name": "complex_tool",
                            "arguments": "{\"config\":{\"nested\":{\"deep\":true}},\"items\":[1,2,3]}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        match &result.content[0] {
            ContentBlock::ToolUse { name, input, .. } => {
                assert_eq!(name, "complex_tool");
                assert_eq!(input["config"]["nested"]["deep"], true);
                assert_eq!(input["items"], serde_json::json!([1, 2, 3]));
            }
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_missing_function_field() {
        // Tool call with missing function field entirely.
        let resp = serde_json::json!({
            "id": "no-func",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "id": "call-nofunc",
                        "type": "function"
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        match &result.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call-nofunc");
                assert_eq!(
                    name, "unknown",
                    "missing function.name should default to 'unknown'"
                );
                assert_eq!(*input, serde_json::json!({}));
            }
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_multiple_tool_calls() {
        // Response with multiple tool calls in a single message.
        let resp = serde_json::json!({
            "id": "multi-tc",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [
                        {
                            "id": "call-1",
                            "type": "function",
                            "function": {
                                "name": "read_file",
                                "arguments": "{\"path\":\"a.txt\"}"
                            }
                        },
                        {
                            "id": "call-2",
                            "type": "function",
                            "function": {
                                "name": "web_search",
                                "arguments": "{\"query\":\"rust\"}"
                            }
                        }
                    ]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.content.len(), 2);
        match &result.content[0] {
            ContentBlock::ToolUse { name, .. } => assert_eq!(name, "read_file"),
            _ => panic!("expected ToolUse"),
        }
        match &result.content[1] {
            ContentBlock::ToolUse { name, .. } => assert_eq!(name, "web_search"),
            _ => panic!("expected ToolUse"),
        }
    }

    #[test]
    fn convert_response_null_content_with_tool_calls() {
        // Content is null (not empty string) and there are tool calls.
        let resp = serde_json::json!({
            "id": "null-content",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": null,
                    "tool_calls": [{
                        "id": "call-null",
                        "type": "function",
                        "function": {
                            "name": "exec",
                            "arguments": "{\"command\":\"ls\"}"
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        // Null content should not produce a Text block
        assert_eq!(result.content.len(), 1);
        assert!(matches!(&result.content[0], ContentBlock::ToolUse { .. }));
    }

    #[test]
    fn convert_response_missing_message_field() {
        // Choice missing the message field entirely.
        let resp = serde_json::json!({
            "id": "no-msg",
            "choices": [{
                "index": 0,
                "finish_reason": "stop"
            }],
            "model": "test"
        });
        let result = convert_response(resp);
        assert!(result.is_err(), "should fail when message field is missing");
    }

    #[test]
    fn convert_response_unknown_finish_reason() {
        // Unknown finish_reason should default to EndTurn.
        let resp = serde_json::json!({
            "id": "unknown-fr",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "ok"
                },
                "finish_reason": "content_filter"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        assert_eq!(result.stop_reason, StopReason::EndTurn);
    }

    #[test]
    fn convert_response_null_finish_reason() {
        // finish_reason is null (streaming incomplete).
        let resp = serde_json::json!({
            "id": "null-fr",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "partial"
                },
                "finish_reason": null
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        // null finish_reason should default to "stop" -> EndTurn
        assert_eq!(result.stop_reason, StopReason::EndTurn);
    }

    #[test]
    fn convert_response_arguments_as_json_value_not_string() {
        // Some providers send arguments as a JSON object, not a string.
        // Our parser expects a string, so a JSON object should fall through
        // to the empty object default gracefully.
        let resp = serde_json::json!({
            "id": "obj-args",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [{
                        "id": "call-obj",
                        "type": "function",
                        "function": {
                            "name": "tool",
                            "arguments": {"key": "value"}
                        }
                    }]
                },
                "finish_reason": "tool_calls"
            }],
            "model": "test"
        });
        let result = convert_response(resp).unwrap();
        match &result.content[0] {
            ContentBlock::ToolUse { input, .. } => {
                // arguments.as_str() returns None for a JSON object,
                // so it falls through to the empty default
                assert_eq!(*input, serde_json::json!({}));
            }
            _ => panic!("expected ToolUse"),
        }
    }

    // ── Streaming tests ─────────────────────────────────────────────

    struct StreamingMockProvider {
        text_chunks: Vec<String>,
        final_response: serde_json::Value,
    }

    impl StreamingMockProvider {
        fn text_stream(chunks: &[&str]) -> Self {
            let full_text: String = chunks.iter().copied().collect();
            Self {
                text_chunks: chunks.iter().map(|c| c.to_string()).collect(),
                final_response: serde_json::json!({
                    "id": "stream-resp",
                    "choices": [{
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": full_text
                        },
                        "finish_reason": "stop"
                    }],
                    "usage": {
                        "prompt_tokens": 10,
                        "completion_tokens": 5,
                        "total_tokens": 15
                    },
                    "model": "test-model"
                }),
            }
        }
    }

    #[async_trait]
    impl LlmProvider for StreamingMockProvider {
        async fn complete(
            &self,
            _model: &str,
            _messages: &[serde_json::Value],
            _tools: &[serde_json::Value],
            _max_tokens: Option<i32>,
            _temperature: Option<f64>,
        ) -> Result<serde_json::Value, String> {
            Ok(self.final_response.clone())
        }

        async fn complete_stream(
            &self,
            _model: &str,
            _messages: &[serde_json::Value],
            _tools: &[serde_json::Value],
            _max_tokens: Option<i32>,
            _temperature: Option<f64>,
            tx: mpsc::Sender<String>,
        ) -> Result<serde_json::Value, String> {
            for chunk in &self.text_chunks {
                if tx.send(chunk.clone()).await.is_err() {
                    break;
                }
            }
            Ok(self.final_response.clone())
        }
    }

    #[tokio::test]
    async fn streaming_transport_collects_text() {
        let provider = Arc::new(StreamingMockProvider::text_stream(&[
            "Hello", " ", "world", "!",
        ]));
        let transport = OpenAiCompatTransport::with_provider(provider);

        let collected = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let collected_clone = collected.clone();

        let callback: StreamCallback = Box::new(move |text| {
            collected_clone.lock().unwrap().push(text.to_string());
            true
        });

        let response = transport
            .complete_stream(&make_transport_request(), callback)
            .await
            .unwrap();

        let chunks = collected.lock().unwrap().clone();
        assert_eq!(chunks, vec!["Hello", " ", "world", "!"]);
        assert_eq!(response.id, "stream-resp");
    }

    #[tokio::test]
    async fn streaming_transport_callback_abort() {
        let provider = Arc::new(StreamingMockProvider::text_stream(&[
            "Hello", " ", "world", "!",
        ]));
        let transport = OpenAiCompatTransport::with_provider(provider);

        let collected = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let collected_clone = collected.clone();

        // Callback that aborts after receiving 2 chunks
        let callback: StreamCallback = Box::new(move |text| {
            let mut vec = collected_clone.lock().unwrap();
            vec.push(text.to_string());
            vec.len() < 2
        });

        let _response = transport
            .complete_stream(&make_transport_request(), callback)
            .await
            .unwrap();

        let chunks = collected.lock().unwrap().clone();
        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0], "Hello");
        assert_eq!(chunks[1], " ");
    }

    #[tokio::test]
    async fn streaming_fallback_for_non_streaming_provider() {
        // MockProvider does not implement complete_stream (uses default),
        // but the LlmTransport::complete_stream default impl falls back
        // to complete() and sends the full text via callback.
        let provider = Arc::new(MockProvider::text_response("Full response text"));
        let transport = OpenAiCompatTransport::with_provider(provider);

        let collected = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let collected_clone = collected.clone();

        let callback: StreamCallback = Box::new(move |text| {
            collected_clone.lock().unwrap().push(text.to_string());
            true
        });

        // The default complete_stream on LlmTransport calls complete()
        // then fires the callback once with the full text. Since MockProvider
        // does not implement LlmProvider::complete_stream, the
        // OpenAiCompatTransport::complete_stream will use the spawned task
        // which will fail, but we have collected text as fallback.
        // Actually, the MockProvider's default complete_stream returns an error,
        // so the transport should use the fallback path.
        let result = transport
            .complete_stream(&make_transport_request(), callback)
            .await;

        // The LlmProvider default complete_stream returns an error, so the
        // spawned stream task fails. Since no text was collected during
        // streaming, the transport propagates an error. Callers should use
        // complete() directly for providers that do not support streaming.
        assert!(
            result.is_err(),
            "expected error from non-streaming provider, got success"
        );
    }

    #[tokio::test]
    async fn streaming_stub_returns_error() {
        let transport = OpenAiCompatTransport::new();

        let callback: StreamCallback = Box::new(|_| true);

        let result = transport
            .complete_stream(&make_transport_request(), callback)
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("transport not configured"));
    }
}