autoagents-llm 0.4.0

Agent Framework for Building Autonomous Agents
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
use std::fmt;
use std::time::Duration;

/// Maximum bytes of a provider response body included in [`Display`](fmt::Display) output.
pub const MAX_ERROR_BODY_DISPLAY_BYTES: usize = 512;

/// Phase where a guardrail violation occurred.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuardrailPhase {
    Input,
    Output,
}

/// Error types that can occur when interacting with LLM providers.
#[derive(Clone)]
pub enum LLMError {
    /// HTTP transport failures (connection, timeout, DNS, etc.).
    HttpError(String),
    /// Authentication and authorization errors (missing local API key or HTTP 401/403).
    AuthError {
        message: String,
        status_code: Option<u16>,
        response_body: Option<Box<str>>,
    },
    /// Rate limit or provider overload (HTTP 429, 529).
    RateLimitError {
        status_code: u16,
        message: String,
        response_body: Box<str>,
        retry_after: Option<Duration>,
        provider_code: Option<Box<str>>,
    },
    /// Non-success HTTP response that is not auth or rate-limit.
    HttpStatusError {
        status_code: u16,
        message: String,
        response_body: Box<str>,
        retry_after: Option<Duration>,
        provider_code: Option<Box<str>>,
    },
    /// Invalid request parameters, format, or client-side HTTP 4xx rejection.
    InvalidRequest {
        message: String,
        status_code: Option<u16>,
        response_body: Option<Box<str>>,
    },
    /// Errors returned by the LLM provider in a parsed response payload.
    ProviderError(String),
    /// API response parsing or format error on a successful HTTP response.
    ResponseFormatError {
        message: String,
        raw_response: String,
    },
    /// Generic error (unsupported features, internal stubs).
    Generic(String),
    /// JSON serialization/deserialization errors.
    JsonError(String),
    /// Tool configuration error.
    ToolConfigError(String),
    /// Provider does not support tool calling.
    NoToolSupport(String),
    /// Guardrail blocked the request/response.
    GuardrailBlocked {
        phase: GuardrailPhase,
        guard: Box<str>,
        rule_id: Box<str>,
        category: Box<str>,
        severity: Box<str>,
        message: Box<str>,
    },
    /// Guardrail execution failed unexpectedly.
    GuardrailExecutionFailed { guard: String, message: String },
}

impl LLMError {
    /// Local configuration error when an API key is missing.
    pub fn missing_api_key(message: impl Into<String>) -> Self {
        Self::AuthError {
            message: message.into(),
            status_code: None,
            response_body: None,
        }
    }

    /// Local validation error for invalid request parameters or configuration.
    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self::InvalidRequest {
            message: message.into(),
            status_code: None,
            response_body: None,
        }
    }

    /// Returns `true` when the error represents a transient failure worth retrying.
    pub fn is_retryable(&self) -> bool {
        is_retryable(self)
    }

    /// HTTP status code when the error originated from a non-success response.
    pub fn http_status_code(&self) -> Option<u16> {
        match self {
            Self::AuthError { status_code, .. } => *status_code,
            Self::RateLimitError { status_code, .. } => Some(*status_code),
            Self::HttpStatusError { status_code, .. } => Some(*status_code),
            Self::InvalidRequest { status_code, .. } => *status_code,
            _ => None,
        }
    }

    /// Provider response body attached to HTTP-related errors.
    pub fn response_body(&self) -> Option<&str> {
        match self {
            Self::AuthError { response_body, .. } => response_body.as_deref(),
            Self::RateLimitError { response_body, .. } => Some(response_body),
            Self::HttpStatusError { response_body, .. } => Some(response_body),
            Self::InvalidRequest { response_body, .. } => response_body.as_deref(),
            Self::ResponseFormatError { raw_response, .. } => Some(raw_response),
            _ => None,
        }
    }

    /// Returns `true` when this `HttpError` represents a retryable transport failure.
    pub fn is_transport_retryable(&self) -> bool {
        match self {
            Self::HttpError(msg) => is_transport_retryable_message(msg),
            _ => false,
        }
    }
}

/// Returns `true` when a transport error message represents a retryable failure.
pub fn is_transport_retryable_message(message: &str) -> bool {
    let m = message.to_ascii_lowercase();
    m.starts_with("request timed out:")
        || m.starts_with("connection failed:")
        || m.contains("connection reset")
        || m.contains("broken pipe")
        || m.contains("dns error")
        || m.contains("dns lookup")
        || m.contains("name or service not known")
}

/// Truncates a response body for safe inclusion in log-oriented display output.
pub fn truncate_for_display(body: &str) -> String {
    if body.len() <= MAX_ERROR_BODY_DISPLAY_BYTES {
        return body.to_string();
    }

    let mut end = MAX_ERROR_BODY_DISPLAY_BYTES;
    while end > 0 && !body.is_char_boundary(end) {
        end -= 1;
    }

    format!(
        "{}... [truncated, {} bytes total]",
        &body[..end],
        body.len()
    )
}

fn write_truncated_body(f: &mut fmt::Formatter<'_>, label: &str, body: &str) -> fmt::Result {
    write!(f, ". {label}: {}", truncate_for_display(body))
}

fn debug_optional_body(body: &Option<Box<str>>) -> Option<String> {
    body.as_deref().map(truncate_for_display)
}

impl fmt::Debug for LLMError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HttpError(message) => f.debug_tuple("HttpError").field(message).finish(),
            Self::AuthError {
                message,
                status_code,
                response_body,
            } => f
                .debug_struct("AuthError")
                .field("message", message)
                .field("status_code", status_code)
                .field("response_body", &debug_optional_body(response_body))
                .finish(),
            Self::RateLimitError {
                status_code,
                message,
                response_body,
                retry_after,
                provider_code,
            } => f
                .debug_struct("RateLimitError")
                .field("status_code", status_code)
                .field("message", message)
                .field("response_body", &truncate_for_display(response_body))
                .field("retry_after", retry_after)
                .field("provider_code", provider_code)
                .finish(),
            Self::HttpStatusError {
                status_code,
                message,
                response_body,
                retry_after,
                provider_code,
            } => f
                .debug_struct("HttpStatusError")
                .field("status_code", status_code)
                .field("message", message)
                .field("response_body", &truncate_for_display(response_body))
                .field("retry_after", retry_after)
                .field("provider_code", provider_code)
                .finish(),
            Self::InvalidRequest {
                message,
                status_code,
                response_body,
            } => f
                .debug_struct("InvalidRequest")
                .field("message", message)
                .field("status_code", status_code)
                .field("response_body", &debug_optional_body(response_body))
                .finish(),
            Self::ProviderError(message) => f.debug_tuple("ProviderError").field(message).finish(),
            Self::ResponseFormatError {
                message,
                raw_response,
            } => f
                .debug_struct("ResponseFormatError")
                .field("message", message)
                .field("raw_response", &truncate_for_display(raw_response))
                .finish(),
            Self::Generic(message) => f.debug_tuple("Generic").field(message).finish(),
            Self::JsonError(message) => f.debug_tuple("JsonError").field(message).finish(),
            Self::ToolConfigError(message) => {
                f.debug_tuple("ToolConfigError").field(message).finish()
            }
            Self::NoToolSupport(message) => f.debug_tuple("NoToolSupport").field(message).finish(),
            Self::GuardrailBlocked {
                phase,
                guard,
                rule_id,
                category,
                severity,
                message,
            } => f
                .debug_struct("GuardrailBlocked")
                .field("phase", phase)
                .field("guard", guard)
                .field("rule_id", rule_id)
                .field("category", category)
                .field("severity", severity)
                .field("message", message)
                .finish(),
            Self::GuardrailExecutionFailed { guard, message } => f
                .debug_struct("GuardrailExecutionFailed")
                .field("guard", guard)
                .field("message", message)
                .finish(),
        }
    }
}

/// Returns `true` when an HTTP status code represents a retryable server/transient error.
pub fn is_http_status_retryable(status_code: u16) -> bool {
    matches!(status_code, 408 | 500..=599)
}

/// Default retryability predicate shared by the retry layer.
pub fn is_retryable(err: &LLMError) -> bool {
    match err {
        LLMError::RateLimitError { .. } => true,
        LLMError::HttpStatusError { status_code, .. } => is_http_status_retryable(*status_code),
        LLMError::HttpError(msg) => is_transport_retryable_message(msg),
        LLMError::Generic(_)
        | LLMError::AuthError { .. }
        | LLMError::InvalidRequest { .. }
        | LLMError::GuardrailBlocked { .. }
        | LLMError::GuardrailExecutionFailed { .. }
        | LLMError::ResponseFormatError { .. }
        | LLMError::JsonError(_)
        | LLMError::ToolConfigError(_)
        | LLMError::NoToolSupport(_)
        | LLMError::ProviderError(_) => false,
    }
}

/// Default fallbackability predicate shared by the fallback layer.
///
/// Unlike [`is_retryable`], every [`LLMError::HttpError`] is fallbackable regardless
/// of message content so callers can route any transport failure to a backup provider.
/// Retryability still requires a transport-failure message via
/// [`is_transport_retryable_message`].
pub fn is_fallbackable(err: &LLMError) -> bool {
    match err {
        LLMError::RateLimitError { .. } => true,
        LLMError::HttpStatusError { status_code, .. } => is_http_status_retryable(*status_code),
        LLMError::HttpError(_) => true,
        LLMError::ProviderError(_)
        | LLMError::ResponseFormatError { .. }
        | LLMError::NoToolSupport(_)
        | LLMError::Generic(_) => true,
        LLMError::AuthError { .. }
        | LLMError::InvalidRequest { .. }
        | LLMError::JsonError(_)
        | LLMError::ToolConfigError(_)
        | LLMError::GuardrailBlocked { .. }
        | LLMError::GuardrailExecutionFailed { .. } => false,
    }
}

fn write_status_prefixed_error(
    f: &mut fmt::Formatter<'_>,
    label: &str,
    message: &str,
    status_code: Option<u16>,
    response_body: Option<&str>,
) -> fmt::Result {
    if let Some(status) = status_code {
        write!(f, "{label} ({status}): {message}")?;
    } else {
        write!(f, "{label}: {message}")?;
    }
    if let Some(body) = response_body {
        write_truncated_body(f, "Response", body)?;
    }
    Ok(())
}

fn display_auth_error(
    f: &mut fmt::Formatter<'_>,
    message: &str,
    status_code: Option<u16>,
    response_body: Option<&str>,
) -> fmt::Result {
    write_status_prefixed_error(f, "Auth Error", message, status_code, response_body)
}

fn display_rate_limit_error(
    f: &mut fmt::Formatter<'_>,
    status_code: u16,
    message: &str,
    response_body: &str,
    retry_after: Option<Duration>,
    provider_code: Option<&str>,
) -> fmt::Result {
    write!(f, "Rate Limit Error ({status_code}): {message}")?;
    write_truncated_body(f, "Response", response_body)?;
    if let Some(code) = provider_code {
        write!(f, ". Provider code: {code}")?;
    }
    if let Some(retry_after) = retry_after {
        write!(f, ". Retry-After: {}s", retry_after.as_secs())?;
    }
    Ok(())
}

fn display_http_status_error(
    f: &mut fmt::Formatter<'_>,
    status_code: u16,
    message: &str,
    response_body: &str,
    retry_after: Option<Duration>,
    provider_code: Option<&str>,
) -> fmt::Result {
    write!(f, "HTTP Status Error ({status_code}): {message}")?;
    write_truncated_body(f, "Response", response_body)?;
    if let Some(code) = provider_code {
        write!(f, ". Provider code: {code}")?;
    }
    if let Some(retry_after) = retry_after {
        write!(f, ". Retry-After: {}s", retry_after.as_secs())?;
    }
    Ok(())
}

fn display_invalid_request(
    f: &mut fmt::Formatter<'_>,
    message: &str,
    status_code: Option<u16>,
    response_body: Option<&str>,
) -> fmt::Result {
    write_status_prefixed_error(f, "Invalid Request", message, status_code, response_body)
}

fn display_response_format_error(
    f: &mut fmt::Formatter<'_>,
    message: &str,
    raw_response: &str,
) -> fmt::Result {
    write!(f, "Response Format Error: {message}")?;
    write_truncated_body(f, "Raw response", raw_response)
}

fn display_guardrail_blocked(
    f: &mut fmt::Formatter<'_>,
    phase: GuardrailPhase,
    guard: &str,
    rule_id: &str,
    category: &str,
    severity: &str,
    message: &str,
) -> fmt::Result {
    let phase = match phase {
        GuardrailPhase::Input => "input",
        GuardrailPhase::Output => "output",
    };
    write!(
        f,
        "guardrail blocked {phase}: guard={guard}, rule={rule_id}, category={category}, severity={severity}, message={message}"
    )
}

impl fmt::Display for LLMError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LLMError::HttpError(e) => write!(f, "HTTP Error: {e}"),
            LLMError::AuthError {
                message,
                status_code,
                response_body,
            } => display_auth_error(f, message, *status_code, response_body.as_deref()),
            LLMError::RateLimitError {
                status_code,
                message,
                response_body,
                retry_after,
                provider_code,
            } => display_rate_limit_error(
                f,
                *status_code,
                message,
                response_body,
                *retry_after,
                provider_code.as_deref(),
            ),
            LLMError::HttpStatusError {
                status_code,
                message,
                response_body,
                retry_after,
                provider_code,
            } => display_http_status_error(
                f,
                *status_code,
                message,
                response_body,
                *retry_after,
                provider_code.as_deref(),
            ),
            LLMError::InvalidRequest {
                message,
                status_code,
                response_body,
            } => display_invalid_request(f, message, *status_code, response_body.as_deref()),
            LLMError::ProviderError(e) => write!(f, "Provider Error: {e}"),
            LLMError::Generic(e) => write!(f, "Generic Error : {e}"),
            LLMError::ResponseFormatError {
                message,
                raw_response,
            } => display_response_format_error(f, message, raw_response),
            LLMError::JsonError(e) => write!(f, "JSON Parse Error: {e}"),
            LLMError::ToolConfigError(e) => write!(f, "Tool Configuration Error: {e}"),
            LLMError::NoToolSupport(e) => write!(f, "No Tool Support: {e}"),
            LLMError::GuardrailBlocked {
                phase,
                guard,
                rule_id,
                category,
                severity,
                message,
            } => display_guardrail_blocked(f, *phase, guard, rule_id, category, severity, message),
            LLMError::GuardrailExecutionFailed { guard, message } => write!(
                f,
                "guardrail execution failed: guard={guard}, error={message}"
            ),
        }
    }
}

impl std::error::Error for LLMError {}

/// Converts reqwest HTTP errors into LLMErrors, preserving transport context.
#[cfg(not(target_arch = "wasm32"))]
impl From<reqwest::Error> for LLMError {
    fn from(err: reqwest::Error) -> Self {
        if err.is_timeout() {
            LLMError::HttpError(format!("request timed out: {err}"))
        } else if err.is_connect() {
            LLMError::HttpError(format!("connection failed: {err}"))
        } else {
            LLMError::HttpError(err.to_string())
        }
    }
}

impl From<serde_json::Error> for LLMError {
    fn from(err: serde_json::Error) -> Self {
        LLMError::JsonError(format!(
            "{} at line {} column {}",
            err,
            err.line(),
            err.column()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Error as JsonError;

    #[test]
    fn test_truncate_for_display_short_body_unchanged() {
        assert_eq!(truncate_for_display("short"), "short");
    }

    #[test]
    fn test_truncate_for_display_long_body() {
        let body = "x".repeat(MAX_ERROR_BODY_DISPLAY_BYTES + 10);
        let truncated = truncate_for_display(&body);
        assert!(truncated.contains("truncated"));
        assert!(truncated.starts_with(&"x".repeat(MAX_ERROR_BODY_DISPLAY_BYTES)));
    }

    #[test]
    fn test_is_transport_retryable_message_prefixed_forms() {
        assert!(is_transport_retryable_message(
            "request timed out: operation timed out"
        ));
        assert!(is_transport_retryable_message(
            "connection failed: tcp connect error"
        ));
        assert!(!is_transport_retryable_message(
            "HTTP Status Error (400): bad request"
        ));
    }

    #[test]
    fn test_llm_error_display_auth_error_with_status_truncates_body() {
        let body = "secret".repeat(200);
        let error = LLMError::AuthError {
            message: "Unauthorized".to_string(),
            status_code: Some(401),
            response_body: Some(body.clone().into_boxed_str()),
        };
        let display = error.to_string();
        assert!(display.contains("401"));
        assert!(display.contains("truncated"));
        assert_eq!(error.response_body(), Some(body.as_str()));
    }

    #[test]
    fn test_llm_error_display_rate_limit_error_includes_status() {
        let error = LLMError::RateLimitError {
            status_code: 529,
            message: "Overloaded".to_string(),
            response_body: "overload".into(),
            retry_after: Some(Duration::from_secs(30)),
            provider_code: Some("overloaded".into()),
        };
        let display = error.to_string();
        assert!(display.contains("529"));
        assert!(display.contains("overloaded"));
        assert_eq!(error.http_status_code(), Some(529));
    }

    #[test]
    fn test_invalid_request_preserves_response_body() {
        let err = LLMError::InvalidRequest {
            message: "bad request".into(),
            status_code: Some(400),
            response_body: Some(r#"{"error":"details"}"#.into()),
        };
        assert_eq!(err.http_status_code(), Some(400));
        assert_eq!(err.response_body(), Some(r#"{"error":"details"}"#));
    }

    #[test]
    fn test_is_retryable_matrix() {
        assert!(
            LLMError::RateLimitError {
                status_code: 429,
                message: "limit".into(),
                response_body: "body".into(),
                retry_after: None,
                provider_code: None,
            }
            .is_retryable()
        );
        assert!(
            LLMError::HttpStatusError {
                status_code: 503,
                message: "down".into(),
                response_body: "body".into(),
                retry_after: None,
                provider_code: None,
            }
            .is_retryable()
        );
        assert!(
            !LLMError::HttpStatusError {
                status_code: 400,
                message: "bad".into(),
                response_body: "body".into(),
                retry_after: None,
                provider_code: None,
            }
            .is_retryable()
        );
        assert!(!LLMError::Generic("unsupported".into()).is_retryable());
        assert!(LLMError::HttpError("request timed out: elapsed".into()).is_retryable());
    }

    #[test]
    fn test_llm_error_debug_truncates_response_body() {
        let body = "secret".repeat(MAX_ERROR_BODY_DISPLAY_BYTES + 10);
        let error = LLMError::RateLimitError {
            status_code: 429,
            message: "limit".into(),
            response_body: body.clone().into_boxed_str(),
            retry_after: None,
            provider_code: None,
        };
        let debug = format!("{error:?}");
        assert!(debug.contains("truncated"));
        assert!(!debug.contains(&body));
    }

    #[test]
    fn test_from_serde_json_error() {
        let json_str = r#"{"invalid": json}"#;
        let json_error: JsonError =
            serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();

        let llm_error: LLMError = json_error.into();

        match llm_error {
            LLMError::JsonError(msg) => {
                assert!(msg.contains("line"));
                assert!(msg.contains("column"));
            }
            _ => panic!("Expected JsonError"),
        }
    }

    #[test]
    fn test_http_status_code_and_response_body_accessors() {
        let auth = LLMError::AuthError {
            message: "denied".into(),
            status_code: Some(403),
            response_body: Some("body".into()),
        };
        assert_eq!(auth.http_status_code(), Some(403));
        assert_eq!(auth.response_body(), Some("body"));

        let rate_limit = LLMError::RateLimitError {
            status_code: 429,
            message: "limit".into(),
            response_body: "payload".into(),
            retry_after: None,
            provider_code: None,
        };
        assert_eq!(rate_limit.response_body(), Some("payload"));

        let http_status = LLMError::HttpStatusError {
            status_code: 502,
            message: "bad gateway".into(),
            response_body: "html".into(),
            retry_after: None,
            provider_code: None,
        };
        assert_eq!(http_status.http_status_code(), Some(502));
        assert_eq!(http_status.response_body(), Some("html"));

        let format_error = LLMError::ResponseFormatError {
            message: "invalid json".into(),
            raw_response: "not-json".into(),
        };
        assert_eq!(format_error.response_body(), Some("not-json"));
        assert_eq!(LLMError::Generic("x".into()).http_status_code(), None);
        assert_eq!(LLMError::JsonError("parse".into()).response_body(), None);
    }

    #[test]
    fn test_is_transport_retryable_method() {
        assert!(LLMError::HttpError("request timed out: elapsed".into()).is_transport_retryable());
        assert!(!LLMError::Generic("timeout".into()).is_transport_retryable());
    }

    #[test]
    fn test_truncate_for_display_respects_utf8_boundary() {
        let body = format!("{}€{}", "a".repeat(511), "z".repeat(20));
        let truncated = truncate_for_display(&body);
        assert!(truncated.contains("truncated"));
        assert!(std::str::from_utf8(truncated.as_bytes()).is_ok());
    }

    #[test]
    fn test_is_fallbackable_matrix() {
        assert!(is_fallbackable(&LLMError::HttpError("down".into())));
        assert!(is_fallbackable(&LLMError::RateLimitError {
            status_code: 429,
            message: "limit".into(),
            response_body: "body".into(),
            retry_after: None,
            provider_code: None,
        }));
        assert!(!is_fallbackable(&LLMError::missing_api_key("missing")));
        assert!(!is_fallbackable(&LLMError::GuardrailBlocked {
            phase: GuardrailPhase::Input,
            guard: "g".into(),
            rule_id: "r".into(),
            category: "c".into(),
            severity: "high".into(),
            message: "blocked".into(),
        }));
    }

    #[test]
    fn test_llm_error_debug_covers_struct_variants() {
        let cases: Vec<LLMError> = vec![
            LLMError::HttpError("transport".into()),
            LLMError::AuthError {
                message: "denied".into(),
                status_code: Some(401),
                response_body: Some("secret".into()),
            },
            LLMError::HttpStatusError {
                status_code: 500,
                message: "fail".into(),
                response_body: "body".into(),
                retry_after: None,
                provider_code: Some("internal".into()),
            },
            LLMError::InvalidRequest {
                message: "bad".into(),
                status_code: Some(422),
                response_body: Some("details".into()),
            },
            LLMError::ProviderError("provider".into()),
            LLMError::ResponseFormatError {
                message: "parse".into(),
                raw_response: "raw".into(),
            },
            LLMError::Generic("generic".into()),
            LLMError::JsonError("json".into()),
            LLMError::ToolConfigError("tool".into()),
            LLMError::NoToolSupport("tools".into()),
            LLMError::GuardrailBlocked {
                phase: GuardrailPhase::Output,
                guard: "guard".into(),
                rule_id: "rule".into(),
                category: "cat".into(),
                severity: "low".into(),
                message: "msg".into(),
            },
            LLMError::GuardrailExecutionFailed {
                guard: "guard".into(),
                message: "runtime".into(),
            },
        ];

        for error in cases {
            let debug = format!("{error:?}");
            assert!(!debug.is_empty());
        }
    }

    #[test]
    fn test_llm_error_display_covers_remaining_variants() {
        assert!(
            LLMError::HttpError("transport".into())
                .to_string()
                .contains("HTTP Error")
        );

        let status = LLMError::HttpStatusError {
            status_code: 500,
            message: "fail".into(),
            response_body: "body".into(),
            retry_after: Some(Duration::from_secs(120)),
            provider_code: Some("INTERNAL".into()),
        };
        let status_display = status.to_string();
        assert!(status_display.contains("Provider code: INTERNAL"));
        assert!(status_display.contains("Retry-After: 120s"));

        let format_error = LLMError::ResponseFormatError {
            message: "bad json".into(),
            raw_response: "not-json".into(),
        };
        assert!(format_error.to_string().contains("Response Format Error"));
        assert!(format_error.to_string().contains("Raw response"));

        let input_block = LLMError::GuardrailBlocked {
            phase: GuardrailPhase::Input,
            guard: "g".into(),
            rule_id: "r".into(),
            category: "c".into(),
            severity: "high".into(),
            message: "blocked".into(),
        };
        assert!(input_block.to_string().contains("guardrail blocked input"));

        let output_block = LLMError::GuardrailBlocked {
            phase: GuardrailPhase::Output,
            guard: "g".into(),
            rule_id: "r".into(),
            category: "c".into(),
            severity: "high".into(),
            message: "blocked".into(),
        };
        assert!(
            output_block
                .to_string()
                .contains("guardrail blocked output")
        );

        let execution_failed = LLMError::GuardrailExecutionFailed {
            guard: "g".into(),
            message: "runtime".into(),
        };
        assert!(
            execution_failed
                .to_string()
                .contains("guardrail execution failed")
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn test_from_reqwest_connection_error() {
        let client = reqwest::Client::new();
        let err = client
            .get("http://127.0.0.1:1")
            .send()
            .await
            .expect_err("connection should fail");

        let llm_err = LLMError::from(err);
        match llm_err {
            LLMError::HttpError(message) => {
                assert!(message.starts_with("connection failed:"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }
}