everruns-provider 0.22.0

Provider/LLM abstraction foundation shared by Everruns core and provider crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use std::sync::OnceLock;

#[cfg(feature = "openapi")]
use utoipa::ToSchema;

pub mod codes {
    pub const BUDGET_EXHAUSTED: &str = "budget_exhausted";
    pub const BUDGET_PAUSED: &str = "budget_paused";
    pub const MODEL_UNAVAILABLE: &str = "model_unavailable";
    pub const MODEL_NOT_CONFIGURED: &str = "model_not_configured";
    pub const REQUEST_TOO_LARGE: &str = "request_too_large";
    pub const PROVIDER_RATE_LIMITED: &str = "provider_rate_limited";
    /// Subscription/plan usage limit was reached (e.g. ChatGPT/Codex
    /// `usage_limit_reached`). Distinct from `provider_rate_limited` (a short
    /// transient throttle) because the reset is far in the future (hours) and
    /// carries a concrete `resets_at` timestamp, and distinct from
    /// `provider_quota_exhausted` (billing/credits) because it recovers on its
    /// own at the reset time without operator action.
    pub const PROVIDER_USAGE_LIMIT_REACHED: &str = "provider_usage_limit_reached";
    pub const PROVIDER_MISCONFIGURED: &str = "provider_misconfigured";
    /// Provider account is out of credits/quota (billing). Distinct from
    /// `provider_misconfigured` (bad/missing API key) so operators can tell
    /// "top up the account" apart from "fix the key".
    pub const PROVIDER_QUOTA_EXHAUSTED: &str = "provider_quota_exhausted";
    /// The provider account has not completed a confirmation the model
    /// requires (OpenRouter's 18+ age verification is the canonical case).
    /// Distinct from `provider_misconfigured` (the key is fine) and from
    /// `provider_quota_exhausted` (nothing is owed): it clears only when the
    /// account holder visits the provider's settings page, so the error
    /// carries that URL rather than pointing at support.
    pub const PROVIDER_ATTESTATION_REQUIRED: &str = "provider_attestation_required";
    pub const PROVIDER_UNAVAILABLE: &str = "provider_unavailable";
    pub const PROCESSING_ERROR: &str = "processing_error";
    pub const DEPENDENCY_UNAVAILABLE: &str = "dependency_unavailable";
    pub const INVALID_TOOL_SCHEMA: &str = "invalid_tool_schema";
    pub const MAX_ITERATIONS: &str = "max_iterations";
    pub const SOFT_LIMIT_REACHED: &str = "soft_limit_reached";
    /// A `user_prompt_submit` hook rejected the inbound user message.
    pub const BLOCKED_BY_HOOK: &str = "blocked_by_hook";
}

pub type UserFacingErrorFields = BTreeMap<String, Value>;

/// Message/event metadata keys used to track error disclosure decisions.
pub mod metadata_keys {
    /// Disclosure mode applied when the error surfaced ("generic" | "standard" | "detailed").
    pub const ERROR_DISCLOSURE: &str = "error_disclosure";
    /// The classified error code before disclosure was applied. Differs from
    /// `error_code` only in `generic` mode, where the displayed code collapses
    /// to `processing_error`.
    pub const SOURCE_ERROR_CODE: &str = "source_error_code";
}

/// How much detail about a run-blocking error is shown to session viewers.
///
/// Ordering matters: variants are declared least → most disclosing so that
/// per-message control overrides can be clamped with `min` against the
/// capability-configured ceiling.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub enum ErrorDisclosure {
    /// Collapse every blocking error into one generic, localizable message
    /// (`processing_error`, no fields). For public-facing agents.
    Generic,
    /// Stable error code + structured interpolation fields. Current default.
    #[default]
    Standard,
    /// Standard plus a `detail` field carrying the underlying driver error
    /// text. For trusted surfaces such as coding-agent harnesses.
    Detailed,
}

impl ErrorDisclosure {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "generic" => Some(ErrorDisclosure::Generic),
            "standard" => Some(ErrorDisclosure::Standard),
            "detailed" => Some(ErrorDisclosure::Detailed),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorDisclosure::Generic => "generic",
            ErrorDisclosure::Standard => "standard",
            ErrorDisclosure::Detailed => "detailed",
        }
    }
}

/// Maximum length of the `detail` field attached in `Detailed` mode. Provider
/// error bodies are normally short; this guards against pathological payloads
/// bloating messages and events.
const DETAIL_MAX_CHARS: usize = 1000;

/// Provider quota/billing-exhaustion patterns shared by the string classifier
/// and the driver-boundary semantic classifier (`LlmErrorKind`).
pub fn is_provider_quota_message(message: &str) -> bool {
    let lower = message.to_ascii_lowercase();
    lower.contains("insufficient_quota")
        || lower.contains("insufficient quota")
        || lower.contains("exceeded your current quota")
        || lower.contains("credit_balance_exhausted")
        || lower.contains("credit balance is too low")
}

/// Subscription/plan usage-limit patterns shared by the string classifier and
/// the transient-retry gate. These recover only at a future reset time (hours
/// away), so unlike an ordinary 429 they must not be retried within the driver
/// backoff window nor collapsed into the "wait a moment" rate-limit copy.
///
/// The canonical shape is the ChatGPT/Codex `429` body
/// (`{"error":{"type":"usage_limit_reached", ...}}`), but the match is kept
/// provider-agnostic so any driver surfacing the same wording is covered.
pub fn is_usage_limit_message(message: &str) -> bool {
    let lower = message.to_ascii_lowercase();
    lower.contains("usage_limit_reached")
        || lower.contains("usage limit reached")
        || lower.contains("usage limit has been reached")
}

/// Extract the absolute reset time (`resets_at`, unix seconds) from a usage-limit
/// error body when present. Prefers the absolute `resets_at` field over the
/// relative `resets_in_seconds` because this classifier is clock-free and callers
/// want a stable timestamp they can render in the viewer's timezone.
pub fn parse_usage_limit_reset_at(message: &str) -> Option<i64> {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r#""resets_at"\s*:\s*(?P<resets_at>\d{9,})"#).expect("valid resets_at regex")
    });
    re.captures(message)?
        .name("resets_at")?
        .as_str()
        .parse::<i64>()
        .ok()
}

/// Sentence OpenRouter puts in the human-readable half of an attestation-gate
/// refusal. Matched case-insensitively as the second detection signal, so a
/// gate reported without the `metadata` block is still recognized.
const ATTESTATION_GATE_SENTENCE: &str = "requires you to complete the following before use";

/// Where the account holder clears OpenRouter attestations. Used only when the
/// provider's own message carries no URL — every observed payload does, but the
/// error is worth nothing to a reader without somewhere to go.
const ATTESTATION_CONFIRM_URL_FALLBACK: &str = "https://openrouter.ai/settings/preferences";

/// Bounds on the provider-supplied halves of an attestation gate. Both values
/// are rendered verbatim into every session viewer's transcript, so the payload
/// does not get to decide how much of it lands there. A URL longer than this,
/// or a gate type longer than `MAX_TYPE_CHARS`, is dropped rather than
/// truncated: half a URL is worse than the fallback, and a truncated gate name
/// is not a gate name.
const MAX_CONFIRM_URL_CHARS: usize = 300;
const MAX_ATTESTATION_TYPES: usize = 8;
const MAX_TYPE_CHARS: usize = 64;

/// A provider account attestation gate: the request is refused until the
/// account completes one or more confirmations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttestationRequirement {
    /// One entry per missing confirmation (e.g. `age_18plus`). Deliberately
    /// `String` rather than an enum: providers add gates without notice, and
    /// an unknown type must still reach the reader verbatim.
    pub missing_types: Vec<String>,
    /// Page where the account holder completes the confirmations.
    pub confirm_url: String,
}

impl AttestationRequirement {
    /// A requirement with nothing parsed out of the body — the reader still
    /// gets the confirmation page, which is the actionable half.
    pub fn fallback() -> Self {
        Self {
            missing_types: Vec::new(),
            confirm_url: ATTESTATION_CONFIRM_URL_FALLBACK.to_string(),
        }
    }

    /// Attach this requirement's interpolation fields to a user-facing error.
    /// `missing_types` is omitted rather than sent empty, so a consumer can
    /// tell "no list in the payload" from "an empty list".
    pub fn apply_fields(self, error: UserFacingError) -> UserFacingError {
        let error = error.with_field("confirm_url", self.confirm_url);
        if self.missing_types.is_empty() {
            error
        } else {
            error.with_field("missing_types", self.missing_types)
        }
    }
}

/// Parse an attestation gate out of a provider error body.
///
/// The canonical shape is OpenRouter's `403`:
///
/// ```json
/// {"error":{"message":"This model requires you to complete the following before
///   use: 18+ age confirmation. Confirm at https://openrouter.ai/settings/preferences.",
///   "code":403,"metadata":{"missing_attestation_types":["age_18plus"], …}}}
/// ```
///
/// Matching is driven by the body rather than the HTTP status, the same way
/// [`is_provider_quota_message`] is: a status alone cannot tell this gate apart
/// from an ordinary `403`, and a provider that reports the same gate under a
/// different status should still be recognized. A `403` carrying neither the
/// `missing_attestation_types` list nor the gate sentence does not match.
pub fn parse_attestation_requirement(message: &str) -> Option<AttestationRequirement> {
    // Bodies reach this classifier both raw and JSON-escaped, because a
    // provider error nested inside another JSON envelope arrives with `\"` and
    // `\/` intact. Undoing those two escapes first lets one parser cover both
    // shapes; text without escapes is unchanged by it.
    let message = message.replace("\\\"", "\"").replace("\\/", "/");
    let missing_types = attestation_missing_types(&message).unwrap_or_default();
    let lower = message.to_ascii_lowercase();
    if missing_types.is_empty() && !lower.contains(ATTESTATION_GATE_SENTENCE) {
        return None;
    }
    Some(AttestationRequirement {
        missing_types,
        confirm_url: attestation_confirm_url(&message, &lower)
            .unwrap_or_else(|| ATTESTATION_CONFIRM_URL_FALLBACK.to_string()),
    })
}

/// Whether a provider error body reports an account attestation gate.
pub fn is_attestation_required_message(message: &str) -> bool {
    parse_attestation_requirement(message).is_some()
}

fn attestation_missing_types(message: &str) -> Option<Vec<String>> {
    static LIST: OnceLock<Regex> = OnceLock::new();
    static ITEM: OnceLock<Regex> = OnceLock::new();
    let list = LIST.get_or_init(|| {
        Regex::new(r#""missing_attestation_types"\s*:\s*\[(?P<types>[^\]]*)\]"#)
            .expect("valid missing_attestation_types regex")
    });
    let item =
        ITEM.get_or_init(|| Regex::new(r#""([^"]*)""#).expect("valid attestation type regex"));
    let types = list.captures(message)?.name("types")?.as_str();
    Some(
        item.captures_iter(types)
            .map(|captures| captures[1].to_string())
            // THREAT[TM-WEB-018] These strings come from the provider and are
            // rendered into every session viewer's transcript, so the payload
            // decides neither how many arrive nor how long each one is.
            .filter(|attestation_type| {
                !attestation_type.is_empty() && attestation_type.chars().count() <= MAX_TYPE_CHARS
            })
            .take(MAX_ATTESTATION_TYPES)
            .collect(),
    )
}

/// The confirmation page URL, searched from the gate sentence onward so a URL
/// in the driver's own error prefix (an endpoint, a docs link) can never be
/// mistaken for it. `lower` is the caller's ASCII-lowercased `message`, whose
/// byte offsets line up with it exactly.
fn attestation_confirm_url(message: &str, lower: &str) -> Option<String> {
    static RE: OnceLock<Regex> = OnceLock::new();
    // THREAT[TM-WEB-018] The scheme is pinned to http(s) here, not just where
    // the UI renders it: this URL is provider-controlled and this is the point
    // at which it stops being an opaque blob and becomes something a reader is
    // told to visit.
    let re = RE
        .get_or_init(|| Regex::new(r#"https?://[^\s"'\\<>)]+"#).expect("valid confirm url regex"));
    let from = lower.find(ATTESTATION_GATE_SENTENCE).unwrap_or(0);
    let url = re
        .find(&message[from..])?
        .as_str()
        .trim_end_matches(['.', ',', ';', ':']);
    (!url.is_empty() && url.chars().count() <= MAX_CONFIRM_URL_CHARS).then(|| url.to_string())
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct UserFacingError {
    pub code: String,
    #[serde(default, skip_serializing_if = "UserFacingErrorFields::is_empty")]
    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
    pub fields: UserFacingErrorFields,
}

#[derive(Debug, Clone, Default)]
pub struct UserFacingErrorContext {
    pub provider: Option<String>,
    pub model_id: Option<String>,
    pub retry_after: Option<u64>,
}

impl UserFacingErrorContext {
    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
        self.provider = Some(provider.into());
        self
    }

    pub fn with_model_id(mut self, model_id: impl Into<String>) -> Self {
        self.model_id = Some(model_id.into());
        self
    }

    pub fn with_retry_after(mut self, retry_after: u64) -> Self {
        self.retry_after = Some(retry_after);
        self
    }
}

impl UserFacingError {
    pub fn new(code: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            fields: UserFacingErrorFields::new(),
        }
    }

    pub fn with_field<T: Serialize>(mut self, key: impl Into<String>, value: T) -> Self {
        let value = serde_json::to_value(value).unwrap_or(Value::Null);
        if !value.is_null() {
            self.fields.insert(key.into(), value);
        }
        self
    }

    pub fn with_optional_field<T: Serialize>(
        self,
        key: impl Into<String>,
        value: Option<T>,
    ) -> Self {
        match value {
            Some(value) => self.with_field(key, value),
            None => self,
        }
    }

    pub fn error_fields(&self) -> Option<UserFacingErrorFields> {
        (!self.fields.is_empty()).then_some(self.fields.clone())
    }

    pub fn apply_to_event_fields(
        &self,
        error_code: &mut Option<String>,
        error_fields: &mut Option<UserFacingErrorFields>,
    ) {
        *error_code = Some(self.code.clone());
        *error_fields = self.error_fields();
    }

    pub fn apply_to_message_metadata(&self, metadata: &mut HashMap<String, Value>) {
        metadata.insert("error_code".to_string(), Value::String(self.code.clone()));
        if let Some(fields) = self.error_fields() {
            metadata.insert(
                "error_fields".to_string(),
                serde_json::to_value(fields).unwrap_or(Value::Null),
            );
        } else {
            // Reusing a metadata map must not retain fields from an older,
            // more detailed error after disclosure has removed them.
            metadata.remove("error_fields");
        }
    }

    /// Apply an error-disclosure mode, returning the error as it should be
    /// shown to session viewers. The original (source) error stays available
    /// to the caller for tracking metadata.
    ///
    /// - `Generic` collapses to `processing_error` with no fields.
    /// - `Standard` returns the error unchanged.
    /// - `Detailed` attaches `detail` (the underlying driver error text,
    ///   truncated) as an extra interpolation field.
    pub fn apply_disclosure(&self, mode: ErrorDisclosure, detail: Option<&str>) -> UserFacingError {
        match mode {
            ErrorDisclosure::Generic => UserFacingError::new(codes::PROCESSING_ERROR),
            ErrorDisclosure::Standard => self.clone(),
            ErrorDisclosure::Detailed => {
                let detail = detail.map(str::trim).filter(|d| !d.is_empty());
                match detail {
                    Some(detail) => self
                        .clone()
                        .with_field("detail", truncate_chars(detail, DETAIL_MAX_CHARS)),
                    None => self.clone(),
                }
            }
        }
    }

    /// Record disclosure tracking metadata on a message: the mode that was
    /// applied and the pre-disclosure (source) error code.
    pub fn apply_disclosure_to_message_metadata(
        metadata: &mut HashMap<String, Value>,
        mode: ErrorDisclosure,
        source_code: &str,
    ) {
        metadata.insert(
            metadata_keys::ERROR_DISCLOSURE.to_string(),
            Value::String(mode.as_str().to_string()),
        );
        metadata.insert(
            metadata_keys::SOURCE_ERROR_CODE.to_string(),
            Value::String(source_code.to_string()),
        );
    }

    pub fn fallback_message(&self) -> String {
        self.base_fallback_message()
    }

    fn base_fallback_message(&self) -> String {
        match self.code.as_str() {
            codes::BUDGET_EXHAUSTED => budget_exhausted_message(&self.fields),
            codes::BUDGET_PAUSED => budget_paused_message(&self.fields),
            codes::SOFT_LIMIT_REACHED => string_field(&self.fields, "message")
                .unwrap_or("Soft limit reached.")
                .to_string(),
            codes::MODEL_UNAVAILABLE => {
                if let Some(model_id) = string_field(&self.fields, "model_id") {
                    format!(
                        "The model `{}` is not available. It may have been removed, renamed, or your API key may not have access to it. Please select a different model.",
                        model_id
                    )
                } else {
                    "The selected model is not available. Please select a different model."
                        .to_string()
                }
            }
            codes::MODEL_NOT_CONFIGURED => {
                "No model is configured for this chat. Choose a model or configure a default model, then try again."
                    .to_string()
            }
            codes::REQUEST_TOO_LARGE => {
                "The conversation has become too long for the model to process. Please start a new session or reduce the context size.".to_string()
            }
            codes::PROVIDER_RATE_LIMITED => {
                "Rate limited by the AI provider. Please wait a moment.".to_string()
            }
            codes::PROVIDER_USAGE_LIMIT_REACHED => usage_limit_reached_message(&self.fields),
            codes::PROVIDER_MISCONFIGURED => {
                "There is a misconfiguration with the AI provider. Please contact support."
                    .to_string()
            }
            codes::PROVIDER_QUOTA_EXHAUSTED => {
                "The AI provider account is out of credits or quota. Add credits or raise the provider account limits to continue."
                    .to_string()
            }
            codes::PROVIDER_ATTESTATION_REQUIRED => attestation_required_message(&self.fields),
            codes::PROVIDER_UNAVAILABLE => {
                "The AI provider is experiencing issues. Please try again shortly.".to_string()
            }
            codes::DEPENDENCY_UNAVAILABLE => {
                "Execution stopped because a required dependency is unavailable.".to_string()
            }
            codes::INVALID_TOOL_SCHEMA => {
                "A connected tool uses an input schema that this model provider does not support. Update the integration or choose a different model provider, then try again."
                    .to_string()
            }
            _ => "I encountered an error while processing your request. Please try again later."
                .to_string(),
        }
    }
}

pub fn classify_runtime_error_message(
    error: &str,
    context: &UserFacingErrorContext,
) -> UserFacingError {
    let normalized = trim_error_chain_prefixes(error).trim();
    let lower = normalized.to_ascii_lowercase();

    if let Some(fields) = parse_budget_exhausted_fields(normalized) {
        return UserFacingError {
            code: codes::BUDGET_EXHAUSTED.to_string(),
            fields,
        };
    }

    if normalized.starts_with("Budget exhausted.") {
        return UserFacingError::new(codes::BUDGET_EXHAUSTED);
    }

    if normalized.starts_with("Budget exhausted (") {
        return UserFacingError::new(codes::BUDGET_EXHAUSTED);
    }

    if let Some(fields) = parse_budget_paused_fields(normalized) {
        return UserFacingError {
            code: codes::BUDGET_PAUSED.to_string(),
            fields,
        };
    }

    if normalized.starts_with("Budget paused.") || normalized.starts_with("Budget paused with ") {
        return UserFacingError::new(codes::BUDGET_PAUSED);
    }

    if normalized.starts_with("Budget paused (") || normalized.starts_with("Soft limit reached.") {
        return if normalized.starts_with("Soft limit reached.") {
            UserFacingError::new(codes::SOFT_LIMIT_REACHED).with_field("message", normalized)
        } else {
            UserFacingError::new(codes::BUDGET_PAUSED)
        };
    }

    if let Some(model_id) = normalized.strip_prefix("Model not available: ") {
        return UserFacingError::new(codes::MODEL_UNAVAILABLE).with_field("model_id", model_id);
    }

    if normalized.starts_with("Model not configured") || lower.contains("no model configured") {
        return UserFacingError::new(codes::MODEL_NOT_CONFIGURED);
    }

    if normalized.starts_with("Request too large:")
        || lower.contains("context length")
        || lower.contains("maximum context length")
    {
        return UserFacingError::new(codes::REQUEST_TOO_LARGE)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone());
    }

    if is_invalid_tool_schema_message(&lower) {
        return UserFacingError::new(codes::INVALID_TOOL_SCHEMA)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone())
            .with_optional_field("schema_path", extract_schema_path(normalized));
    }

    // Exhausted provider billing (OpenAI: HTTP 429 + `insufficient_quota`,
    // Anthropic: 400 + "credit balance is too low"). The "(429)" prefix would
    // otherwise route it to PROVIDER_RATE_LIMITED ("wait a moment"), but the
    // condition is non-transient and needs operator action (top up the
    // account or raise limits), so it gets its own code.
    if is_provider_quota_message(normalized) {
        return UserFacingError::new(codes::PROVIDER_QUOTA_EXHAUSTED)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone());
    }

    // Subscription/plan usage limit (e.g. ChatGPT/Codex `usage_limit_reached`).
    // Checked before the generic 429 branch below: the outer error text carries
    // "429 Too Many Requests", which would otherwise route it to the transient
    // "wait a moment" rate-limit copy. This condition instead recovers on its
    // own at `resets_at`, so it gets its own code and carries the reset time.
    if is_usage_limit_message(normalized) {
        return UserFacingError::new(codes::PROVIDER_USAGE_LIMIT_REACHED)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone())
            .with_optional_field("resets_at", parse_usage_limit_reset_at(normalized));
    }

    // Provider account attestation gate (OpenRouter: HTTP 403 carrying
    // `missing_attestation_types`). Checked before the auth branch below: the
    // outer error text contains "(403)", which would route it to
    // PROVIDER_MISCONFIGURED — wrong twice over, because the API key is fine
    // and the only person who can clear the gate is the account holder, not
    // support. Checked before the 429 branch too, so a provider that reports
    // the gate under a throttling status still reaches the right copy.
    if let Some(requirement) = parse_attestation_requirement(normalized) {
        return requirement.apply_fields(
            UserFacingError::new(codes::PROVIDER_ATTESTATION_REQUIRED)
                .with_optional_field("provider", context.provider.clone())
                .with_optional_field("model_id", context.model_id.clone()),
        );
    }

    if lower.contains("(429)")
        || lower.contains("rate limit")
        || lower.contains("too many requests")
    {
        return UserFacingError::new(codes::PROVIDER_RATE_LIMITED)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone())
            .with_optional_field("retry_after", context.retry_after);
    }

    if lower.contains("(401)") || lower.contains("(403)") {
        return UserFacingError::new(codes::PROVIDER_MISCONFIGURED)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone());
    }

    if lower.contains("api key is required")
        || lower.contains("configure the api key")
        || lower.contains("api key missing")
        || lower.contains("missing api key")
        || lower.contains("invalid api key")
    {
        return UserFacingError::new(codes::PROVIDER_MISCONFIGURED)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone());
    }

    if ["(500)", "(502)", "(503)", "(504)", "(529)"]
        .iter()
        .any(|code| lower.contains(code))
    {
        return UserFacingError::new(codes::PROVIDER_UNAVAILABLE)
            .with_optional_field("provider", context.provider.clone())
            .with_optional_field("model_id", context.model_id.clone());
    }

    UserFacingError::new(codes::PROCESSING_ERROR)
        .with_optional_field("provider", context.provider.clone())
        .with_optional_field("model_id", context.model_id.clone())
}

fn is_invalid_tool_schema_message(lower: &str) -> bool {
    lower.contains("invalid_function_parameters")
        || lower.contains("invalid function parameters")
        || (lower.contains("invalid json schema") && lower.contains("$.properties"))
        || lower.contains("invalid tool schema")
}

fn extract_schema_path(message: &str) -> Option<String> {
    let path = message.split_once("Found at ")?.1;
    let path = path
        .split(|character: char| character.is_whitespace() || character == '`')
        .next()?
        .trim_end_matches(['.', ',', ';', ':']);
    (path.starts_with('$')
        && path.len() <= 200
        && path.chars().all(|character| {
            character.is_ascii_alphanumeric()
                || matches!(character, '$' | '.' | '_' | '-' | '[' | ']')
        }))
    .then(|| path.to_string())
}

pub fn trim_error_chain_prefixes(error_chain: &str) -> &str {
    error_chain
        .trim()
        .trim_start_matches("InputAtom execution failed: ")
        .trim_start_matches("ReasonAtom execution failed: ")
        .trim_start_matches("ActAtom execution failed: ")
}

/// Render the copy for a subscription/plan usage-limit error. The `resets_at`
/// field (unix seconds) is rendered as a UTC fallback; clients localize it into
/// the viewer's timezone from the same raw field. When `auto_continue` is set —
/// added by the emit site only when an auto-continue capability is active — the
/// copy promises automatic resumption; otherwise it stays generic.
fn attestation_required_message(fields: &UserFacingErrorFields) -> String {
    let confirm_url =
        string_field(fields, "confirm_url").unwrap_or(ATTESTATION_CONFIRM_URL_FALLBACK);
    let missing_types = fields
        .get("missing_types")
        .and_then(Value::as_array)
        .map(|types| {
            types
                .iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join(", ")
        })
        .filter(|list| !list.is_empty());
    match missing_types {
        Some(list) => format!(
            "The AI provider account has not completed a confirmation this model requires ({list}). Complete it at {confirm_url}, then try again."
        ),
        None => format!(
            "The AI provider account has not completed a confirmation this model requires. Complete it at {confirm_url}, then try again."
        ),
    }
}

fn usage_limit_reached_message(fields: &UserFacingErrorFields) -> String {
    let mut message = String::from("You're out of LLM usage limits.");

    if let Some(resets_at) = number_field(fields, "resets_at")
        && let Some(reset) = chrono::DateTime::from_timestamp(resets_at as i64, 0)
    {
        message.push_str(&format!(
            " Your usage limit resets at {}.",
            reset.format("%H:%M UTC on %b %-d")
        ));
    }

    if bool_field(fields, "auto_continue") {
        message.push_str(" We'll continue work automatically once it resets.");
    }

    message
}

fn budget_exhausted_message(fields: &UserFacingErrorFields) -> String {
    if let (Some(spent), Some(limit), Some(currency)) = (
        number_field(fields, "spent"),
        number_field(fields, "limit"),
        string_field(fields, "currency"),
    ) {
        let comparison = if spent > limit { "exceeded" } else { "reached" };
        return format!(
            "Budget exhausted. {:.2} {} spent {} the {:.2} {} limit. Increase the budget to continue.",
            spent, currency, comparison, limit, currency
        );
    }

    "Budget exhausted. Increase the budget to continue.".to_string()
}

fn budget_paused_message(fields: &UserFacingErrorFields) -> String {
    let spent = number_field(fields, "spent");
    let currency = string_field(fields, "currency");
    let soft_limit = number_field(fields, "soft_limit");

    match (spent, currency, soft_limit) {
        (Some(spent), Some(currency), Some(soft_limit)) => {
            let comparison = if spent > soft_limit {
                "exceeded"
            } else if spent >= soft_limit {
                "reached"
            } else {
                "with"
            };
            if comparison == "with" {
                format!(
                    "Budget paused with {:.2} {} spent. Increase or resume the budget to continue.",
                    spent, currency
                )
            } else {
                format!(
                    "Budget paused. {:.2} {} spent {} the {:.2} {} soft limit. Increase or resume the budget to continue.",
                    spent, currency, comparison, soft_limit, currency
                )
            }
        }
        (Some(spent), Some(currency), None) => format!(
            "Budget paused with {:.2} {} spent. Increase or resume the budget to continue.",
            spent, currency
        ),
        _ => "Budget paused. Increase or resume the budget to continue.".to_string(),
    }
}

fn parse_budget_exhausted_fields(message: &str) -> Option<UserFacingErrorFields> {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(
            r"^Budget exhausted\. (?P<spent>\d+(?:\.\d+)?) (?P<currency>\S+) spent (?:reached|exceeded) the (?P<limit>\d+(?:\.\d+)?) \S+ limit\.",
        )
        .expect("valid budget exhausted regex")
    });
    let caps = re.captures(message)?;
    Some(
        UserFacingErrorFields::new()
            .with_number("spent", caps.name("spent")?.as_str())
            .with_number("limit", caps.name("limit")?.as_str())
            .with_string("currency", caps.name("currency")?.as_str()),
    )
}

fn parse_budget_paused_fields(message: &str) -> Option<UserFacingErrorFields> {
    static SOFT_LIMIT_RE: OnceLock<Regex> = OnceLock::new();
    static SIMPLE_RE: OnceLock<Regex> = OnceLock::new();

    let soft_limit_re = SOFT_LIMIT_RE.get_or_init(|| {
        Regex::new(
            r"^Budget paused\. (?P<spent>\d+(?:\.\d+)?) (?P<currency>\S+) spent (?:reached|exceeded) the (?P<soft_limit>\d+(?:\.\d+)?) \S+ soft limit\.",
        )
        .expect("valid budget paused regex")
    });
    if let Some(caps) = soft_limit_re.captures(message) {
        return Some(
            UserFacingErrorFields::new()
                .with_number("spent", caps.name("spent")?.as_str())
                .with_number("soft_limit", caps.name("soft_limit")?.as_str())
                .with_string("currency", caps.name("currency")?.as_str()),
        );
    }

    let simple_re = SIMPLE_RE.get_or_init(|| {
        Regex::new(r"^Budget paused with (?P<spent>\d+(?:\.\d+)?) (?P<currency>\S+) spent\.")
            .expect("valid budget paused simple regex")
    });
    let caps = simple_re.captures(message)?;
    Some(
        UserFacingErrorFields::new()
            .with_number("spent", caps.name("spent")?.as_str())
            .with_string("currency", caps.name("currency")?.as_str()),
    )
}

fn string_field<'a>(fields: &'a UserFacingErrorFields, key: &str) -> Option<&'a str> {
    fields.get(key)?.as_str()
}

fn bool_field(fields: &UserFacingErrorFields, key: &str) -> bool {
    fields.get(key).and_then(Value::as_bool).unwrap_or(false)
}

fn truncate_chars(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_string();
    }
    let truncated: String = value.chars().take(max_chars).collect();
    format!("{truncated}\u{2026}")
}

fn number_field(fields: &UserFacingErrorFields, key: &str) -> Option<f64> {
    match fields.get(key)? {
        Value::Number(number) => number.as_f64(),
        Value::String(value) => value.parse().ok(),
        _ => None,
    }
}

trait ErrorFieldsExt {
    fn with_string(self, key: &str, value: &str) -> Self;
    fn with_number(self, key: &str, value: &str) -> Self;
}

impl ErrorFieldsExt for UserFacingErrorFields {
    fn with_string(mut self, key: &str, value: &str) -> Self {
        self.insert(key.to_string(), Value::String(value.to_string()));
        self
    }

    fn with_number(mut self, key: &str, value: &str) -> Self {
        if let Ok(number) = value.parse::<f64>()
            && let Some(json_number) = serde_json::Number::from_f64(number)
        {
            self.insert(key.to_string(), Value::Number(json_number));
        }
        self
    }
}

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

    fn wire(error: &UserFacingError) -> Value {
        serde_json::to_value(error).unwrap()
    }
    fn context() -> UserFacingErrorContext {
        UserFacingErrorContext::default()
            .with_provider("provider")
            .with_model_id("model")
            .with_retry_after(7)
    }

    #[test]
    fn quota_classification_preserves_context_without_raw_payload_or_retry_delay() {
        for message in [
            "ReasonAtom execution failed: OpenAI API error (429): {\"error\":{\"type\":\"insufficient_quota\",\"message\":\"You exceeded your current quota\"}}",
            "LLM error: insufficient_quota: You exceeded your current quota.",
            "credit_balance_exhausted: secret=hidden",
            "Anthropic API error (400): Your credit balance is too low to access the Anthropic API.",
            "INSUFFICIENT QUOTA",
        ] {
            let error = classify_runtime_error_message(message, &context());
            assert_eq!(
                wire(&error),
                json!({"code":"provider_quota_exhausted","fields":{"provider":"provider","model_id":"model"}})
            );
            assert_eq!(
                error.fallback_message(),
                "The AI provider account is out of credits or quota. Add credits or raise the provider account limits to continue."
            );
            assert_eq!(
                wire(&classify_runtime_error_message(
                    message,
                    &UserFacingErrorContext::default()
                )),
                json!({"code":"provider_quota_exhausted"})
            );
        }
    }

    #[test]
    fn ordinary_classification_has_exact_code_and_allowed_context_fields() {
        for (message, expected) in [
            (
                "OpenAI API error (429): rate limit exceeded",
                json!({"code":"provider_rate_limited","fields":{"provider":"provider","model_id":"model","retry_after":7}}),
            ),
            (
                "LLM error: API key is required. Configure the API key in provider settings.",
                json!({"code":"provider_misconfigured","fields":{"provider":"provider","model_id":"model"}}),
            ),
            (
                "ReasonAtom execution failed: Model not configured",
                json!({"code":"model_not_configured"}),
            ),
            (
                "ActAtom execution failed: Model not available: retired-model",
                json!({"code":"model_unavailable","fields":{"model_id":"retired-model"}}),
            ),
            (
                "Request too large: context length",
                json!({"code":"request_too_large","fields":{"provider":"provider","model_id":"model"}}),
            ),
            (
                "provider error (503)",
                json!({"code":"provider_unavailable","fields":{"provider":"provider","model_id":"model"}}),
            ),
            (
                "unknown raw error secret=hidden",
                json!({"code":"processing_error","fields":{"provider":"provider","model_id":"model"}}),
            ),
        ] {
            assert_eq!(
                wire(&classify_runtime_error_message(message, &context())),
                expected,
                "{message}"
            );
        }
        assert_eq!(
            UserFacingError::new("model_not_configured").fallback_message(),
            "No model is configured for this chat. Choose a model or configure a default model, then try again."
        );
    }

    #[test]
    fn budget_fields_drive_exact_exhausted_and_paused_copy() {
        let error = classify_runtime_error_message(
            "ReasonAtom execution failed: Budget exhausted. 12.50 usd spent exceeded the 10.00 usd limit. Increase the budget to continue.",
            &context(),
        );
        assert_eq!(
            wire(&error),
            json!({"code":"budget_exhausted","fields":{"spent":12.5,"limit":10.0,"currency":"usd"}})
        );
        assert_eq!(
            error.fallback_message(),
            "Budget exhausted. 12.50 usd spent exceeded the 10.00 usd limit. Increase the budget to continue."
        );
        for (spent, expected) in [
            (
                4.0,
                "Budget paused with 4.00 tokens spent. Increase or resume the budget to continue.",
            ),
            (
                5.0,
                "Budget paused. 5.00 tokens spent reached the 5.00 tokens soft limit. Increase or resume the budget to continue.",
            ),
            (
                6.0,
                "Budget paused. 6.00 tokens spent exceeded the 5.00 tokens soft limit. Increase or resume the budget to continue.",
            ),
        ] {
            let error = UserFacingError::new("budget_paused")
                .with_field("spent", spent)
                .with_field("soft_limit", 5.0)
                .with_field("currency", "tokens");
            assert_eq!(error.fallback_message(), expected);
        }
        assert_eq!(
            UserFacingError::new("budget_paused").fallback_message(),
            "Budget paused. Increase or resume the budget to continue."
        );
    }

    #[test]
    fn schema_rejections_only_expose_safe_bounded_paths() {
        let path200 = format!("$.{}", "a".repeat(198));
        let path201 = format!("$.{}", "a".repeat(199));
        for (path, expected_path) in [
            (
                "$.properties.email.pattern",
                Some("$.properties.email.pattern"),
            ),
            ("$.properties.email.pattern?<token>", None),
            (path200.as_str(), Some(path200.as_str())),
            (path201.as_str(), None),
        ] {
            let error = classify_runtime_error_message(
                &format!(
                    "Invalid JSON schema at $.properties: regex lookaround is unsupported. Found at {path}."
                ),
                &context(),
            );
            let mut fields = json!({"provider":"provider","model_id":"model"});
            if let Some(path) = expected_path {
                fields["schema_path"] = json!(path);
            }
            assert_eq!(
                wire(&error),
                json!({"code":"invalid_tool_schema","fields":fields})
            );
            assert_eq!(
                error.fallback_message(),
                "A connected tool uses an input schema that this model provider does not support. Update the integration or choose a different model provider, then try again."
            );
        }
    }

    #[test]
    fn usage_limits_have_exact_reset_copy_and_explicit_auto_continue_policy() {
        let error = classify_runtime_error_message(
            "Codex API error (429 Too Many Requests): {\"error\":{\"type\":\"usage_limit_reached\",\"resets_at\":1783767823,\"resets_in_seconds\":12337}}",
            &context(),
        );
        assert_eq!(
            wire(&error),
            json!({"code":"provider_usage_limit_reached","fields":{"provider":"provider","model_id":"model","resets_at":1783767823}})
        );
        assert_eq!(
            error.fallback_message(),
            "You're out of LLM usage limits. Your usage limit resets at 11:03 UTC on Jul 11."
        );
        assert_eq!(
            error
                .clone()
                .with_field("auto_continue", true)
                .fallback_message(),
            "You're out of LLM usage limits. Your usage limit resets at 11:03 UTC on Jul 11. We'll continue work automatically once it resets."
        );
        assert_eq!(
            error
                .clone()
                .with_field("auto_continue", false)
                .fallback_message(),
            error.fallback_message()
        );
        let no_reset = classify_runtime_error_message(
            "Some Provider API error (429): usage limit reached",
            &UserFacingErrorContext::default(),
        );
        assert_eq!(
            wire(&no_reset),
            json!({"code":"provider_usage_limit_reached"})
        );
        assert_eq!(
            no_reset.fallback_message(),
            "You're out of LLM usage limits."
        );
    }

    #[test]
    fn disclosure_modes_preserve_only_their_allowed_fields() {
        let error = UserFacingError::new("provider_quota_exhausted")
            .with_field("provider", "openai")
            .with_field("model_id", "model");
        let detail = " Authorization: Bearer synthetic-secret ";
        let generic = error.apply_disclosure(ErrorDisclosure::Generic, Some(detail));
        assert_eq!(wire(&generic), json!({"code":"processing_error"}));
        assert_eq!(
            generic.fallback_message(),
            "I encountered an error while processing your request. Please try again later."
        );
        assert_eq!(
            error.apply_disclosure(ErrorDisclosure::Standard, Some(detail)),
            error
        );
        let detailed = error.apply_disclosure(ErrorDisclosure::Detailed, Some(detail));
        assert_eq!(
            wire(&detailed),
            json!({"code":"provider_quota_exhausted","fields":{"provider":"openai","model_id":"model","detail":"Authorization: Bearer synthetic-secret"}})
        );
        assert_eq!(
            detailed.fallback_message(),
            "The AI provider account is out of credits or quota. Add credits or raise the provider account limits to continue."
        );
        for empty in [None, Some(""), Some(" \n\t")] {
            assert_eq!(
                error.apply_disclosure(ErrorDisclosure::Detailed, empty),
                error
            );
        }
    }

    #[test]
    fn detailed_disclosure_has_literal_unicode_character_boundary() {
        let error = UserFacingError::new("processing_error");
        for length in [999, 1000, 1001] {
            let input = "🦀".repeat(length);
            let expected = if length <= 1000 {
                input.clone()
            } else {
                format!("{}…", "🦀".repeat(1000))
            };
            assert_eq!(
                wire(&error.apply_disclosure(ErrorDisclosure::Detailed, Some(&input))),
                json!({"code":"processing_error","fields":{"detail":expected}})
            );
        }
    }

    #[test]
    fn disclosure_parse_and_ordering() {
        assert_eq!(
            ErrorDisclosure::parse("Generic"),
            Some(ErrorDisclosure::Generic)
        );
        assert_eq!(
            ErrorDisclosure::parse("detailed"),
            Some(ErrorDisclosure::Detailed)
        );
        assert_eq!(ErrorDisclosure::parse("nope"), None);
        assert!(ErrorDisclosure::Generic < ErrorDisclosure::Standard);
        assert!(ErrorDisclosure::Standard < ErrorDisclosure::Detailed);
        assert_eq!(ErrorDisclosure::default(), ErrorDisclosure::Standard);
    }

    #[test]
    fn applying_error_replaces_owned_metadata_and_clears_previous_detail() {
        let mut metadata = HashMap::from([
            ("other".into(), json!("preserve")),
            (
                "error_fields".into(),
                json!({"detail":"old-private-detail"}),
            ),
            ("error_code".into(), json!("old-code")),
        ]);
        let error = UserFacingError::new("provider_rate_limited").with_field("retry_after", 7);
        error.apply_to_message_metadata(&mut metadata);
        assert_eq!(
            metadata,
            HashMap::from([
                ("other".into(), json!("preserve")),
                ("error_code".into(), json!("provider_rate_limited")),
                ("error_fields".into(), json!({"retry_after":7}))
            ])
        );
        let generic = error.apply_disclosure(ErrorDisclosure::Generic, None);
        generic.apply_to_message_metadata(&mut metadata);
        assert_eq!(
            metadata,
            HashMap::from([
                ("other".into(), json!("preserve")),
                ("error_code".into(), json!("processing_error"))
            ])
        );
        let mut code = Some("old-code".into());
        let mut fields = Some(BTreeMap::from([(
            "detail".into(),
            json!("old-private-detail"),
        )]));
        generic.apply_to_event_fields(&mut code, &mut fields);
        assert_eq!((code, fields), (Some("processing_error".into()), None));
        UserFacingError::apply_disclosure_to_message_metadata(
            &mut metadata,
            ErrorDisclosure::Generic,
            "provider_rate_limited",
        );
        assert_eq!(
            metadata,
            HashMap::from([
                ("other".into(), json!("preserve")),
                ("error_code".into(), json!("processing_error")),
                ("error_disclosure".into(), json!("generic")),
                ("source_error_code".into(), json!("provider_rate_limited"))
            ])
        );
    }
}