forked from Hmbown/Codewhale
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
1908 lines (1698 loc) · 64.6 KB
/
Copy pathmod.rs
File metadata and controls
1908 lines (1698 loc) · 64.6 KB
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
//! LLM Client Trait and Retry Logic
//!
//! This module provides a unified interface for LLM providers with robust retry logic,
//! exponential backoff, and proper error classification.
//!
//! # Architecture
//!
//! - `LlmClient` trait: Async interface for LLM providers (DeepSeek, `OpenAI`, etc.)
//! - `RetryConfig`: Configurable retry behavior with exponential backoff and jitter
//! - `LlmError`: Classified errors with retryability information
//! - `with_retry`: Generic retry wrapper for any async operation
//!
//! # Example
//!
//! ```ignore
//! use crate::llm_client::{LlmClient, RetryConfig, with_retry};
//!
//! let config = RetryConfig::default();
//! let result = with_retry(&config, || async {
//! client.create_message(request).await
//! }, None).await;
//! ```
use crate::config::RetryPolicy;
use anyhow::Result;
use codewhale_models::{MessageRequest, MessageResponse, StreamEvent};
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, Instant};
use uuid::Uuid;
#[cfg(test)]
pub mod mock;
// === LlmClient Trait ===
/// Type alias for boxed stream of SSE events
pub type StreamEventBox =
Pin<Box<dyn futures_util::Stream<Item = Result<StreamEvent>> + Send + 'static>>;
/// Unified interface for LLM providers.
///
/// This trait abstracts over different LLM APIs (DeepSeek, `OpenAI`, etc.)
/// allowing the agent to work with any provider that implements this interface.
///
/// # Implementation Notes
///
/// - All methods are async and require `Send + Sync` for thread safety
/// - The `create_message_stream` method returns a pinned boxed stream for SSE
/// - Implementations should handle their own authentication and base URL configuration
#[allow(async_fn_in_trait, dead_code)] // Trait methods are part of the LLM provider interface
pub trait LlmClient: Send + Sync {
/// Returns the provider name (e.g., "openai", "deepseek")
fn provider_name(&self) -> &'static str;
/// Returns the model identifier being used
fn model(&self) -> &str;
/// Creates a non-streaming message completion
fn create_message(
&self,
request: MessageRequest,
) -> impl Future<Output = Result<MessageResponse>> + Send;
/// Dispatch a fresh request. Clients with a local response cache must
/// override this; authorization decisions cannot reuse earlier answers.
fn create_message_uncached(
&self,
request: MessageRequest,
) -> impl Future<Output = Result<MessageResponse>> + Send {
self.create_message(request)
}
/// Creates a streaming message completion
///
/// Returns a stream of SSE events that should be consumed until completion.
fn create_message_stream(
&self,
request: MessageRequest,
) -> impl Future<Output = Result<StreamEventBox>> + Send;
/// Optional health check to verify API connectivity
fn health_check(&self) -> impl Future<Output = Result<bool>> + Send {
async { Ok(true) }
}
/// The concrete base URL requests go to, when the implementation knows it.
///
/// Background cost accrual uses this for billing provenance only: it is
/// reduced to a non-secret surface classification and a SHA-256 fingerprint
/// before being recorded, and the URL itself is never persisted or logged
/// (#4318). The default is `None` so an implementation that cannot report a
/// stable endpoint yields "unknown endpoint" — which fails closed — rather
/// than being assumed to be the provider's public API.
fn billing_base_url(&self) -> Option<&str> {
None
}
/// Non-secret limits frozen with the resolved route, when available.
fn route_limits(&self) -> Option<codewhale_config::route::RouteLimits> {
None
}
/// Output cap for a request sent through this exact client route.
fn effective_max_output_tokens(&self, requested_model: &str) -> u32 {
let route = self.effective_route_envelope(requested_model, chrono::Utc::now());
crate::route_budget::effective_max_output_tokens_for_route(
route.provider,
&route.model,
self.route_limits(),
)
}
/// Freeze the non-secret effective route immediately before a request is
/// dispatched. Implementations with richer configured identity/billing
/// facts should override this fail-closed default.
fn effective_route_envelope(
&self,
requested_model: &str,
dispatched_at: chrono::DateTime<chrono::Utc>,
) -> crate::cost_status::EffectiveRouteEnvelope {
let provider = crate::config::ApiProvider::parse(self.provider_name())
.unwrap_or(crate::config::ApiProvider::Custom);
crate::cost_status::EffectiveRouteEnvelope::capture(
None,
provider,
self.provider_name(),
requested_model,
self.billing_base_url(),
dispatched_at,
)
}
}
// === Authentication diagnostics ===
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AuthenticationErrorContext {
pub provider: Option<String>,
pub base_url_authority: Option<String>,
pub model: Option<String>,
pub key_source: Option<String>,
pub key_fingerprint: Option<String>,
pub key_kind: Option<String>,
}
impl AuthenticationErrorContext {
#[must_use]
pub fn new(
provider: &str,
base_url: &str,
model: &str,
key_source: &str,
api_key: &str,
) -> Self {
Self::from_parts(
Some(provider),
Some(base_url),
Some(model),
Some(key_source),
Some(api_key),
)
}
#[must_use]
pub fn from_parts(
provider: Option<&str>,
base_url: Option<&str>,
model: Option<&str>,
key_source: Option<&str>,
api_key: Option<&str>,
) -> Self {
let api_key = api_key.and_then(non_empty_trimmed);
Self {
provider: provider.and_then(non_empty_trimmed).map(str::to_string),
base_url_authority: base_url.and_then(base_url_authority),
model: model.and_then(non_empty_trimmed).map(str::to_string),
key_source: key_source.and_then(non_empty_trimmed).map(str::to_string),
key_fingerprint: api_key.map(redacted_key_fingerprint),
key_kind: api_key.map(classify_api_key_prefix).map(str::to_string),
}
}
fn is_empty(&self) -> bool {
self.provider.is_none()
&& self.base_url_authority.is_none()
&& self.model.is_none()
&& self.key_source.is_none()
&& self.key_fingerprint.is_none()
&& self.key_kind.is_none()
}
fn detail_segments(&self) -> Vec<String> {
let mut segments = Vec::new();
if let Some(provider) = self.provider.as_deref() {
segments.push(format!("provider: {provider}"));
}
if let Some(authority) = self.base_url_authority.as_deref() {
segments.push(format!("base URL authority: {authority}"));
}
if let Some(model) = self.model.as_deref() {
segments.push(format!("model: {model}"));
}
if let Some(source) = self.key_source.as_deref() {
segments.push(format!("key source: {source}"));
}
if let Some(fingerprint) = self.key_fingerprint.as_deref() {
segments.push(format!("key fingerprint: {fingerprint}"));
}
if let Some(kind) = self.key_kind.as_deref() {
segments.push(format!("key type: {kind}"));
}
segments
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthenticationErrorDetail {
message: String,
context: Option<AuthenticationErrorContext>,
}
impl AuthenticationErrorDetail {
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
context: None,
}
}
#[must_use]
pub fn with_context(
message: impl Into<String>,
context: Option<AuthenticationErrorContext>,
) -> Self {
let context = context.filter(|context| !context.is_empty());
Self {
message: message.into(),
context,
}
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn to_user_message(&self) -> String {
let Some(context) = self.context.as_ref() else {
return self.message.clone();
};
let segments = context.detail_segments();
if segments.is_empty() {
self.message.clone()
} else {
format!("{} ({})", self.message, segments.join(", "))
}
}
}
impl From<String> for AuthenticationErrorDetail {
fn from(message: String) -> Self {
Self::new(message)
}
}
impl From<&str> for AuthenticationErrorDetail {
fn from(message: &str) -> Self {
Self::new(message)
}
}
#[must_use]
pub fn classify_api_key_prefix(api_key: &str) -> &'static str {
if api_key.starts_with("tp-") {
"Xiaomi MiMo Token Plan key"
} else {
"API key"
}
}
fn non_empty_trimmed(value: &str) -> Option<&str> {
let value = value.trim();
if value.is_empty() { None } else { Some(value) }
}
fn base_url_authority(base_url: &str) -> Option<String> {
let base_url = non_empty_trimmed(base_url)?;
let without_scheme = base_url
.split_once("://")
.map_or(base_url, |(_, rest)| rest);
let authority = without_scheme.split('/').next().unwrap_or(without_scheme);
let authority = authority
.rsplit_once('@')
.map_or(authority, |(_, authority)| authority);
non_empty_trimmed(authority).map(str::to_string)
}
fn redacted_key_fingerprint(api_key: &str) -> String {
let api_key = api_key.trim();
let len = api_key.chars().count();
match public_key_prefix(api_key) {
Some(prefix) => format!("{prefix}... (len={len})"),
None => format!("unprefixed (len={len})"),
}
}
fn public_key_prefix(api_key: &str) -> Option<&str> {
["tp-", "sk-", "hf_", "hf-", "ak-", "rk-"]
.into_iter()
.find(|prefix| api_key.starts_with(prefix))
}
fn redact_api_key_from_message(message: &str, api_key: Option<&str>) -> String {
let Some(api_key) = api_key.and_then(non_empty_trimmed) else {
return message.to_string();
};
message.replace(api_key, "[redacted API key]")
}
// === LlmError - Classified Error Types ===
/// Evidence captured when an HTTP response explicitly identifies plan quota
/// exhaustion. The private field prevents callers outside this parser module
/// from manufacturing the durable classification from arbitrary text.
#[derive(Debug)]
pub struct QuotaExhaustionError {
message: String,
}
impl QuotaExhaustionError {
fn from_http_message(message: String) -> Self {
Self { message }
}
pub(crate) fn into_message(self) -> String {
self.message
}
}
/// Classified LLM errors with retryability information.
///
/// This enum categorizes API errors to enable smart retry decisions.
/// Some errors (rate limits, transient server errors) are retryable,
/// while others (auth failures, invalid requests) should fail immediately.
#[derive(Debug)]
pub enum LlmError {
/// Rate limit exceeded (HTTP 429)
/// Contains optional Retry-After duration from server
RateLimited {
message: String,
retry_after: Option<Duration>,
},
/// The provider explicitly reported that the account's plan quota is exhausted.
///
/// Unlike an ordinary 429 rate limit, retrying the same request after a short
/// backoff cannot resolve this condition. This variant is constructed only at
/// the provider HTTP response boundary from explicit quota evidence.
QuotaExhausted(QuotaExhaustionError),
/// Server error (HTTP 5xx)
ServerError { status: u16, message: String },
/// Network connectivity error
NetworkError(String),
/// Request timed out
Timeout(Duration),
/// Authentication failed (HTTP 401, selected HTTP 403)
AuthenticationError(AuthenticationErrorDetail),
/// Authorization or provider-side blocking failed (HTTP 403)
AuthorizationError(String),
/// Invalid request parameters (HTTP 400)
InvalidRequest { status: u16, message: String },
/// Model-specific error (model not found, etc.)
ModelError(String),
/// Content policy violation (safety filters)
ContentPolicyError(String),
/// Failed to parse API response
ParseError(String),
/// Context length exceeded
ContextLengthError(String),
/// Catch-all for other errors
Other(String),
}
impl std::fmt::Display for LlmError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LlmError::RateLimited { message, .. } => write!(f, "Rate limit exceeded: {message}"),
LlmError::QuotaExhausted(error) => {
write!(f, "Provider plan quota exhausted: {}", error.message)
}
LlmError::ServerError { status, message } => {
write!(f, "Server error ({status}): {message}")
}
LlmError::NetworkError(msg) => write!(f, "Network error: {msg}"),
LlmError::Timeout(d) => write!(f, "Request timed out after {d:?}"),
LlmError::AuthenticationError(auth) => {
write!(f, "Authentication failed: {}", auth.to_user_message())
}
LlmError::AuthorizationError(msg) => write!(f, "Authorization failed: {msg}"),
LlmError::InvalidRequest { status, message } => {
write!(f, "Invalid request ({status}): {message}")
}
LlmError::ModelError(msg) => write!(f, "Model error: {msg}"),
LlmError::ContentPolicyError(msg) => write!(f, "Content policy violation: {msg}"),
LlmError::ParseError(msg) => write!(f, "Response parsing error: {msg}"),
LlmError::ContextLengthError(msg) => write!(f, "Context length exceeded: {msg}"),
LlmError::Other(msg) => write!(f, "LLM error: {msg}"),
}
}
}
impl std::error::Error for LlmError {}
impl LlmError {
/// Determines if this error is potentially transient and worth retrying.
///
/// Retryable errors:
/// - Rate limits (with backoff)
/// - Server errors (5xx)
/// - Network errors (connection issues)
/// - Timeouts
///
/// Non-retryable errors:
/// - Provider plan quota exhaustion
/// - Authentication failures
/// - Invalid requests
/// - Content policy violations
/// - Context length errors
pub fn is_retryable(&self) -> bool {
matches!(
self,
LlmError::RateLimited { .. }
| LlmError::ServerError { .. }
| LlmError::NetworkError(_)
| LlmError::Timeout(_)
)
}
/// Returns the server-suggested retry delay if available.
///
/// This is typically present for rate limit errors when the server
/// provides a Retry-After header.
pub fn suggested_retry_delay(&self) -> Option<Duration> {
match self {
LlmError::RateLimited { retry_after, .. } => *retry_after,
_ => None,
}
}
/// Constructs an `LlmError` from HTTP status code and response body.
///
/// Performs heuristic classification based on:
/// - Status code (429 = rate limit, 401/403 = auth, 499/5xx = transient upstream error)
/// - Response body keywords (`context_length`, `content_policy`, safety, etc.)
pub fn from_http_response(status: u16, body: &str) -> Self {
if matches!(status, 400 | 402 | 429) && has_explicit_quota_evidence(body) {
return LlmError::QuotaExhausted(QuotaExhaustionError::from_http_message(
body.to_string(),
));
}
match status {
429 => LlmError::RateLimited {
message: body.to_string(),
retry_after: None,
},
401 => Self::authentication_error(body),
403 => {
if looks_like_authentication_failure(body) {
Self::authentication_error(body)
} else {
LlmError::AuthorizationError(body.to_string())
}
}
400 => {
// Classify 400 errors by examining the response body
let body_lower = body.to_lowercase();
// An "unsupported parameter" 400 names the offending field
// (often `max_output_tokens` or another *token* field), which
// the generic keyword rules below would misread as a context
// window overflow. Parameter shape errors are invalid
// requests, not prompt-size errors, so they get their own
// branch ahead of the heuristic.
if body_lower.contains("unsupported parameter")
|| body_lower.contains("invalid_request_error")
&& body_lower.contains("parameter")
{
LlmError::InvalidRequest {
status,
message: body.to_string(),
}
} else if body_lower.contains("context_length")
|| body_lower.contains("token")
|| body_lower.contains("too long")
|| body_lower.contains("maximum")
{
LlmError::ContextLengthError(body.to_string())
} else if body_lower.contains("content_policy")
|| body_lower.contains("safety")
|| body_lower.contains("harmful")
|| body_lower.contains("inappropriate")
{
LlmError::ContentPolicyError(body.to_string())
} else if body_lower.contains("model") && body_lower.contains("not found") {
LlmError::ModelError(body.to_string())
} else {
LlmError::InvalidRequest {
status,
message: body.to_string(),
}
}
}
404 => {
if body.to_lowercase().contains("model") {
LlmError::ModelError(body.to_string())
} else {
LlmError::InvalidRequest {
status,
message: body.to_string(),
}
}
}
// Several OpenAI-compatible gateways use nginx's non-standard
// 499 for an upstream request that was cancelled before response
// streaming began. At this boundary no response body stream has
// been exposed, so it is eligible for the same bounded retry
// policy as a 5xx gateway failure.
499..=599 => LlmError::ServerError {
status,
message: body.to_string(),
},
_ => LlmError::Other(format!("HTTP {status}: {body}")),
}
}
#[must_use]
pub fn authentication_error(message: impl Into<String>) -> Self {
LlmError::AuthenticationError(AuthenticationErrorDetail::new(message))
}
#[must_use]
pub fn authentication_error_with_context(
message: impl Into<String>,
context: Option<AuthenticationErrorContext>,
) -> Self {
LlmError::AuthenticationError(AuthenticationErrorDetail::with_context(message, context))
}
/// Constructs an `LlmError` from HTTP response data plus request context
/// that is safe to display when authentication fails.
#[must_use]
pub fn from_http_response_with_request_context(
status: u16,
body: &str,
provider: Option<&str>,
base_url: Option<&str>,
model: Option<&str>,
key_source: Option<&str>,
api_key: Option<&str>,
) -> Self {
let body = redact_api_key_from_message(body, api_key);
let context =
AuthenticationErrorContext::from_parts(provider, base_url, model, key_source, api_key);
Self::from_http_response_with_auth_context(status, &body, Some(context))
}
/// Constructs an `LlmError` from HTTP status code and response body, with
/// optional structured details for authentication failures.
///
/// The `body` passed here must already be safe for user display. Prefer
/// [`Self::from_http_response_with_request_context`] when the raw API key is
/// available so the response body can be redacted before rendering.
#[must_use]
pub fn from_http_response_with_auth_context(
status: u16,
body: &str,
auth_context: Option<AuthenticationErrorContext>,
) -> Self {
match status {
401 => Self::authentication_error_with_context(body, auth_context),
403 => {
if looks_like_authentication_failure(body) {
Self::authentication_error_with_context(body, auth_context)
} else {
LlmError::AuthorizationError(body.to_string())
}
}
_ => Self::from_http_response(status, body),
}
}
/// Constructs an `LlmError` from HTTP status code, body, and optional Retry-After header.
pub fn from_http_response_with_retry_after(
status: u16,
body: &str,
retry_after: Option<Duration>,
) -> Self {
let mut error = Self::from_http_response(status, body);
if let LlmError::RateLimited {
retry_after: ref mut ra,
..
} = error
{
*ra = retry_after;
}
error
}
/// Constructs an `LlmError` from a reqwest error.
pub fn from_reqwest(err: &reqwest::Error) -> Self {
if err.is_timeout() {
LlmError::Timeout(Duration::from_secs(0))
} else if err.is_connect() {
LlmError::NetworkError(format!("Connection failed: {err}"))
} else if err.is_request() {
LlmError::NetworkError(format!("Request failed: {err}"))
} else {
LlmError::Other(err.to_string())
}
}
}
/// Format provider HTTP error bodies before they are surfaced in the TUI.
///
/// Providers sometimes return whole HTML error pages for gateway/WAF blocks.
/// Passing those pages through raw floods the transcript and can also make a
/// provider-side 403 look like a broken API key. Keep the useful details and
/// cap everything else.
#[must_use]
pub(crate) fn sanitize_http_error_body(
provider_label: Option<&str>,
status: u16,
body: &str,
) -> String {
let json_message = extract_json_error_message(body);
let message = json_message.as_deref().unwrap_or(body);
// Gate on Google's actual rejection, not the selected provider or model:
// compatible gateways may manage signatures themselves (#6048). This
// shared boundary covers both streaming and non-streaming HTTP failures.
const SIGNATURE_HINT: &str = "Gemini rejected tool-call replay because a thought signature is missing. \
Use the built-in `google` provider with its default endpoint, or a gateway that preserves \
Google thought signatures, then start a new session before using tools. \
Changing reasoning settings will not restore missing signatures.";
if status == 400
&& !is_probably_html(message)
&& explicit_quota_code(body).is_none()
&& !message.contains(SIGNATURE_HINT)
{
let lower = collapse_whitespace(message).to_ascii_lowercase();
if lower.contains("missing a thought_signature")
|| lower.contains("missing thought_signature")
|| lower.contains("thought_signature is missing")
{
let detail = truncate_for_error(&collapse_whitespace(message), 900);
return format!("{SIGNATURE_HINT} Provider error: {detail}");
}
}
if let Some(message) = json_message {
let message = truncate_for_error(&collapse_whitespace(&message), 2_000);
if let Some(code) = explicit_quota_code(body) {
return format!("{message} (provider error code: {code})");
}
return message;
}
if is_probably_html(body) {
let text = html_to_text(body);
let lower = text.to_ascii_lowercase();
let provider = provider_label.unwrap_or("Provider");
// Cloudflare's "Access Denied" interstitial strips the literal word
// "cloudflare" once tags are removed (it only survives in `<meta>`
// attributes and the `<style>`/`<script>` blocks we discard). Arcee's
// 403 page is exactly this shape, so also key off the WAF's stock copy
// ("security alert", "contact support") and a Cloudflare error/ray ID.
let error_id = extract_cloudflare_error_id(&text);
let is_cloudflare = lower.contains("cloudflare");
let looks_like_access_denied = lower.contains("access denied")
&& (is_cloudflare
|| lower.contains("security alert")
|| lower.contains("contact support")
|| lower.contains("contact us")
|| error_id.is_some());
if looks_like_access_denied {
let label = if is_cloudflare {
"Cloudflare Access Denied"
} else {
"Access Denied"
};
let mut message = format!(
"{provider} API returned {label} (HTTP {status}). \
The request was blocked before it reached the model; retry with a \
smaller request or fewer tools, or contact provider support"
);
if let Some(id) = error_id {
message.push_str(&format!(" with ID {id}"));
}
message.push('.');
return message;
}
let text = truncate_for_error(&collapse_whitespace(&text), 900);
return format!("{provider} API returned an HTML error page (HTTP {status}): {text}");
}
truncate_for_error(&collapse_whitespace(body), 2_000)
}
fn looks_like_authentication_failure(body: &str) -> bool {
let lower = body.to_ascii_lowercase();
lower.contains("authentication")
|| lower.contains("unauthorized")
|| lower.contains("api key")
|| lower.contains("invalid key")
|| lower.contains("invalid token")
|| lower.contains("bearer token")
|| lower.contains("missing token")
}
/// Quota exhaustion is a durable account state, not a generic rate-limit
/// synonym. Accept only explicit provider evidence at the HTTP/parser boundary;
/// callers holding a stringified error must never promote it to this type.
fn has_explicit_quota_evidence(body: &str) -> bool {
explicit_quota_code(body).is_some()
|| has_explicit_quota_code_marker(body)
|| has_explicit_quota_phrase(body)
}
fn explicit_quota_code(body: &str) -> Option<String> {
let value: Value = serde_json::from_str(body).ok()?;
[
"/error/code",
"/error/type",
"/error/error_code",
"/code",
"/type",
"/error_code",
]
.into_iter()
.filter_map(|pointer| value.pointer(pointer).and_then(Value::as_str))
.find(|code| is_explicit_quota_code(code))
.map(ToOwned::to_owned)
}
fn is_explicit_quota_code(code: &str) -> bool {
let normalized: String = code
.chars()
.filter(|ch| ch.is_ascii_alphanumeric())
.map(|ch| ch.to_ascii_lowercase())
.collect();
matches!(
normalized.as_str(),
"insufficientquota"
| "quotaexceeded"
| "quotaexhausted"
| "billinghardlimitreached"
| "billinglimitreached"
| "creditbalanceexhausted"
)
}
fn has_explicit_quota_code_marker(body: &str) -> bool {
let lower = body.to_ascii_lowercase();
let Some((_, suffix)) = lower.split_once("provider error code:") else {
return false;
};
let code = suffix
.trim_start()
.split(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')))
.next()
.unwrap_or_default();
is_explicit_quota_code(code)
}
fn has_explicit_quota_phrase(body: &str) -> bool {
let lower = body.to_ascii_lowercase();
let current_quota_exhausted = lower.contains("exceeded your current quota")
|| lower.contains("current quota has been exceeded");
let plan_and_billing_guidance = lower.contains("plan") && lower.contains("billing");
let durable_scope_exhausted = [
"billing quota exceeded",
"billing quota exhausted",
"billing quota is exhausted",
"billing quota has been exceeded",
"billing quota has been exhausted",
"account quota exceeded",
"account quota exhausted",
"account quota is exhausted",
"account quota has been exceeded",
"account quota has been exhausted",
"plan quota exceeded",
"plan quota exhausted",
"plan quota is exhausted",
"plan quota has been exceeded",
"plan quota has been exhausted",
]
.into_iter()
.any(|phrase| lower.contains(phrase));
lower.contains("billing hard limit has been reached")
|| lower.contains("credit balance exhausted")
|| lower.contains("credit balance is exhausted")
|| durable_scope_exhausted
|| (current_quota_exhausted && plan_and_billing_guidance)
}
fn extract_json_error_message(body: &str) -> Option<String> {
let value: Value = serde_json::from_str(body).ok()?;
// Flat gateway bodies (`{"error":"Bad Request","message":"Invalid model
// name: 'x'"}` — Concentrate, among others) keep the class in `error` and
// the detail in `message`. Surfacing only the class hid the one line the
// person needed, so carry both when both are present and differ.
if let (Some(class), Some(detail)) = (
value.pointer("/error").and_then(Value::as_str),
value.pointer("/message").and_then(Value::as_str),
) && !class.trim().is_empty()
&& !detail.trim().is_empty()
&& !class.trim().eq_ignore_ascii_case(detail.trim())
{
return Some(format!("{}: {}", class.trim(), detail.trim()));
}
for pointer in [
"/error/message",
"/error",
"/message",
"/detail",
"/error_description",
] {
let Some(value) = value.pointer(pointer) else {
continue;
};
if let Some(message) = value.as_str() {
if !message.trim().is_empty() {
return Some(message.to_string());
}
} else if value.is_object() || value.is_array() {
return Some(value.to_string());
}
}
None
}
fn is_probably_html(body: &str) -> bool {
let prefix = body
.chars()
.take(512)
.collect::<String>()
.to_ascii_lowercase();
prefix.contains("<!doctype html") || prefix.contains("<html") || prefix.contains("<head")
}
fn html_to_text(html: &str) -> String {
let without_scripts = strip_html_block(html, "script");
let without_styles = strip_html_block(&without_scripts, "style");
let mut text = String::with_capacity(without_styles.len().min(4096));
let mut in_tag = false;
for ch in without_styles.chars() {
match ch {
'<' => {
in_tag = true;
text.push(' ');
}
'>' => {
in_tag = false;
text.push(' ');
}
_ if !in_tag => text.push(ch),
_ => {}
}
}
decode_basic_html_entities(&collapse_whitespace(&text))
}
fn strip_html_block(input: &str, tag: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut cursor = 0usize;
let lower = input.to_ascii_lowercase();
let start_marker = format!("<{tag}");
let end_marker = format!("</{tag}>");
while let Some(relative_start) = lower[cursor..].find(&start_marker) {
let start = cursor + relative_start;
out.push_str(&input[cursor..start]);
let after_start = start + start_marker.len();
let Some(relative_end) = lower[after_start..].find(&end_marker) else {
cursor = input.len();
break;
};
cursor = after_start + relative_end + end_marker.len();
out.push(' ');
}
out.push_str(&input[cursor..]);
out
}
fn decode_basic_html_entities(input: &str) -> String {
input
.replace(" ", " ")
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'")
}
fn collapse_whitespace(input: &str) -> String {
input.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn truncate_for_error(input: &str, max_chars: usize) -> String {
let mut out = String::with_capacity(input.len().min(max_chars + 32));
for (count, ch) in input.chars().enumerate() {
if count >= max_chars {
out.push_str("...");
return out;
}
out.push(ch);
}
out
}
fn extract_cloudflare_error_id(text: &str) -> Option<String> {
let mut last = None;
for token in text.split(|ch: char| !ch.is_ascii_hexdigit()) {
if (16..=64).contains(&token.len()) && token.bytes().any(|b| b.is_ascii_alphabetic()) {
last = Some(token.to_string());
}
}
last
}
impl From<reqwest::Error> for LlmError {
fn from(err: reqwest::Error) -> Self {
LlmError::from_reqwest(&err)
}
}
impl From<serde_json::Error> for LlmError {
fn from(err: serde_json::Error) -> Self {
LlmError::ParseError(err.to_string())
}
}
// === RetryConfig - Exponential Backoff Configuration ===
/// Configuration for retry behavior with exponential backoff.
///
/// This struct controls how retries are performed:
/// - Number of retry attempts
/// - Delay calculation (exponential backoff with optional jitter)
/// - Which HTTP status codes are retryable
/// - Timeout handling
///
/// # Default Values
///
/// - `enabled`: true
/// - `max_retries`: 3
/// - `initial_delay`: 1.0 seconds
/// - `max_delay`: 60.0 seconds
/// - `exponential_base`: 2.0
/// - `jitter`: true (adds randomness to prevent thundering herd)
/// - `jitter_factor`: 0.1 (10% variation)
/// - `retryable_status_codes`: [429, 499, 500, 502, 503, 504]
#[derive(Debug, Clone)]
pub struct RetryConfig {
/// Whether retry logic is enabled
pub enabled: bool,
/// Maximum number of retry attempts (0 = no retries, 3 = up to 4 total attempts)
pub max_retries: u32,
/// Initial delay before first retry (seconds)
pub initial_delay: f64,
/// Maximum delay between retries (seconds)
pub max_delay: f64,
/// Base for exponential backoff (delay = initial * base^attempt)
pub exponential_base: f64,
/// Whether to add random jitter to delays
pub jitter: bool,