rig-core 0.44.0

An opinionated library for building LLM powered applications.
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
//! The provider error type, serializable error reports, and shared retry
//! classifications for the effect protocol. Reports preserve classifications,
//! available provider metadata, and textual source chains.
//!
//! ```
//! use rig_core::error::{ErrorKind, ProviderError};
//!
//! let error = ProviderError::from_http_response(http::StatusCode::TOO_MANY_REQUESTS, "slow down");
//! assert!(error.is_retryable());
//! assert_eq!(error.report().kind, ErrorKind::ProviderResponse);
//! ```

use std::fmt;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::{
    completion::UnsupportedOption,
    http_client,
    memory::MemoryError,
    observe::AdapterErrorBoundary,
    provider_response::ProviderResponseError,
    tool::{ToolErrorKind, ToolExecutionError},
    vector_store::VectorStoreError,
};

/// Normalized classification of an [`ErrorReport`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorKind {
    /// A transport failure that produced no provider reply: a reset
    /// connection, a timeout, a protocol error, an unreadable response. It
    /// never carries a status; a reply the server made, whatever its status,
    /// is [`Self::ProviderResponse`].
    Http,
    /// JSON serialization or deserialization failed.
    Json,
    /// A URL could not be parsed.
    Url,
    /// The request could not be built.
    Request,
    /// The response could not be parsed.
    Response,
    /// The provider reported a failure without a preserved raw response.
    Provider,
    /// The provider replied and its raw response was preserved: a non-2xx
    /// status with a body, a 2xx error envelope, or a non-HTTP transport's
    /// error payload. Status, body, request id and headers are on the report.
    ProviderResponse,
    /// A tool failed; the inner kind is the tool's own classification.
    Tool(ToolErrorKind),
    /// A conversation-memory backend failed.
    MemoryBackend,
    /// A conversation-memory policy or filter rejected the history.
    MemoryPolicy,
    /// An internal invariant was violated.
    Internal,
    /// The operation was cancelled.
    Cancelled,
    /// The operation exceeded its deadline.
    Timeout,
    /// The effect bus's driver is gone: the owner dropped it, so nothing can
    /// serve a dispatch. A lifecycle event; never retryable on the same bus.
    BusClosed,
    /// No handler serves the requested key and effect family on the live bus.
    /// The message identifies the key.
    HandlerUnavailable,
    /// Replay requested a different effect or exhausted the log.
    /// The run fails without retry rather than inventing a recorded answer.
    Divergence,
    /// Policy denied dispatch before handler execution. Not retryable under
    /// the same policy; distinct from program cancellation.
    Denied,
    /// Anything else.
    Other,
}

impl ErrorKind {
    /// Stable snake-case classification code, excluding variant payloads.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Http => "http",
            Self::Json => "json",
            Self::Url => "url",
            Self::Request => "request",
            Self::Response => "response",
            Self::Provider => "provider",
            Self::ProviderResponse => "provider_response",
            Self::Tool(_) => "tool",
            Self::MemoryBackend => "memory_backend",
            Self::MemoryPolicy => "memory_policy",
            Self::Internal => "internal",
            Self::Cancelled => "cancelled",
            Self::Timeout => "timeout",
            Self::BusClosed => "bus_closed",
            Self::HandlerUnavailable => "handler_unavailable",
            Self::Divergence => "divergence",
            Self::Denied => "denied",
            Self::Other => "other",
        }
    }
}

/// A serde-able error crossing a wire boundary.
///
/// Field semantics:
/// - `retryable` is the one policy signal; it is decided at conversion time
///   from the source's own classification (see [`retryable_status`]).
/// - `message` is the source's `Display`; `source_chain` is the `Display` of
///   each `source()` link, outermost first, excluding `message` itself.
/// - `code`, `http_status`, `refusal` are copied when the source had them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorReport {
    /// Normalized classification.
    pub kind: ErrorKind,
    /// Whether the same operation may reasonably be retried.
    pub retryable: bool,
    /// Human-readable description (the source's `Display`).
    pub message: String,
    /// A provider- or tool-specific machine code, when one was reported:
    /// for a provider's reply, the transport's own code when it gave one
    /// apart from the body, else the code the body names
    /// (`provider_response::body_code`).
    pub code: Option<String>,
    /// The HTTP status, when the failure had one.
    pub http_status: Option<u16>,
    /// The failure was an intentional refusal rather than a fault.
    pub refusal: bool,
    /// `Display` of each `source()` link, outermost first.
    pub source_chain: Vec<String>,
    /// The provider's request id, when the failure had a response that
    /// carried one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Preserved provider failure response, including available status, body,
    /// headers, and request ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_response: Option<crate::provider_response::ProviderResponseError>,
}

impl ErrorReport {
    /// Build a report of `kind` with `message` and no other metadata.
    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            retryable: false,
            message: message.into(),
            code: None,
            http_status: None,
            refusal: false,
            source_chain: Vec::new(),
            request_id: None,
            provider_response: None,
        }
    }

    /// Set `retryable`.
    pub fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    /// Set the machine code.
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// Set the HTTP status.
    pub fn with_http_status(mut self, status: u16) -> Self {
        self.http_status = Some(status);
        self
    }

    /// Mark the report as an intentional refusal.
    pub fn refused(mut self) -> Self {
        self.refusal = true;
        self
    }

    /// Attach the provider's request id.
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = Some(request_id.into());
        self
    }

    /// Whether the same operation may reasonably be retried.
    pub const fn is_retryable(&self) -> bool {
        self.retryable
    }
}

impl ErrorReport {
    /// The provider response body preserved on this report, if any.
    pub fn provider_response_body(&self) -> Option<&str> {
        self.provider_response
            .as_ref()
            .map(|response| response.body.as_str())
    }

    /// The preserved provider response body parsed as JSON, when present.
    pub fn provider_response_json(&self) -> Result<Option<serde_json::Value>, serde_json::Error> {
        crate::provider_response::json(self.provider_response_body())
    }

    /// The preserved provider response headers, if any.
    pub fn provider_response_headers(&self) -> Option<&http::HeaderMap> {
        self.provider_response
            .as_ref()
            .and_then(|response| response.headers.as_ref())
    }

    /// The HTTP status this report carries, as a status code.
    pub fn provider_response_status(&self) -> Option<http::StatusCode> {
        self.http_status
            .and_then(|status| http::StatusCode::from_u16(status).ok())
    }

    /// The provider's transport request id, if the failure carried one.
    pub fn provider_request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }
}

impl fmt::Display for ErrorReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

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

/// The one status → retryable table.
///
/// Request Timeout (408), Too Early (425), Too Many Requests (429) and every
/// server error (5xx) are retryable; every other status is not. A missing
/// status decides nothing here: a failure with no status is classified by
/// what it is ([`transient_transport`]), not by what it lacks.
pub const fn retryable_status(status: Option<u16>) -> bool {
    match status {
        None => false,
        Some(408 | 425 | 429) => true,
        Some(s) => s >= 500 && s <= 599,
    }
}

/// Classifies `StreamEnded` and backend `Instance` errors as retryable.
/// Protocol, header, and content-type errors are not retryable. Errors carrying
/// an HTTP status use [`retryable_status`]. This does not guarantee the server
/// has not processed the request.
pub fn transient_transport(error: &http_client::Error) -> bool {
    match error {
        http_client::Error::StreamEnded | http_client::Error::Instance(_) => true,
        http_client::Error::Protocol(_)
        | http_client::Error::InvalidHeaderValue(_)
        | http_client::Error::NoHeaders
        | http_client::Error::InvalidContentType(_) => false,
        http_client::Error::InvalidStatusCodeWithDetails { status, .. } => {
            retryable_status(Some(status.as_u16()))
        }
    }
}

/// Collect the `Display` of each `source()` link below `error`, outermost
/// first.
pub(crate) fn source_chain(error: &(dyn std::error::Error + 'static)) -> Vec<String> {
    let mut chain = Vec::new();
    let mut current = error.source();
    while let Some(source) = current {
        chain.push(source.to_string());
        current = source.source();
    }
    chain
}

/// A boxed request-building failure.
#[cfg(not(target_family = "wasm"))]
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// A boxed request-building failure.
#[cfg(target_family = "wasm")]
pub type BoxError = Box<dyn std::error::Error + 'static>;

/// A request-building failure shared by every clone of the error that holds
/// it.
#[cfg(not(target_family = "wasm"))]
pub type SharedError = Arc<dyn std::error::Error + Send + Sync + 'static>;

/// A request-building failure shared by every clone of the error that holds
/// it.
#[cfg(target_family = "wasm")]
pub type SharedError = Arc<dyn std::error::Error + 'static>;

/// A failed provider operation: completion, embedding, reranking,
/// transcription, image or audio generation, verification, model listing, or
/// context caching.
///
/// The variant is the classification, and each variant maps to one
/// [`ErrorKind`]. A provider's reply is preserved as a
/// [`ProviderResponseError`] with its status, body, headers, and request ID;
/// read it through [`Self::provider_response`] or the accessors below.
///
/// ```
/// use rig_core::error::ProviderError;
///
/// fn log(error: &ProviderError) {
///     if let Some(status) = error.provider_response_status() {
///         // Error envelopes can arrive with successful HTTP statuses.
///         eprintln!("provider returned HTTP {status}");
///     }
///     match error.provider_response_json() {
///         Ok(Some(json)) => eprintln!("provider error payload: {json}"),
///         Ok(None) => eprintln!("no provider response body: {error}"),
///         Err(_) => eprintln!("non-JSON body: {:?}", error.provider_response_body()),
///     }
/// }
/// ```
///
/// Errors are `Clone`: sources are shared, so a stream that already yielded
/// an error can hand the same error to a later caller.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum ProviderError {
    /// A transport failure that produced no provider reply: a reset
    /// connection, a timeout, an unreadable response. A reply the server
    /// made is [`Self::ProviderResponse`].
    Http(Arc<http_client::Error>),
    /// JSON serialization or deserialization failed.
    Json(Arc<serde_json::Error>),
    /// A URL could not be parsed.
    Url(url::ParseError),
    /// The request could not be built.
    Request(SharedError),
    /// The reply decoded but does not answer the request.
    Response(String),
    /// The provider reported a failure without a preserved reply.
    Provider(String),
    /// The provider's reply, preserved: a non-success status with its body, a
    /// 2xx error envelope, or a non-HTTP transport's error payload.
    ProviderResponse(ProviderResponseError),
    /// The provider rejected the configured credentials with 401 or 403.
    InvalidAuthentication(ProviderResponseError),
    /// A request for an existing context-cache handle answered 403 or 404.
    /// The reply's body is the provider's explanation, which can name a
    /// cause other than expiry, such as a credential or quota failure.
    CacheExpired {
        /// The cache handle the request named.
        name: String,
        /// The provider's reply.
        response: ProviderResponseError,
    },
    /// The provider returned vectors of a width other than the one the caller
    /// declared through an embedding wire's `ndims` argument. Raised only
    /// when the width was set explicitly.
    MismatchedDimensions {
        /// Provider whose response disagreed with the declared width.
        provider: String,
        /// Width the caller declared.
        requested: usize,
        /// Width the provider actually returned.
        returned: usize,
    },
    /// A failure a relay delivered as its report, such as a stream relayed
    /// over the effect bus. It reports as the relayed report, unchanged.
    Relayed(Box<ErrorReport>),
    /// The reply stopped before the provider ended it: its frames ran out,
    /// or the runtime stopped, without the provider's end.
    Truncated,
    /// A [`GenerationOptions`](crate::completion::GenerationOptions) field
    /// the wire or model cannot honour, under
    /// [`OnUnsupported::Error`](crate::completion::OnUnsupported::Error).
    UnsupportedOption(UnsupportedOption),
}

impl fmt::Display for ProviderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Http(error) => write!(f, "HttpError: {error}"),
            Self::Json(error) => write!(f, "JsonError: {error}"),
            Self::Url(error) => write!(f, "UrlError: {error}"),
            Self::Request(error) => write!(f, "RequestError: {error}"),
            Self::Response(message) => write!(f, "ResponseError: {message}"),
            Self::Provider(message) => write!(f, "ProviderError: {message}"),
            Self::ProviderResponse(response) => write!(f, "ProviderResponseError: {response}"),
            Self::InvalidAuthentication(response) => {
                write!(f, "invalid authentication: {response}")
            }
            Self::CacheExpired { name, response } => write!(
                f,
                "cached content `{name}` is expired or was deleted: {}",
                response.body
            ),
            Self::MismatchedDimensions {
                provider,
                requested,
                returned,
            } => write!(
                f,
                "{provider} embedding response returned {returned}-dimension vectors, but the \
                 model was created with {requested} dimensions; this provider does not resize \
                 embeddings"
            ),
            Self::Relayed(report) => f.write_str(&report.message),
            Self::Truncated => {
                f.write_str("ResponseError: the reply ended before the provider ended it")
            }
            Self::UnsupportedOption(option) => write!(f, "RequestError: {option}"),
        }
    }
}

/// The source is the shared error itself, not its `Arc`, so callers can
/// downcast it.
impl std::error::Error for ProviderError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Json(error) => Some(&**error),
            Self::Url(error) => Some(error),
            Self::Request(error) => Some(&**error),
            _ => None,
        }
    }
}

impl From<url::ParseError> for ProviderError {
    fn from(error: url::ParseError) -> Self {
        Self::Url(error)
    }
}

impl ProviderError {
    /// A request that could not be built, for the given reason.
    pub fn request(reason: impl Into<BoxError>) -> Self {
        Self::Request(Arc::from(reason.into()))
    }

    /// Preserves the status and verbatim body as [`Self::ProviderResponse`],
    /// including error envelopes returned with 2xx statuses.
    pub fn from_http_response(status: http::StatusCode, body: impl Into<String>) -> Self {
        Self::ProviderResponse(ProviderResponseError::new(status, body))
    }

    /// Preserves a verbatim provider error body with no HTTP status as
    /// [`Self::ProviderResponse`].
    pub fn from_provider_body(body: impl Into<String>) -> Self {
        Self::ProviderResponse(ProviderResponseError::without_status(body))
    }

    /// Converts a non-success reply the transport reported as an error to
    /// [`Self::ProviderResponse`], keeping its status, body, and headers.
    /// Other transport errors become [`Self::Http`].
    pub fn from_transport_error(error: http_client::Error) -> Self {
        match error {
            http_client::Error::InvalidStatusCodeWithDetails {
                status,
                body,
                headers,
            } => Self::from_http_response(status, body).with_response_headers(Some(headers)),
            other => Self::Http(Arc::new(other)),
        }
    }

    /// The classification this error reports as.
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::Http(_) => ErrorKind::Http,
            Self::Json(_) => ErrorKind::Json,
            Self::Url(_) => ErrorKind::Url,
            Self::Request(_) | Self::UnsupportedOption(_) => ErrorKind::Request,
            Self::Response(_) | Self::MismatchedDimensions { .. } | Self::Truncated => {
                ErrorKind::Response
            }
            Self::Provider(_) => ErrorKind::Provider,
            Self::ProviderResponse(_)
            | Self::InvalidAuthentication(_)
            | Self::CacheExpired { .. } => ErrorKind::ProviderResponse,
            Self::Relayed(report) => report.kind,
        }
    }

    /// Classifies transport failures with [`transient_transport`] and
    /// preserved replies with [`ProviderResponseError::is_retryable`]; a
    /// truncated reply is retryable. Every other failure, rejected
    /// credentials and expired caches included, is not retryable.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Http(error) => transient_transport(error),
            Self::ProviderResponse(response) => response.is_retryable(),
            Self::Relayed(report) => report.retryable,
            // A reply cut short, by its transport or its runtime, may end on
            // the next attempt.
            Self::Truncated => true,
            _ => false,
        }
    }

    /// The provider's preserved reply, when this error carries one.
    pub fn provider_response(&self) -> Option<&ProviderResponseError> {
        match self {
            Self::ProviderResponse(response)
            | Self::InvalidAuthentication(response)
            | Self::CacheExpired { response, .. } => Some(response),
            Self::Relayed(report) => report.provider_response.as_ref(),
            _ => None,
        }
    }

    /// The preserved reply's body. An empty body returns `Some("")`, while
    /// [`Self::provider_response_json`] maps it to `Ok(None)`.
    pub fn provider_response_body(&self) -> Option<&str> {
        self.provider_response()
            .map(|response| response.body.as_str())
    }

    /// Parses the preserved reply's body as JSON: `Ok(None)` when there is no
    /// body or it is empty, `Err` when it is not valid JSON.
    pub fn provider_response_json(&self) -> Result<Option<serde_json::Value>, serde_json::Error> {
        crate::provider_response::json(self.provider_response_body())
    }

    /// The preserved reply's HTTP status. It may be 2xx for an error envelope.
    pub fn provider_response_status(&self) -> Option<http::StatusCode> {
        self.provider_response()
            .and_then(|response| response.status)
    }

    /// The provider's transport request ID, when the reply carried one.
    pub fn provider_request_id(&self) -> Option<&str> {
        self.provider_response()
            .and_then(|response| response.provider_request_id.as_deref())
    }

    /// The preserved reply's headers. `None` means not captured, as for
    /// non-HTTP transports and replies built from only a status and body.
    /// This example reads the seconds form of `Retry-After`:
    ///
    /// ```no_run
    /// # use rig_core::error::ProviderError;
    /// # use std::time::Duration;
    /// fn backoff(error: &ProviderError) -> Option<Duration> {
    ///     let seconds = error
    ///         .provider_response_headers()?
    ///         .get(http::header::RETRY_AFTER)?
    ///         .to_str()
    ///         .ok()?
    ///         .parse()
    ///         .ok()?;
    ///     Some(Duration::from_secs(seconds))
    /// }
    /// ```
    pub fn provider_response_headers(&self) -> Option<&http::HeaderMap> {
        self.provider_response()
            .and_then(|response| response.headers.as_ref())
    }

    /// Fills an absent request ID on the preserved reply, ignoring empty
    /// strings.
    pub fn with_provider_request_id(self, request_id: Option<String>) -> Self {
        self.map_response(|response| match response.provider_request_id {
            Some(_) => response,
            None => response.with_provider_request_id(request_id),
        })
    }

    /// Fills absent headers on the preserved reply.
    pub fn with_response_headers(self, headers: Option<http::HeaderMap>) -> Self {
        self.map_response(|response| match (&response.headers, headers) {
            (None, Some(headers)) => response.with_headers(Some(headers)),
            _ => response,
        })
    }

    /// Attaches the HTTP status a transport reported beside a reply preserved
    /// without one, so it classifies by status. A captured status is kept.
    pub fn with_provider_status(self, status: Option<http::StatusCode>) -> Self {
        self.map_response(|response| response.with_status(status))
    }

    /// Attaches the provider's machine-readable code for the failure, such as
    /// a gRPC status name or an AWS exception type.
    pub fn with_provider_code(self, code: Option<String>) -> Self {
        self.map_response(|response| response.with_code(code))
    }

    /// Replaces the preserved reply's transport retry verdict, used when its
    /// status is absent or successful.
    pub fn with_transient(self, transient: Option<bool>) -> Self {
        self.map_response(|response| response.with_transient(transient))
    }

    /// The wire form of this error.
    pub fn report(&self) -> ErrorReport {
        ErrorReport::from(self)
    }

    /// Which boundary produced this error, by its classification.
    pub(crate) fn boundary(&self) -> AdapterErrorBoundary {
        match (self, self.kind()) {
            (Self::Http(error), _) => AdapterErrorBoundary::from_http(error),
            (_, ErrorKind::Json | ErrorKind::Response) => AdapterErrorBoundary::Decode,
            (_, ErrorKind::Provider | ErrorKind::ProviderResponse) => {
                AdapterErrorBoundary::ProviderResponse
            }
            _ => AdapterErrorBoundary::Request,
        }
    }

    fn map_response(
        self,
        map: impl FnOnce(ProviderResponseError) -> ProviderResponseError,
    ) -> Self {
        match self {
            Self::ProviderResponse(response) => Self::ProviderResponse(map(response)),
            Self::InvalidAuthentication(response) => Self::InvalidAuthentication(map(response)),
            Self::CacheExpired { name, response } => Self::CacheExpired {
                name,
                response: map(response),
            },
            // The report restates what it read from the reply it preserves,
            // so what the map fills reaches both. What it held is kept.
            Self::Relayed(mut report) => {
                if let Some(response) = report.provider_response.take() {
                    let response = map(response);
                    report.request_id = report
                        .request_id
                        .or_else(|| response.provider_request_id.clone());
                    report.http_status = report
                        .http_status
                        .or_else(|| response.status.map(|status| status.as_u16()));
                    report.code = report.code.or_else(|| response.machine_code());
                    report.refusal |= response.refusal;
                    report.provider_response = Some(response);
                }
                Self::Relayed(report)
            }
            other => other,
        }
    }
}

impl From<serde_json::Error> for ProviderError {
    fn from(error: serde_json::Error) -> Self {
        Self::Json(Arc::new(error))
    }
}

impl From<BoxError> for ProviderError {
    fn from(error: BoxError) -> Self {
        Self::Request(Arc::from(error))
    }
}

impl From<http_client::Error> for ProviderError {
    fn from(error: http_client::Error) -> Self {
        Self::from_transport_error(error)
    }
}

/// A failure to build a provider request, returned by
/// [`Wire::encode`](crate::wire::Wire::encode). It converts only into
/// [`ProviderError::Request`] or [`ProviderError::UnsupportedOption`], both
/// of kind [`ErrorKind::Request`], so every provider classifies its encode
/// failures alike.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct EncodeError(ProviderError);

impl EncodeError {
    /// A request that could not be built, for the given reason.
    pub fn request(reason: impl Into<BoxError>) -> Self {
        Self(ProviderError::request(reason))
    }

    /// A request that sets an option the wire or model cannot honour.
    pub fn unsupported(option: UnsupportedOption) -> Self {
        Self(ProviderError::UnsupportedOption(option))
    }

    /// The refused option, when this error is a refusal.
    pub fn unsupported_option(&self) -> Option<&UnsupportedOption> {
        match &self.0 {
            ProviderError::UnsupportedOption(option) => Some(option),
            _ => None,
        }
    }
}

impl From<EncodeError> for ProviderError {
    fn from(error: EncodeError) -> Self {
        debug_assert_eq!(error.0.kind(), ErrorKind::Request);
        error.0
    }
}

impl From<http::Error> for EncodeError {
    fn from(error: http::Error) -> Self {
        Self::request(error)
    }
}

impl From<serde_json::Error> for EncodeError {
    fn from(error: serde_json::Error) -> Self {
        Self::request(error)
    }
}

impl From<crate::message::MessageError> for EncodeError {
    fn from(error: crate::message::MessageError) -> Self {
        Self::request(error)
    }
}

impl From<BoxError> for EncodeError {
    fn from(error: BoxError) -> Self {
        Self(ProviderError::from(error))
    }
}

impl From<http::Error> for ProviderError {
    fn from(error: http::Error) -> Self {
        Self::request(error)
    }
}

impl From<&ProviderError> for ErrorReport {
    fn from(error: &ProviderError) -> Self {
        if let ProviderError::Relayed(report) = error {
            return (**report).clone();
        }
        let response = error.provider_response();
        ErrorReport {
            kind: error.kind(),
            retryable: error.is_retryable(),
            message: error.to_string(),
            code: response.and_then(ProviderResponseError::machine_code),
            http_status: response
                .and_then(|response| response.status)
                .map(|status| status.as_u16()),
            refusal: response.is_some_and(|response| response.refusal),
            source_chain: source_chain(error),
            request_id: response.and_then(|response| response.provider_request_id.clone()),
            provider_response: response.cloned(),
        }
    }
}

impl From<ProviderError> for ErrorReport {
    fn from(error: ProviderError) -> Self {
        Self::from(&error)
    }
}

impl ToolExecutionError {
    /// The wire form of this error.
    pub fn report(&self) -> ErrorReport {
        ErrorReport::from(self)
    }
}

impl ToolExecutionError {
    /// Whether the tool may reasonably be re-run: the explicit override when
    /// one was set, else the kind's own default
    /// ([`ToolErrorKind::default_retryable`]); a kind that leaves it to the
    /// tool (`None`) is not retryable on the wire.
    pub fn is_retryable(&self) -> bool {
        self.retryable()
            .or_else(|| self.kind().default_retryable())
            .unwrap_or(false)
    }
}

impl From<&ToolExecutionError> for ErrorReport {
    fn from(error: &ToolExecutionError) -> Self {
        ErrorReport {
            kind: ErrorKind::Tool(error.kind()),
            retryable: error.is_retryable(),
            message: error.message().to_string(),
            code: error.code().map(str::to_string),
            http_status: error.http_status(),
            refusal: error.is_refusal(),
            source_chain: source_chain(error),
            request_id: None,
            provider_response: None,
        }
    }
}

impl From<ToolExecutionError> for ErrorReport {
    fn from(error: ToolExecutionError) -> Self {
        Self::from(&error)
    }
}

/// Rebuilds a tool failure from a dispatch report.
///
/// An [`ErrorKind::Tool`] report keeps its tool kind; other kinds map to the
/// closest [`ToolErrorKind`]. Retryability, code, HTTP status, and refusal are
/// copied, the message is model-visible, and the report is the `source()`.
impl From<ErrorReport> for ToolExecutionError {
    fn from(report: ErrorReport) -> Self {
        let kind = match report.kind {
            ErrorKind::Tool(kind) => kind,
            ErrorKind::Timeout => ToolErrorKind::Timeout,
            ErrorKind::Cancelled => ToolErrorKind::Cancelled,
            ErrorKind::Denied => ToolErrorKind::PermissionDenied,
            ErrorKind::HandlerUnavailable => ToolErrorKind::NotFound,
            ErrorKind::Http => ToolErrorKind::Network,
            ErrorKind::Provider | ErrorKind::ProviderResponse => ToolErrorKind::Provider,
            ErrorKind::Json
            | ErrorKind::Url
            | ErrorKind::Request
            | ErrorKind::Response
            | ErrorKind::MemoryBackend
            | ErrorKind::MemoryPolicy
            | ErrorKind::Internal
            | ErrorKind::BusClosed
            | ErrorKind::Divergence
            | ErrorKind::Other => ToolErrorKind::Other,
        };
        let mut error = if report.refusal {
            ToolExecutionError::refused(report.message.clone())
        } else {
            ToolExecutionError::new(kind, report.message.clone())
        }
        .with_retryable(report.retryable);
        if let Some(code) = &report.code {
            error = error.with_code(code.clone());
        }
        if let Some(status) = report.http_status {
            error = error.with_http_status(status);
        }
        error.with_source(report)
    }
}

impl MemoryError {
    /// The wire form of this error.
    pub fn report(&self) -> ErrorReport {
        ErrorReport::from(self)
    }
}

impl From<&MemoryError> for ErrorReport {
    fn from(error: &MemoryError) -> Self {
        let kind = match error {
            MemoryError::Backend(_) => ErrorKind::MemoryBackend,
            MemoryError::Policy(_) => ErrorKind::MemoryPolicy,
            MemoryError::Internal(_) => ErrorKind::Internal,
        };
        ErrorReport {
            kind,
            retryable: false,
            message: error.to_string(),
            code: None,
            http_status: None,
            refusal: false,
            source_chain: source_chain(error),
            request_id: None,
            provider_response: None,
        }
    }
}

impl From<MemoryError> for ErrorReport {
    fn from(error: MemoryError) -> Self {
        Self::from(&error)
    }
}

impl From<&VectorStoreError> for ErrorReport {
    fn from(error: &VectorStoreError) -> Self {
        let (kind, provider_response) = match error {
            VectorStoreError::EmbeddingError(inner) => {
                return Self {
                    message: error.to_string(),
                    source_chain: source_chain(error),
                    ..Self::from(inner)
                };
            }
            VectorStoreError::JsonError(_) => (ErrorKind::Json, None),
            VectorStoreError::DatastoreError(_) => (ErrorKind::Provider, None),
            VectorStoreError::FilterError(_) | VectorStoreError::SamplesOutOfRange { .. } => {
                (ErrorKind::Request, None)
            }
            VectorStoreError::MissingIdError(_) => (ErrorKind::Response, None),
            VectorStoreError::Http(crate::http_client::Error::InvalidStatusCodeWithDetails {
                status,
                body,
                headers,
            }) => (
                ErrorKind::ProviderResponse,
                Some(
                    crate::provider_response::ProviderResponseError::new(*status, body.clone())
                        .with_headers(Some(headers.clone())),
                ),
            ),
            VectorStoreError::Http(_) => (ErrorKind::Http, None),
            // A store's own non-2xx reply: the server answered, so the status
            // classifies it and its retryability, like any provider reply.
            VectorStoreError::ExternalAPIError(status, body) => (
                ErrorKind::ProviderResponse,
                Some(crate::provider_response::ProviderResponseError::new(
                    *status,
                    body.clone(),
                )),
            ),
        };
        let http_status = provider_response
            .as_ref()
            .and_then(|response| response.status.map(|status| status.as_u16()));
        let retryable = match error {
            VectorStoreError::Http(inner) => transient_transport(inner),
            VectorStoreError::ExternalAPIError(..) => retryable_status(http_status),
            _ => false,
        };
        let code = provider_response
            .as_ref()
            .and_then(|response| response.machine_code());
        ErrorReport {
            kind,
            retryable,
            message: error.to_string(),
            code,
            http_status,
            refusal: provider_response.as_ref().is_some_and(|r| r.refusal),
            source_chain: source_chain(error),
            request_id: None,
            provider_response,
        }
    }
}

impl From<VectorStoreError> for ErrorReport {
    fn from(error: VectorStoreError) -> Self {
        Self::from(&error)
    }
}

// The report is the wire error of the effect protocol: it must cross threads
// and serialize on every target, browser wasm included.
const _: fn() = || {
    fn assert_wire<T: Send + Sync + 'static + Serialize + serde::de::DeserializeOwned>() {}
    assert_wire::<ErrorReport>();
    assert_wire::<ErrorKind>();
};

#[cfg(test)]
mod encode_tests;
#[cfg(test)]
mod tests;