tinyharness-lib 0.5.6

Core library for TinyHarness: LLM providers, tools, sessions and context management
Documentation
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
1286
1287
use std::collections::HashMap;
use std::time::Duration;

use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio_stream::StreamExt;

use crate::{
    SecretString,
    provider::{
        ChatMessage, ChatMessageResponse, Message, Role, ToolCall, ToolCallFunction, ToolDefinition,
    },
};

/// Default per-request timeout for OpenAI-compatible providers when no
/// explicit value is configured (via `/timeout` or settings).
pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;

/// Shared inner state for OpenAI-compatible providers (llama.cpp, vLLM, etc.).
///
/// Encapsulates the common `{client, base_url, model, api_key}` fields and all
/// shared logic so that provider implementations only need to differ in
/// `list_models()`.
pub struct OpenAiCompatInner {
    client: Client,
    base_url: String,
    model: Option<String>,
    /// Optional bearer token sent as `Authorization: Bearer <key>` on every
    /// request. Used by hosted OpenAI-compatible APIs (e.g. OpenRouter,
    /// Together, self-hosted gateways) that require authentication.
    api_key: Option<SecretString>,
    /// Per-request timeout in seconds, applied to connecting and reading the
    /// HTTP response. The default (30s) covers a slow backend; increase via
    /// `/timeout <secs>` for large-context requests.
    timeout_secs: u64,
    /// Maximum number of attempts for transient failures (connection errors,
    /// timeouts, 5xx responses). 1 = no retries. 4xx responses are never
    /// retried. Backoff between attempts: 1s, 2s, 4s, …
    max_retries: u32,
}

impl OpenAiCompatInner {
    pub fn new(base_url: String) -> Self {
        Self::with_api_key(base_url, None)
    }

    /// Create a new inner state with an optional bearer token.
    pub fn with_api_key(base_url: String, api_key: Option<SecretString>) -> Self {
        Self::with_options(base_url, api_key, DEFAULT_REQUEST_TIMEOUT_SECS, 0)
    }

    /// Create a new inner state with explicit timeout/retry configuration.
    pub fn with_options(
        base_url: String,
        api_key: Option<SecretString>,
        timeout_secs: u64,
        max_retries: u32,
    ) -> Self {
        // Read timeout bounds how long we wait between bytes on an active
        // stream; add slack over the request timeout so long generations
        // that keep producing tokens are never cut off mid-stream.
        let client = Client::builder()
            .connect_timeout(Duration::from_secs(15))
            .read_timeout(Duration::from_secs(timeout_secs + 60))
            .build()
            .unwrap_or_else(|_| Client::new());
        OpenAiCompatInner {
            client,
            base_url,
            model: None,
            api_key,
            timeout_secs,
            max_retries,
        }
    }

    /// Current request timeout in seconds.
    pub fn timeout_secs(&self) -> u64 {
        self.timeout_secs
    }

    /// Current maximum retry count.
    pub fn max_retries(&self) -> u32 {
        self.max_retries
    }

    /// Update the request timeout. Applies to subsequent requests (the HTTP
    /// client's read timeout is rebuilt lazily on the next `chat()`).
    pub fn set_timeout(&mut self, timeout_secs: u64) {
        self.timeout_secs = timeout_secs;
        self.client = Client::builder()
            .connect_timeout(Duration::from_secs(15))
            .read_timeout(Duration::from_secs(timeout_secs + 60))
            .build()
            .unwrap_or_else(|_| Client::new());
    }

    /// Update the maximum retry count. Applies to subsequent requests.
    pub fn set_retries(&mut self, max_retries: u32) {
        self.max_retries = max_retries;
    }

    /// Perform a health check against the server's `/health` endpoint.
    ///
    /// Servers that don't expose `/health` answer with HTTP 404 (llama.cpp,
    /// many gateways and proxies). In that case we fall back to
    /// `/v1/models`: a reachable endpoint returning a non-empty model list
    /// proves the backend is up and usable, so it counts as a successful
    /// health check. An empty list — or a failing `/v1/models` request — is
    /// reported as a failure, since it tells us nothing about the server.
    ///
    /// Any other `/health` status (5xx, 401, …) is reported directly and is
    /// never masked by the fallback: the endpoint exists, it is unhappy.
    pub async fn health_check(&self) -> Result<(), String> {
        let url = format!("{}/health", self.base_url.trim_end_matches('/'));
        let mut req = self.client.get(&url);
        if let Some(key) = &self.api_key {
            req = req.bearer_auth(key.expose_secret());
        }
        match req.send().await {
            Ok(resp) if resp.status().is_success() => Ok(()),
            // A 404 usually means the server simply has no /health
            // endpoint. Don't dump its response body (often a large HTML
            // or JSON error page) into the warning — probe /v1/models
            // instead.
            Ok(resp) if resp.status() == reqwest::StatusCode::NOT_FOUND => {
                match self.fetch_models_raw().await {
                    Ok(models) if !models.is_empty() => Ok(()),
                    Ok(_) => Err(
                        "Server has no /health endpoint and /v1/models returned an empty list"
                            .to_string(),
                    ),
                    Err(e) => Err(format!(
                        "Server has no /health endpoint and /v1/models failed: {e}"
                    )),
                }
            }
            Ok(resp) => Err(format!(
                "Server returned {}: {}",
                resp.status().as_u16(),
                resp.text().await.unwrap_or_default()
            )),
            Err(e) => Err(format!("Cannot reach {}: {}", url, e)),
        }
    }

    pub fn select_model(&mut self, name: String) {
        self.model = Some(name);
    }

    pub fn current_model(&self) -> Option<String> {
        self.model.clone()
    }

    /// Return the `/v1/chat/completions` URL for this server.
    pub fn chat_url(&self) -> String {
        format!(
            "{}/v1/chat/completions",
            self.base_url.trim_end_matches('/').trim_end_matches("/v1")
        )
    }

    /// Return the `/v1/models` URL for this server.
    pub fn models_url(&self) -> String {
        format!(
            "{}/v1/models",
            self.base_url.trim_end_matches('/').trim_end_matches("/v1")
        )
    }

    /// Fetch the model list from `/v1/models`, propagating failures.
    ///
    /// Unlike [`Self::fetch_model_list`], this distinguishes "the server
    /// answered with an empty list" (`Ok(vec![])`) from "the request could
    /// not be completed" (`Err`), which callers such as the health check
    /// need in order to interpret the result.
    pub async fn fetch_models_raw(&self) -> Result<Vec<String>, String> {
        let url = self.models_url();
        let mut req = self.client.get(&url);
        if let Some(key) = &self.api_key {
            req = req.bearer_auth(key.expose_secret());
        }
        let resp = match req.send().await {
            Ok(resp) => resp,
            Err(e) => return Err(format!("cannot reach {url}: {e}")),
        };
        if !resp.status().is_success() {
            return Err(format!("server returned {}", resp.status().as_u16()));
        }
        match resp.json::<ModelListResponse>().await {
            Ok(list) => Ok(list.data.into_iter().map(|m| m.id).collect()),
            Err(e) => Err(format!("invalid model list response: {e}")),
        }
    }

    /// Fetch the model list from the server's `/v1/models` endpoint.
    /// Returns the list of model IDs, or an empty vec on failure.
    pub async fn fetch_model_list(&self) -> Vec<String> {
        match self.fetch_models_raw().await {
            Ok(models) => models,
            Err(_) => self.model.clone().into_iter().collect(),
        }
    }

    /// Stream chat completions using the OpenAI-compatible API.
    /// Returns a receiver for streaming response chunks, or an error string
    /// if the request cannot be started.
    pub async fn chat(
        &self,
        messages: Vec<Message>,
        tools: Vec<ToolDefinition>,
    ) -> Result<tokio::sync::mpsc::Receiver<ChatMessageResponse>, String> {
        let (send, recv) =
            tokio::sync::mpsc::channel::<ChatMessageResponse>(super::STREAM_CHANNEL_CAPACITY);

        let model = self.model.clone().unwrap_or_default();
        let openai_messages = messages.into_iter().map(to_openai_message).collect();
        let openai_tools = tools.into_iter().map(to_openai_tool).collect();
        let client = self.client.clone();
        let chat_url = self.chat_url();
        let api_key = self.api_key.clone();
        let timeout_secs = self.timeout_secs;
        let max_retries = self.max_retries;

        let body = ChatRequest {
            model,
            messages: openai_messages,
            stream: true,
            stream_options: Some(StreamOptions {
                include_usage: true,
            }),
            tools: openai_tools,
        };

        // Spawn the streaming work on a background task
        tokio::spawn(async move {
            let _usage = chat_with_retries(
                &client,
                &chat_url,
                &body,
                api_key.as_ref(),
                timeout_secs,
                max_retries,
                &send,
            )
            .await;
        });

        Ok(recv)
    }
}

/// Send the chat request with retry + exponential backoff for transient
/// failures, then stream the response chunks through `send`.
///
/// Retryable failures: connection errors, request timeouts (when the whole
/// attempt is cut off before any output), and 5xx / 429 responses. Once a
/// terminal chunk has reached the receiver (success, mid-stream error, or a
/// 4xx error), the outcome is final — retrying would duplicate output.
///
/// Backoff between attempts: 1s, 2s, 4s, … Returns the token usage when a
/// final attempt succeeds.
async fn chat_with_retries(
    client: &reqwest::Client,
    url: &str,
    body: &ChatRequest,
    api_key: Option<&SecretString>,
    timeout_secs: u64,
    max_retries: u32,
    send: &tokio::sync::mpsc::Sender<ChatMessageResponse>,
) -> Option<crate::provider::TokenUsage> {
    let max_attempts = max_retries.max(1);

    for attempt in 1..=max_attempts {
        let result = tokio::time::timeout(
            Duration::from_secs(timeout_secs),
            stream_chat_completions(client, url, body, api_key, send),
        )
        .await;

        match result {
            // The attempt produced a terminal chunk (success or surfaced
            // error) — the receiver already has the outcome, don't retry.
            Ok(AttemptOutcome::Final(usage)) => return usage,
            // The attempt failed before delivering anything.
            Ok(AttemptOutcome::Retryable(e)) => {
                if attempt >= max_attempts {
                    send_error_chunk(send, &format!("Error after {attempt} attempt(s): {e}")).await;
                    return None;
                }
            }
            // The whole attempt timed out before completing.
            Err(_) => {
                if attempt >= max_attempts {
                    send_error_chunk(
                        send,
                        &format!(
                            "Error: Request timed out after {timeout_secs}s ({attempt} attempt(s))"
                        ),
                    )
                    .await;
                    return None;
                }
            }
        }

        // Exponential backoff: 1s, 2s, 4s, ...
        let backoff = Duration::from_secs(1 << (attempt - 1));
        tokio::time::sleep(backoff).await;
    }

    None
}

// ── OpenAI-compatible request/response types ──

#[derive(Serialize)]
pub struct ChatRequest {
    pub model: String,
    pub messages: Vec<OpenAIMessage>,
    pub stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<StreamOptions>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<OpenAITool>,
}

#[derive(Serialize)]
pub struct StreamOptions {
    pub include_usage: bool,
}

#[derive(Serialize)]
pub struct OpenAIMessage {
    pub role: String,
    pub content: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<OpenAIToolCall>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
}

#[derive(Serialize)]
pub struct OpenAITool {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: OpenAIToolFunction,
}

#[derive(Serialize)]
pub struct OpenAIToolFunction {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct OpenAIToolCall {
    #[serde(default)]
    pub index: usize,
    #[serde(default)]
    pub id: String,
    #[serde(rename = "type", default)]
    pub call_type: String,
    #[serde(default)]
    pub function: OpenAIToolCallFunction,
}

#[derive(Serialize, Deserialize, Clone, Default)]
pub struct OpenAIToolCallFunction {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub arguments: String,
}

#[derive(Deserialize)]
pub struct ChunkChoice {
    pub delta: Delta,
    #[serde(default, rename = "finish_reason")]
    pub _finish_reason: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct Delta {
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default)]
    pub tool_calls: Option<Vec<OpenAIToolCall>>,
    /// Reasoning text — OpenRouter / DeepSeek spelling.
    #[serde(default)]
    pub reasoning: Option<String>,
    /// Reasoning text — vLLM / Qwen `--reasoning-parser` spelling.
    #[serde(default)]
    pub reasoning_content: Option<String>,
    /// Structured reasoning parts (OpenRouter): the portable representation
    /// used for providers whose reasoning is signed or encrypted.
    #[serde(default)]
    pub reasoning_details: Option<Vec<ReasoningDetail>>,
}

/// One item of an OpenAI-compatible `delta.reasoning_details` array.
///
/// Only the displayable shapes are modelled: `text` / `reasoning_text` items
/// carry their content in `text`, Anthropic-style `summary` items carry an
/// array of `{ "text": … }` parts. `encrypted` / `redacted_reasoning` items
/// have no readable payload, so they contribute nothing to the display.
#[derive(Deserialize, Clone, Debug, Default)]
pub struct ReasoningDetail {
    #[serde(default)]
    pub text: Option<String>,
    #[serde(default)]
    pub summary: Option<serde_json::Value>,
}

impl ReasoningDetail {
    /// The human-readable text carried by this reasoning part (may be empty).
    fn display_text(&self) -> String {
        let mut out = String::new();
        if let Some(text) = &self.text {
            out.push_str(text);
        }
        if let Some(summary) = &self.summary {
            match summary {
                serde_json::Value::String(s) => out.push_str(s),
                serde_json::Value::Array(parts) => {
                    for part in parts {
                        if let Some(s) = part.get("text").and_then(|t| t.as_str()) {
                            out.push_str(s);
                        }
                    }
                }
                _ => {}
            }
        }
        out
    }
}

/// Extract the displayable reasoning chain from a streaming delta.
///
/// Servers disagree on how reasoning is spelled (`reasoning`,
/// `reasoning_content`, or the structured `reasoning_details` array), so all
/// shapes collapse into a single string. The plain fields win when present —
/// OpenRouter emits both the text and its structured form, and concatenating
/// them would duplicate the chain. Returns `None` when the delta carries no
/// reasoning at all.
fn delta_reasoning(delta: &Delta) -> Option<String> {
    let mut out = String::new();
    for text in [&delta.reasoning, &delta.reasoning_content]
        .into_iter()
        .flatten()
    {
        out.push_str(text);
    }
    if out.is_empty()
        && let Some(details) = &delta.reasoning_details
    {
        for detail in details {
            out.push_str(&detail.display_text());
        }
    }
    if out.is_empty() { None } else { Some(out) }
}

#[derive(Deserialize)]
pub struct StreamChunk {
    #[serde(default)]
    pub choices: Vec<ChunkChoice>,
    #[serde(default)]
    pub usage: Option<OpenAIUsage>,
}

#[derive(Deserialize, Clone)]
pub struct OpenAIUsage {
    #[serde(default)]
    pub prompt_tokens: u32,
    #[serde(default)]
    pub completion_tokens: u32,
    #[serde(default)]
    pub total_tokens: u32,
}

// ── Model list response types ──

#[derive(Deserialize)]
pub struct ModelListResponse {
    pub data: Vec<ModelEntry>,
}

#[derive(Deserialize)]
pub struct ModelEntry {
    pub id: String,
}

// ── Conversion helpers ──

pub fn to_openai_message(msg: Message) -> OpenAIMessage {
    /// Build the content value: if images are present, use multipart array format;
    /// otherwise use plain string.
    fn build_content(msg: &Message) -> serde_json::Value {
        if msg.images.is_empty() {
            serde_json::Value::String(msg.content.clone())
        } else {
            let mut parts: Vec<serde_json::Value> = Vec::new();
            // Add text part
            if !msg.content.is_empty() {
                parts.push(serde_json::json!({
                    "type": "text",
                    "text": msg.content
                }));
            }
            // Add image parts
            for img in &msg.images {
                parts.push(serde_json::json!({
                    "type": "image_url",
                    "image_url": {
                        "url": img.data_uri()
                    }
                }));
            }
            serde_json::Value::Array(parts)
        }
    }

    match msg.role {
        Role::System => OpenAIMessage {
            role: "system".to_string(),
            content: serde_json::Value::String(msg.content),
            tool_calls: None,
            tool_call_id: None,
        },
        Role::User => OpenAIMessage {
            role: "user".to_string(),
            content: build_content(&msg),
            tool_calls: None,
            tool_call_id: None,
        },
        Role::Assistant => {
            if msg.tool_calls.is_empty() {
                OpenAIMessage {
                    role: "assistant".to_string(),
                    content: serde_json::Value::String(msg.content),
                    tool_calls: None,
                    tool_call_id: None,
                }
            } else {
                let tool_calls: Vec<OpenAIToolCall> = msg
                    .tool_calls
                    .into_iter()
                    .enumerate()
                    .map(|(i, tc)| {
                        // Synthesize a stable id when the upstream provider
                        // didn't return one (some local / non-OpenAI servers
                        // omit it). OpenAI requires a non-empty id.
                        let id = tc
                            .id
                            .filter(|s| !s.is_empty())
                            .unwrap_or_else(|| format!("call_{}", i));
                        let args_str = if tc.function.arguments.is_null() {
                            "{}".to_string()
                        } else {
                            tc.function.arguments.to_string()
                        };
                        OpenAIToolCall {
                            index: i,
                            id,
                            call_type: "function".to_string(),
                            function: OpenAIToolCallFunction {
                                name: tc.function.name,
                                arguments: args_str,
                            },
                        }
                    })
                    .collect();
                OpenAIMessage {
                    role: "assistant".to_string(),
                    // MiniMax and some other strict providers reject empty
                    // strings in assistant messages that contain only tool
                    // calls.  Send `null` when there is no text content.
                    content: if msg.content.is_empty() {
                        serde_json::Value::Null
                    } else {
                        serde_json::Value::String(msg.content)
                    },
                    tool_calls: Some(tool_calls),
                    tool_call_id: None,
                }
            }
        }
        Role::Tool => {
            // tool_call_id should have been set by the agent loop. If somehow
            // missing, skip the field rather than emitting a bogus id that the
            // server will reject.
            let tool_call_id = msg.tool_call_id.filter(|s| !s.is_empty());
            OpenAIMessage {
                role: "tool".to_string(),
                content: serde_json::Value::String(msg.content),
                tool_calls: None,
                tool_call_id,
            }
        }
    }
}

pub fn to_openai_tool(ti: ToolDefinition) -> OpenAITool {
    OpenAITool {
        tool_type: "function".to_string(),
        function: OpenAIToolFunction {
            name: ti.name,
            description: ti.description,
            parameters: serde_json::to_value(ti.parameters).unwrap_or_default(),
        },
    }
}

/// Outcome of a single streaming attempt.
///
/// `Retryable` failures happen before anything was delivered to the
/// receiver, so the attempt can be repeated cleanly. `Final` outcomes
/// already produced a terminal chunk on the channel (success or an error
/// the receiver has seen), so retrying would duplicate output.
enum AttemptOutcome {
    /// Nothing was sent to the receiver — safe to retry.
    Retryable(String),
    /// A final chunk (success or error) was already sent.
    Final(Option<crate::provider::TokenUsage>),
}

/// Determine whether an HTTP status code should be retried.
///
/// 5xx responses (server-side trouble) and 429 (rate limit) are transient;
/// other 4xx errors indicate a request problem that retrying won't fix.
fn is_retryable_status(status: reqwest::StatusCode) -> bool {
    status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS
}

/// Stream chat completions from an OpenAI-compatible endpoint.
///
/// Returns `AttemptOutcome::Retryable` when the request failed before any
/// chunk reached the receiver (connection error, non-retryable status
/// surfaced via `Err`); returns `AttemptOutcome::Final` once a terminal
/// chunk (success or surfaced error) has been delivered.
///
/// If `api_key` is `Some`, the request includes an
/// `Authorization: Bearer <key>` header.
async fn stream_chat_completions(
    client: &reqwest::Client,
    url: &str,
    body: &ChatRequest,
    api_key: Option<&SecretString>,
    send: &tokio::sync::mpsc::Sender<ChatMessageResponse>,
) -> AttemptOutcome {
    let mut request = client.post(url).json(body);
    if let Some(key) = api_key {
        request = request.bearer_auth(key.expose_secret());
    }
    let response = match request.send().await {
        Ok(r) => r,
        Err(e) => return AttemptOutcome::Retryable(format!("Error: {}", e)),
    };

    // If the server returned a non-success status, surface the body as an
    // error instead of feeding it into the SSE parser (which would silently
    // drop it). Server-side (5xx) and rate-limit (429) failures are retried
    // by the caller; client errors (4xx) are surfaced immediately.
    let status = response.status();
    if !status.is_success() {
        let body = response.text().await.unwrap_or_default();
        let msg = format!("Error: HTTP {} — {}", status.as_u16(), body);
        if is_retryable_status(status) {
            return AttemptOutcome::Retryable(msg);
        }
        send_error_chunk(send, &msg).await;
        return AttemptOutcome::Final(None);
    }

    let mut stream = response.bytes_stream();
    let mut buf = String::new();

    let mut acc_tool_calls: HashMap<usize, OpenAIToolCall> = HashMap::new();
    let mut response_content = String::new();
    let mut response_thinking = String::new();
    let mut token_usage: Option<crate::provider::TokenUsage> = None;

    while let Some(chunk_result) = stream.next().await {
        let chunk = match chunk_result {
            Ok(c) => c,
            Err(e) => {
                // Stream read error — surface it rather than silently breaking.
                // This is final: partial output may already have been delivered.
                send_error_chunk(send, &format!("\n\nStream error: {}", e)).await;
                return AttemptOutcome::Final(token_usage);
            }
        };

        buf.push_str(&String::from_utf8_lossy(&chunk));

        loop {
            match buf.find('\n') {
                None => break,
                Some(pos) => {
                    let line = buf[..pos].trim().to_string();
                    buf = buf[pos + 1..].to_string();

                    if line.is_empty() || line == "data: [DONE]" {
                        continue;
                    }

                    if let Some(data) = line.strip_prefix("data: ")
                        && let Ok(chunk) = serde_json::from_str::<StreamChunk>(data)
                    {
                        // Capture token usage if present (usually in the final chunk)
                        if let Some(usage) = &chunk.usage {
                            token_usage = Some(crate::provider::TokenUsage {
                                prompt_tokens: usage.prompt_tokens,
                                completion_tokens: usage.completion_tokens,
                                total_tokens: usage.total_tokens,
                            });
                        }

                        for choice in chunk.choices {
                            if let Some(content) = &choice.delta.content {
                                response_content.push_str(content);
                            }

                            // Reasoning deltas arrive before (and sometimes
                            // interleaved with) the visible content; keep them
                            // in their own buffer so the UI can render the
                            // `[thinking]` stream separately.
                            if let Some(reasoning) = delta_reasoning(&choice.delta) {
                                response_thinking.push_str(&reasoning);
                            }

                            if let Some(tool_calls) = &choice.delta.tool_calls {
                                for tc in tool_calls {
                                    let entry =
                                        acc_tool_calls.entry(tc.index).or_insert(OpenAIToolCall {
                                            index: tc.index,
                                            id: String::new(),
                                            call_type: "function".to_string(),
                                            function: OpenAIToolCallFunction::default(),
                                        });

                                    if !tc.id.is_empty() {
                                        entry.id = tc.id.clone();
                                    }
                                    if !tc.function.name.is_empty() {
                                        entry.function.name = tc.function.name.clone();
                                    }
                                    entry.function.arguments.push_str(&tc.function.arguments);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Flush whichever buffer has data — a chunk may carry only reasoning
        // (models that think before they answer) or only content.
        if !response_thinking.is_empty() {
            let thinking = std::mem::take(&mut response_thinking);
            if send
                .send(ChatMessageResponse {
                    message: ChatMessage {
                        content: String::new(),
                        tool_calls: vec![],
                        thinking: Some(thinking),
                    },
                    done: false,
                    is_error: false,
                    usage: None,
                })
                .await
                .is_err()
            {
                return AttemptOutcome::Final(token_usage);
            }
        }

        if !response_content.is_empty() {
            // If the receiver is gone (user interrupt, shutdown), stop
            // reading the HTTP stream instead of draining the rest of it.
            if send
                .send(ChatMessageResponse {
                    message: ChatMessage {
                        content: response_content.clone(),
                        tool_calls: vec![],
                        thinking: None,
                    },
                    done: false,
                    is_error: false,
                    usage: None,
                })
                .await
                .is_err()
            {
                return AttemptOutcome::Final(token_usage);
            }
            response_content.clear();
        }
    }

    // Reasoning can still be buffered when the server closes the stream
    // without another content/usage chunk — flush it so the tail is not lost.
    if !response_thinking.is_empty() {
        let thinking = std::mem::take(&mut response_thinking);
        if send
            .send(ChatMessageResponse {
                message: ChatMessage {
                    content: String::new(),
                    tool_calls: vec![],
                    thinking: Some(thinking),
                },
                done: false,
                is_error: false,
                usage: None,
            })
            .await
            .is_err()
        {
            return AttemptOutcome::Final(token_usage);
        }
    }

    let tool_calls: Vec<ToolCall> = if !acc_tool_calls.is_empty() {
        acc_tool_calls
            .into_values()
            .map(|tc| {
                let args: serde_json::Value =
                    serde_json::from_str(&tc.function.arguments).unwrap_or(serde_json::Value::Null);
                ToolCall {
                    id: if tc.id.is_empty() { None } else { Some(tc.id) },
                    function: ToolCallFunction {
                        name: tc.function.name,
                        arguments: args,
                        thought_signature: None,
                    },
                }
            })
            .collect()
    } else {
        vec![]
    };

    // Send the final response with tool calls and token usage
    let _ = send
        .send(ChatMessageResponse {
            message: ChatMessage {
                content: String::new(),
                tool_calls,
                thinking: None,
            },
            done: true,
            is_error: false,
            usage: token_usage.clone(),
        })
        .await;

    AttemptOutcome::Final(token_usage)
}

/// Send a terminal error chunk (done: true, is_error: true) to the receiver.
async fn send_error_chunk(send: &tokio::sync::mpsc::Sender<ChatMessageResponse>, message: &str) {
    let _ = send
        .send(ChatMessageResponse {
            message: ChatMessage {
                content: message.to_string(),
                tool_calls: vec![],
                thinking: None,
            },
            done: true,
            is_error: true,
            usage: None,
        })
        .await;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// Reason phrase for the canned status lines used by the mock server.
    fn reason_phrase(status: u16) -> &'static str {
        match status {
            200 => "OK",
            404 => "Not Found",
            401 => "Unauthorized",
            500 => "Internal Server Error",
            503 => "Service Unavailable",
            _ => "Status",
        }
    }

    /// Spawn a minimal HTTP server answering fixed paths, logging every
    /// requested path in order. Unknown paths get a 404.
    ///
    /// Returns `(base_url, request_log, server_handle)`.
    async fn spawn_mock_server(
        routes: Vec<(&'static str, u16, &'static str)>,
    ) -> (String, Arc<Mutex<Vec<String>>>, tokio::task::JoinHandle<()>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("mock server bind");
        let addr = listener.local_addr().expect("mock server addr");
        let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![]));
        let routes = Arc::new(routes);
        let log_in = Arc::clone(&log);

        let handle = tokio::spawn(async move {
            while let Ok((mut stream, _)) = listener.accept().await {
                let routes = Arc::clone(&routes);
                let log = Arc::clone(&log_in);
                tokio::spawn(async move {
                    let mut buf = [0u8; 4096];
                    let n = match stream.read(&mut buf).await {
                        Ok(0) | Err(_) => return,
                        Ok(n) => n,
                    };
                    let head = String::from_utf8_lossy(&buf[..n]);
                    let path = head
                        .split_whitespace()
                        .nth(1)
                        .unwrap_or_default()
                        .to_string();
                    log.lock().unwrap().push(path.clone());

                    let (status, body) = routes
                        .iter()
                        .find(|(p, _, _)| *p == path)
                        .map(|(_, s, b)| (*s, *b))
                        .unwrap_or((404, "{\"error\":\"not found\"}"));
                    let resp = format!(
                        "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\n\
                         content-length: {len}\r\nconnection: close\r\n\r\n{body}",
                        reason = reason_phrase(status),
                        len = body.len(),
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                    let _ = stream.shutdown().await;
                });
            }
        });

        (format!("http://{addr}"), log, handle)
    }

    /// 5xx and 429 are transient and should be retried.
    #[test]
    fn retryable_status_codes() {
        assert!(is_retryable_status(reqwest::StatusCode::BAD_GATEWAY));
        assert!(is_retryable_status(
            reqwest::StatusCode::SERVICE_UNAVAILABLE
        ));
        assert!(is_retryable_status(
            reqwest::StatusCode::INTERNAL_SERVER_ERROR
        ));
        assert!(is_retryable_status(reqwest::StatusCode::TOO_MANY_REQUESTS));
    }

    /// 4xx responses (other than 429) mean the request itself is wrong —
    /// retrying won't help, so they must not be retried.
    #[test]
    fn non_retryable_status_codes() {
        assert!(!is_retryable_status(reqwest::StatusCode::UNAUTHORIZED));
        assert!(!is_retryable_status(reqwest::StatusCode::NOT_FOUND));
        assert!(!is_retryable_status(reqwest::StatusCode::BAD_REQUEST));
        assert!(!is_retryable_status(
            reqwest::StatusCode::UNPROCESSABLE_ENTITY
        ));
    }

    /// Defaults for fresh inner state: 30s timeout, no retries (matches the
    /// pre-change hardcoded behaviour for retries and read-timeout headroom).
    #[test]
    fn defaults_timeout_and_retries() {
        let inner = OpenAiCompatInner::new("http://localhost:8080".to_string());
        assert_eq!(inner.timeout_secs(), 30);
        assert_eq!(inner.max_retries(), 0);
    }

    /// Explicit options constructor stores timeout and retries.
    #[test]
    fn with_options_stores_configuration() {
        let inner =
            OpenAiCompatInner::with_options("http://localhost:8080".to_string(), None, 120, 5);
        assert_eq!(inner.timeout_secs(), 120);
        assert_eq!(inner.max_retries(), 5);
    }

    /// set_timeout rebuilds the HTTP client and updates the stored value.
    #[test]
    fn set_timeout_updates_value() {
        let mut inner = OpenAiCompatInner::new("http://localhost:8080".to_string());
        inner.set_timeout(60);
        assert_eq!(inner.timeout_secs(), 60);
    }

    /// set_retries updates the stored value.
    #[test]
    fn set_retries_updates_value() {
        let mut inner = OpenAiCompatInner::new("http://localhost:8080".to_string());
        inner.set_retries(7);
        assert_eq!(inner.max_retries(), 7);
    }

    /// `models_url` strips a trailing `/v1` so both `http://host` and
    /// `http://host/v1` resolve to `http://host/v1/models`.
    #[test]
    fn models_url_normalises_trailing_v1() {
        let plain = OpenAiCompatInner::new("http://example.test:1234".to_string());
        assert_eq!(plain.models_url(), "http://example.test:1234/v1/models");
        let with_v1 = OpenAiCompatInner::new("http://example.test:1234/v1".to_string());
        assert_eq!(with_v1.models_url(), "http://example.test:1234/v1/models");
    }

    /// A working `/health` endpoint short-circuits the check — `/v1/models`
    /// is never queried.
    #[tokio::test]
    async fn health_check_uses_health_endpoint_when_present() {
        let (base, log, _server) =
            spawn_mock_server(vec![("/health", 200, "{\"status\":\"ok\"}")]).await;
        let inner = OpenAiCompatInner::new(base);

        assert!(inner.health_check().await.is_ok());
        assert_eq!(log.lock().unwrap().as_slice(), ["/health".to_string()]);
    }

    /// No `/health` endpoint (404) but a non-empty `/v1/models` list counts
    /// as a successful health check.
    #[tokio::test]
    async fn health_check_falls_back_to_models_endpoint() {
        let (base, log, _server) = spawn_mock_server(vec![(
            "/v1/models",
            200,
            "{\"data\":[{\"id\":\"gpt-4o-mini\"}]}",
        )])
        .await;
        let inner = OpenAiCompatInner::new(base);

        assert!(inner.health_check().await.is_ok());
        assert_eq!(
            log.lock().unwrap().as_slice(),
            ["/health".to_string(), "/v1/models".to_string()]
        );
    }

    /// An empty model list proves nothing, so the fallback fails with a
    /// message mentioning both endpoints.
    #[tokio::test]
    async fn health_check_fallback_rejects_empty_model_list() {
        let (base, _log, _server) =
            spawn_mock_server(vec![("/v1/models", 200, "{\"data\":[]}")]).await;
        let inner = OpenAiCompatInner::new(base);

        let err = inner.health_check().await.expect_err("should fail");
        assert!(err.contains("/health"), "unexpected error: {err}");
        assert!(err.contains("empty list"), "unexpected error: {err}");
    }

    /// A `/v1/models` endpoint that errors out also fails the health check.
    #[tokio::test]
    async fn health_check_fallback_reports_models_failure() {
        let (base, _log, _server) =
            spawn_mock_server(vec![("/v1/models", 500, "{\"error\":\"boom\"}")]).await;
        let inner = OpenAiCompatInner::new(base);

        let err = inner.health_check().await.expect_err("should fail");
        assert!(err.contains("/health"), "unexpected error: {err}");
        assert!(err.contains("500"), "unexpected error: {err}");
    }

    /// Non-404 `/health` responses are reported as-is — the fallback must
    /// not mask a health endpoint that exists but is unhappy.
    #[tokio::test]
    async fn health_check_does_not_mask_non_404_errors() {
        let (base, log, _server) =
            spawn_mock_server(vec![("/health", 503, "{\"status\":\"unhealthy\"}")]).await;
        let inner = OpenAiCompatInner::new(base);

        let err = inner.health_check().await.expect_err("should fail");
        assert!(err.contains("503"), "unexpected error: {err}");
        assert_eq!(log.lock().unwrap().as_slice(), ["/health".to_string()]);
    }

    /// `fetch_models_raw` propagates errors instead of silently returning
    /// the currently selected model.
    #[tokio::test]
    async fn fetch_models_raw_propagates_errors() {
        let (base, _log, _server) = spawn_mock_server(vec![]).await;
        let inner = OpenAiCompatInner::new(base);
        assert!(inner.fetch_models_raw().await.is_err());

        let (base, _log, _server) = spawn_mock_server(vec![(
            "/v1/models",
            200,
            "{\"data\":[{\"id\":\"alpha\"},{\"id\":\"beta\"}]}",
        )])
        .await;
        let inner = OpenAiCompatInner::new(base);
        assert_eq!(
            inner.fetch_models_raw().await.expect("ok"),
            vec!["alpha".to_string(), "beta".to_string()]
        );
    }

    /// `fetch_model_list` keeps its lenient contract: on failure it falls
    /// back to the currently selected model.
    #[tokio::test]
    async fn fetch_model_list_falls_back_to_selected_model() {
        let (base, _log, _server) = spawn_mock_server(vec![]).await;
        let mut inner = OpenAiCompatInner::new(base);
        inner.select_model("chosen-model".to_string());

        assert_eq!(
            inner.fetch_model_list().await,
            vec!["chosen-model".to_string()]
        );
    }

    // ── reasoning / thinking extraction ──

    /// Parse a single SSE `data:` payload into a `StreamChunk`.
    fn parse_chunk(json: &str) -> StreamChunk {
        serde_json::from_str(json).unwrap_or_else(|e| panic!("invalid chunk {json}: {e}"))
    }

    /// Pull the reasoning out of the first choice of a chunk.
    fn reasoning_of(json: &str) -> Option<String> {
        let chunk = parse_chunk(json);
        chunk
            .choices
            .first()
            .and_then(|c| delta_reasoning(&c.delta))
    }

    /// OpenRouter / DeepSeek spell the field `reasoning`.
    #[test]
    fn delta_reasoning_reads_openrouter_field() {
        assert_eq!(
            reasoning_of(r#"{"choices":[{"delta":{"reasoning":"hmm"}}]}"#).as_deref(),
            Some("hmm")
        );
    }

    /// vLLM / Qwen reasoning parsers emit `reasoning_content`.
    #[test]
    fn delta_reasoning_reads_vllm_field() {
        assert_eq!(
            reasoning_of(r#"{"choices":[{"delta":{"reasoning_content":"hmm"}}]}"#).as_deref(),
            Some("hmm")
        );
    }

    /// OpenRouter's structured `reasoning_details` array is the fallback when
    /// no plain-text field is present.
    #[test]
    fn delta_reasoning_reads_structured_details() {
        assert_eq!(
            reasoning_of(
                r#"{"choices":[{"delta":{"reasoning_details":[{"type":"text","text":"a"},{"type":"text","text":"b"}]}}]}"#
            )
            .as_deref(),
            Some("ab")
        );
    }

    /// Anthropic-style summary parts nest their text in a `summary` array.
    #[test]
    fn delta_reasoning_reads_summary_parts() {
        assert_eq!(
            reasoning_of(
                r#"{"choices":[{"delta":{"reasoning_details":[{"type":"summary_text","summary":[{"text":"x"}]}]}}]}"#
            )
            .as_deref(),
            Some("x")
        );
    }

    /// Encrypted / redacted reasoning has no readable payload — it must not
    /// produce an empty `Some("")` that would trip the UI into printing a
    /// bare `[thinking]` header.
    #[test]
    fn delta_reasoning_ignores_opaque_details() {
        assert_eq!(
            reasoning_of(
                r#"{"choices":[{"delta":{"reasoning_details":[{"type":"reasoning.encrypted","data":"gAAAAA"}]}}]}"#
            ),
            None
        );
    }

    /// When both spellings are present (OpenRouter does this), the plain
    /// field wins so the chain is not duplicated.
    #[test]
    fn delta_reasoning_does_not_duplicate_plain_and_structured() {
        assert_eq!(
            reasoning_of(
                r#"{"choices":[{"delta":{"reasoning":"same","reasoning_details":[{"type":"text","text":"same"}]}}]}"#
            )
            .as_deref(),
            Some("same")
        );
    }

    /// A content-only delta carries no reasoning.
    #[test]
    fn delta_reasoning_is_none_without_reasoning_fields() {
        assert_eq!(
            reasoning_of(r#"{"choices":[{"delta":{"content":"hello"}}]}"#),
            None
        );
    }

    /// SSE body serving a reasoning stream: thinking deltas, then content,
    /// then a usage-only final chunk.
    const REASONING_SSE: &str = concat!(
        "data: {\"choices\":[{\"delta\":{\"reasoning\":\"think \"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"reasoning\":\"more\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2,\"total_tokens\":3}}\n\n",
        "data: [DONE]\n\n",
    );

    /// End-to-end: reasoning deltas reach the consumer through
    /// `ChatMessage::thinking`, and content is not mixed in with them.
    #[tokio::test]
    async fn stream_forwards_reasoning_as_thinking_chunks() {
        let (base, _log, _server) =
            spawn_mock_server(vec![("/v1/chat/completions", 200, REASONING_SSE)]).await;
        let mut inner = OpenAiCompatInner::new(base);
        inner.select_model("test-model".to_string());

        let mut recv = inner
            .chat(vec![Message::simple(Role::User, "hi")], vec![])
            .await
            .expect("chat started");

        let mut thinking = String::new();
        let mut content = String::new();
        let mut done = false;
        while let Some(resp) = recv.recv().await {
            if let Some(t) = &resp.message.thinking {
                thinking.push_str(t);
            }
            content.push_str(&resp.message.content);
            if resp.done {
                done = true;
                break;
            }
        }
        assert!(done, "stream should terminate with a done chunk");
        assert_eq!(thinking, "think more");
        assert_eq!(content, "Hello");
    }

    /// A server that never emits reasoning keeps `thinking` unset, so the UI
    /// skips the `[thinking]` block entirely.
    #[tokio::test]
    async fn stream_without_reasoning_leaves_thinking_unset() {
        let (base, _log, _server) = spawn_mock_server(vec![(
            "/v1/chat/completions",
            200,
            "data: {\"choices\":[{\"delta\":{\"content\":\"plain\"}}]}\n\ndata: [DONE]\n\n",
        )])
        .await;
        let mut inner = OpenAiCompatInner::new(base);
        inner.select_model("test-model".to_string());

        let mut recv = inner
            .chat(vec![Message::simple(Role::User, "hi")], vec![])
            .await
            .expect("chat started");

        while let Some(resp) = recv.recv().await {
            assert!(resp.message.thinking.is_none());
            if resp.done {
                break;
            }
        }
    }
}