zai-rs 0.2.0

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

use std::sync::{Arc, LazyLock};

use regex::Regex;
use thiserror::Error;

/// Pre-compiled regex patterns for sensitive data masking (avoids recompilation
/// on every call)
static API_KEY_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b[a-zA-Z0-9_-]{3,}\.[a-zA-Z0-9_-]{10,}\b").expect("invalid regex")
});

static SENSITIVE_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    vec![
        (
            Regex::new(r"(?i)(api[_-]?key\s*[=:]\s*)[^\s,]+").expect("invalid regex"),
            "$1[FILTERED]",
        ),
        (
            Regex::new(r"(?i)(password\s*[=:]\s*)[^\s,]+").expect("invalid regex"),
            "$1[FILTERED]",
        ),
        (
            Regex::new(r"(?i)(token\s*[=:]\s*)[^\s,]+").expect("invalid regex"),
            "$1[FILTERED]",
        ),
        (
            Regex::new(r"(?i)(secret\s*[=:]\s*)[^\s,]+").expect("invalid regex"),
            "$1[FILTERED]",
        ),
        (
            Regex::new(r"(?i)(bearer\s+[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)").expect("invalid regex"),
            "bearer [FILTERED]",
        ),
        (
            Regex::new(r"(?i)(authorization\s*:\s*Bearer\s+)[^\s,]+").expect("invalid regex"),
            "$1[FILTERED]",
        ),
    ]
});

static CONTAINS_SENSITIVE_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    vec![
        Regex::new(r"(?i)api[_-]?key\s*[=:]").expect("invalid regex"),
        Regex::new(r"(?i)password\s*[=:]").expect("invalid regex"),
        Regex::new(r"(?i)token\s*[=:]").expect("invalid regex"),
        Regex::new(r"(?i)secret\s*[=:]").expect("invalid regex"),
        Regex::new(r"(?i)authorization\s*:\s*Bearer").expect("invalid regex"),
    ]
});

/// Masks sensitive information in text for secure logging
///
/// This function filters out potentially sensitive data such as API keys,
/// passwords, and tokens from log messages.
///
/// # Arguments
///
/// * `text` - The text to filter
///
/// # Returns
///
/// Text with sensitive information masked as `[FILTERED]`
///
/// # Patterns Masked
///
/// - API keys (format: `id.secret` where id ≥ 3 chars, secret ≥ 10 chars)
/// - Password fields
/// - Token values
/// - Secret fields
/// - Bearer tokens
/// - Authorization headers
///
/// # Example
///
/// ```
/// use zai_rs::client::error::mask_sensitive_info;
///
/// // API key requires secret >= 10 chars
/// let text = "API key: abc123.abcdefghijklmnopqrstuvwxyz, password: secret123";
/// let filtered = mask_sensitive_info(text);
/// assert!(filtered.contains("[FILTERED]"));
/// assert!(!filtered.contains("abc123"));
/// ```
pub fn mask_sensitive_info(text: &str) -> String {
    let mut result = API_KEY_PATTERN.replace_all(text, "[FILTERED]").to_string();

    for (re, replacement) in SENSITIVE_PATTERNS.iter() {
        result = re.replace_all(&result, *replacement).to_string();
    }

    result
}

/// Masks API keys in text
///
/// A specialized function that only masks API keys following the ZhipuAI
/// format.
pub fn mask_api_key(text: &str) -> String {
    API_KEY_PATTERN.replace_all(text, "[FILTERED]").to_string()
}

/// Checks if text contains sensitive information patterns
pub fn contains_sensitive_info(text: &str) -> bool {
    if API_KEY_PATTERN.is_match(text) {
        return true;
    }

    CONTAINS_SENSITIVE_PATTERNS
        .iter()
        .any(|re| re.is_match(text))
}

/// Validates Zhipu AI API key format
///
/// Zhipu AI API keys follow the format: `<id>.<secret>`
/// where both parts are alphanumeric strings.
///
/// # Arguments
///
/// * `api_key` - The API key to validate
///
/// # Returns
///
/// * `Ok(())` if API key is valid
/// * `Err(ZaiError)` if API key is invalid
///
/// # Example
///
/// ```
/// use zai_rs::client::error::validate_api_key;
///
/// // Valid API key (id >= 3 chars, secret >= 10 chars)
/// assert!(validate_api_key("abc123.abcdefghijklmnopqrstuvwxyz").is_ok());
/// assert!(validate_api_key("").is_err());
/// assert!(validate_api_key("invalid").is_err());
/// ```
pub fn validate_api_key(api_key: &str) -> ZaiResult<()> {
    if api_key.is_empty() {
        return Err(ZaiError::ApiError {
            code: 1200,
            message: "API key cannot be empty".to_string(),
        });
    }

    let parts: Vec<&str> = api_key.split('.').collect();
    if parts.len() != 2 {
        return Err(ZaiError::ApiError {
            code: 1001,
            message: "API key must be in format '<id>.<secret>'".to_string(),
        });
    }

    let (id, secret) = (parts[0], parts[1]);

    if id.is_empty() || secret.is_empty() {
        return Err(ZaiError::ApiError {
            code: 1200,
            message: "API key id and secret must not be empty".to_string(),
        });
    }

    // Check if parts contain only valid characters (alphanumeric and some special
    // chars)
    let valid_chars = |s: &str| -> bool {
        s.chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    };

    if !valid_chars(id) || !valid_chars(secret) {
        return Err(ZaiError::ApiError {
            code: 1200,
            message: "API key contains invalid characters".to_string(),
        });
    }

    // Check reasonable length (id should be at least 3 chars, secret at least 10
    // chars)
    if id.len() < 3 {
        return Err(ZaiError::ApiError {
            code: 1200,
            message: "API key id is too short".to_string(),
        });
    }

    if secret.len() < 10 {
        return Err(ZaiError::ApiError {
            code: 1200,
            message: "API key secret is too short".to_string(),
        });
    }

    Ok(())
}

/// Reserved error-code constants for failures originating inside the SDK
/// itself (client-side validation, I/O, timeouts, external/toolkit calls).
///
/// These never overlap with codes emitted by the Zhipu AI API (documented
/// range `1000`–`1499`). Every value lives in the reserved `9000`–`9999`
/// band, so a caller can distinguish "the server rejected this"
/// (`1000`–`1499`) from "the SDK failed before/after the server replied"
/// (`9000`–`9999`) via [`ZaiError::code`] / [`ZaiError::is_sdk_error`].
pub mod codes {
    /// Generic client-side validation failure (bad argument shape, …).
    pub const SDK_VALIDATION: u16 = 9001;

    /// Client-side configuration error (bad base URL, missing value, …).
    pub const SDK_CONFIG: u16 = 9600;

    /// A local file referenced by the request does not exist.
    pub const SDK_FILE_NOT_FOUND: u16 = 9100;

    /// A local file exceeds the SDK/enforced size limit.
    pub const SDK_FILE_TOO_LARGE: u16 = 9101;

    /// The file type/extension is not supported by the target tool.
    pub const SDK_FILE_TYPE_UNSUPPORTED: u16 = 9102;

    /// Generic local I/O failure (read/write/permission, …).
    pub const SDK_IO: u16 = 9400;

    /// A client-side timeout (e.g. polling an async task for too long).
    pub const SDK_TIMEOUT: u16 = 9300;

    /// A failure reported by an external/toolkit source (RMCP, function tool).
    pub const SDK_EXTERNAL_TOOL: u16 = 9500;
}

/// Main error type for the ZAI-RS SDK
#[derive(Error, Debug)]
pub enum ZaiError {
    /// HTTP status errors
    #[error("HTTP error [{status}]: {message}")]
    HttpError { status: u16, message: String },

    /// Authentication and authorization errors
    #[error("Authentication error [{code}]: {message}")]
    AuthError { code: u16, message: String },

    /// Account-related errors
    #[error("Account error [{code}]: {message}")]
    AccountError { code: u16, message: String },

    /// API call errors
    #[error("API error [{code}]: {message}")]
    ApiError { code: u16, message: String },

    /// Rate limiting and quota errors
    #[error("Rate limit error [{code}]: {message}")]
    RateLimitError { code: u16, message: String },

    /// Content policy errors
    #[error("Content policy error [{code}]: {message}")]
    ContentPolicyError { code: u16, message: String },

    /// File processing errors
    #[error("File error [{code}]: {message}")]
    FileError { code: u16, message: String },

    /// Network/IO errors (wrapped in Arc for Clone support)
    #[error("Network error: {0}")]
    NetworkError(Arc<reqwest::Error>),

    /// JSON parsing errors (wrapped in Arc for Clone support)
    #[error("JSON error: {0}")]
    JsonError(Arc<serde_json::Error>),

    /// Realtime (WebSocket) transport errors — wrapped in `Arc` so the variant
    /// stays `Clone`-able. See [`RealtimeErrorKind`] for the breakdown.
    #[error("Realtime error: {0}")]
    RealtimeError(Arc<RealtimeErrorKind>),

    /// Realtime authentication / JWT errors (bad API-key shape, signing
    /// failure, token rejected during the WebSocket handshake).
    #[error("Realtime auth error: {0}")]
    RealtimeAuthError(String),

    /// Other errors
    #[error("Unknown error [{code}]: {message}")]
    Unknown { code: u16, message: String },
}

/// Concrete error categories for the realtime (WebSocket) transport.
///
/// Kept separate from [`ZaiError`] so callers can introspect the failure mode
/// without matching on the full enum, and so the realtime module can construct
/// rich errors without touching HTTP-specific machinery.
#[derive(Debug, thiserror::Error)]
pub enum RealtimeErrorKind {
    /// Low-level WebSocket error (connect/handshake/read/write). The original
    /// `tungstenite` error is kept as the `#[source]` so the full chain
    /// survives propagation.
    #[error("websocket: {source}")]
    WebSocket {
        /// The underlying tungstenite error.
        #[source]
        source: tokio_tungstenite::tungstenite::Error,
    },

    /// (De)serialization of a realtime event failed.
    #[error("serialize: {source}")]
    Serialize {
        #[source]
        source: serde_json::Error,
    },

    /// Protocol violation — unexpected or malformed server event.
    #[error("protocol: {0}")]
    Protocol(String),

    /// The server emitted an `error` event.
    #[error("server error event [code={code:?}]: {message}")]
    ServerEvent {
        /// Machine-readable error code (may be numeric or textual).
        code: String,
        /// Human-readable error message.
        message: String,
    },

    /// The WebSocket session has been closed.
    #[error("session closed")]
    Closed,
}

impl ZaiError {
    /// Convert an HTTP status code and API error response to a ZaiError
    pub fn from_api_response(status: u16, api_code: u16, api_message: String) -> Self {
        if api_code != 0 {
            return match api_code {
                // Authentication errors
                1000..=1004 | 1100 => ZaiError::AuthError {
                    code: api_code,
                    message: api_message,
                },
                // Account/package/balance errors
                1110..=1121 => ZaiError::AccountError {
                    code: api_code,
                    message: api_message,
                },
                // API call/validation errors
                1200..=1234 => ZaiError::ApiError {
                    code: api_code,
                    message: api_message,
                },
                // Rate limiting and package access pressure/fair-use errors
                1300..=1313 => ZaiError::RateLimitError {
                    code: api_code,
                    message: api_message,
                },
                // File processing errors
                1400..=1499 => ZaiError::FileError {
                    code: api_code,
                    message: api_message,
                },
                _ => ZaiError::Unknown {
                    code: api_code,
                    message: if api_message.is_empty() {
                        "Unknown error".to_string()
                    } else {
                        api_message
                    },
                },
            };
        }

        // Fall back to HTTP status when no business code is present.
        match status {
            400 => ZaiError::HttpError {
                status,
                message: if api_message.is_empty() {
                    "Bad request - check your parameters".to_string()
                } else {
                    api_message
                },
            },
            401 => ZaiError::HttpError {
                status,
                message: "Unauthorized - check your API key".to_string(),
            },
            404 => ZaiError::HttpError {
                status,
                message: "Not found - requested resource doesn't exist".to_string(),
            },
            429 => ZaiError::HttpError {
                status,
                message: if api_message.is_empty() {
                    "Too many requests - rate limit exceeded".to_string()
                } else {
                    api_message
                },
            },
            434 => ZaiError::HttpError {
                status,
                message: "No API permission - feature not available".to_string(),
            },
            435 => ZaiError::HttpError {
                status,
                message: "File size exceeds 100MB limit".to_string(),
            },
            500 => ZaiError::HttpError {
                status,
                message: "Internal server error - try again later".to_string(),
            },
            _ => ZaiError::Unknown {
                code: status,
                message: if api_message.is_empty() {
                    "Unknown error".to_string()
                } else {
                    api_message
                },
            },
        }
    }

    /// Check if the error is a rate limit error
    pub fn is_rate_limit(&self) -> bool {
        matches!(self, ZaiError::RateLimitError { .. })
    }

    /// Check if the error is an authentication error
    pub fn is_auth_error(&self) -> bool {
        matches!(self, ZaiError::AuthError { .. })
    }

    /// Check if the error is a client error (4xx)
    pub fn is_client_error(&self) -> bool {
        match self {
            ZaiError::HttpError { status, .. } => *status >= 400 && *status < 500,
            ZaiError::AuthError { .. }
            | ZaiError::AccountError { .. }
            | ZaiError::ApiError { .. }
            | ZaiError::RateLimitError { .. }
            | ZaiError::ContentPolicyError { .. }
            | ZaiError::FileError { .. }
            | ZaiError::RealtimeAuthError(_) => true,
            ZaiError::RealtimeError(kind) => match kind.as_ref() {
                // Protocol/serialize/server-event failures are client-caused;
                // transport/closure are not necessarily so.
                RealtimeErrorKind::Protocol(_)
                | RealtimeErrorKind::Serialize { .. }
                | RealtimeErrorKind::ServerEvent { .. } => true,
                RealtimeErrorKind::WebSocket { .. } | RealtimeErrorKind::Closed => false,
            },
            _ => false,
        }
    }

    /// Check if the error is a server error (5xx)
    pub fn is_server_error(&self) -> bool {
        match self {
            ZaiError::HttpError { status, .. } => *status >= 500,
            ZaiError::Unknown { code, .. } => *code >= 500,
            _ => false,
        }
    }

    /// Whether this error originates from the SDK itself rather than the API.
    ///
    /// True iff [`code`](Self::code) is in the reserved `9000`–`9999` band
    /// (see [`codes`]). Variants without a numeric code
    /// ([`NetworkError`](Self::NetworkError), [`JsonError`](Self::JsonError),
    /// [`RealtimeError`](Self::RealtimeError)) return `false`.
    pub fn is_sdk_error(&self) -> bool {
        self.code().is_some_and(|c| (9000..=9999).contains(&c))
    }

    /// Get a compact representation of error suitable for logging
    pub fn compact(&self) -> String {
        match self {
            ZaiError::HttpError { status, message } => {
                format!("HTTP[{}]: {}", status, message)
            },
            ZaiError::AuthError { code, message } => {
                format!("AUTH[{}]: {}", code, message)
            },
            ZaiError::AccountError { code, message } => {
                format!("ACCOUNT[{}]: {}", code, message)
            },
            ZaiError::ApiError { code, message } => {
                format!("API[{}]: {}", code, message)
            },
            ZaiError::RateLimitError { code, message } => {
                format!("RATE_LIMIT[{}]: {}", code, message)
            },
            ZaiError::ContentPolicyError { code, message } => {
                format!("POLICY[{}]: {}", code, message)
            },
            ZaiError::FileError { code, message } => {
                format!("FILE[{}]: {}", code, message)
            },
            ZaiError::NetworkError(err) => {
                format!("NETWORK: {}", err)
            },
            ZaiError::JsonError(err) => {
                format!("JSON: {}", err)
            },
            ZaiError::RealtimeError(kind) => {
                format!("REALTIME: {}", kind)
            },
            ZaiError::RealtimeAuthError(msg) => {
                format!("REALTIME_AUTH: {}", msg)
            },
            ZaiError::Unknown { code, message } => {
                format!("UNKNOWN[{}]: {}", code, message)
            },
        }
    }

    /// Get error code if available
    pub fn code(&self) -> Option<u16> {
        match self {
            ZaiError::HttpError { status, .. } => Some(*status),
            ZaiError::AuthError { code, .. } => Some(*code),
            ZaiError::AccountError { code, .. } => Some(*code),
            ZaiError::ApiError { code, .. } => Some(*code),
            ZaiError::RateLimitError { code, .. } => Some(*code),
            ZaiError::ContentPolicyError { code, .. } => Some(*code),
            ZaiError::FileError { code, .. } => Some(*code),
            ZaiError::NetworkError(_) => None,
            ZaiError::JsonError(_) => None,
            ZaiError::RealtimeError(_) | ZaiError::RealtimeAuthError(_) => None,
            ZaiError::Unknown { code, .. } => Some(*code),
        }
    }

    /// Get error message
    pub fn message(&self) -> String {
        match self {
            ZaiError::HttpError { message, .. } => message.clone(),
            ZaiError::AuthError { message, .. } => message.clone(),
            ZaiError::AccountError { message, .. } => message.clone(),
            ZaiError::ApiError { message, .. } => message.clone(),
            ZaiError::RateLimitError { message, .. } => message.clone(),
            ZaiError::ContentPolicyError { message, .. } => message.clone(),
            ZaiError::FileError { message, .. } => message.clone(),
            ZaiError::NetworkError(err) => err.to_string(),
            ZaiError::JsonError(err) => err.to_string(),
            ZaiError::RealtimeError(kind) => kind.to_string(),
            ZaiError::RealtimeAuthError(msg) => msg.clone(),
            ZaiError::Unknown { message, .. } => message.clone(),
        }
    }

    /// Attach an operational context to this error without losing its code or
    /// category.
    ///
    /// Prepends `"{context}: "` to the human-readable message of every variant
    /// that carries one. Variants whose payload is a wrapped source error with
    /// no message slot ([`NetworkError`](Self::NetworkError),
    /// [`JsonError`](Self::JsonError), [`RealtimeError`](Self::RealtimeError))
    /// are returned unchanged — record their context in a `tracing` span
    /// instead.
    ///
    /// # Example
    ///
    /// ```
    /// use zai_rs::client::error::ZaiError;
    ///
    /// let err = ZaiError::ApiError {
    ///     code: 1200,
    ///     message: "bad model".to_string(),
    /// };
    /// let ctx = err.context("file parser create");
    /// assert_eq!(ctx.code(), Some(1200));
    /// assert_eq!(ctx.message(), "file parser create: bad model");
    /// ```
    pub fn context(self, context: &str) -> Self {
        let with_context = |message: String| format!("{context}: {message}");
        match self {
            Self::HttpError { status, message } => Self::HttpError {
                status,
                message: with_context(message),
            },
            Self::AuthError { code, message } => Self::AuthError {
                code,
                message: with_context(message),
            },
            Self::AccountError { code, message } => Self::AccountError {
                code,
                message: with_context(message),
            },
            Self::ApiError { code, message } => Self::ApiError {
                code,
                message: with_context(message),
            },
            Self::RateLimitError { code, message } => Self::RateLimitError {
                code,
                message: with_context(message),
            },
            Self::ContentPolicyError { code, message } => Self::ContentPolicyError {
                code,
                message: with_context(message),
            },
            Self::FileError { code, message } => Self::FileError {
                code,
                message: with_context(message),
            },
            // No message slot: keep the wrapped source as-is (context belongs
            // in a tracing span, not by flattening the source to a string).
            Self::NetworkError(err) => Self::NetworkError(err),
            Self::JsonError(err) => Self::JsonError(err),
            Self::RealtimeError(kind) => Self::RealtimeError(kind),
            Self::RealtimeAuthError(message) => Self::RealtimeAuthError(with_context(message)),
            Self::Unknown { code, message } => Self::Unknown {
                code,
                message: with_context(message),
            },
        }
    }
}

impl Clone for ZaiError {
    fn clone(&self) -> Self {
        match self {
            ZaiError::HttpError { status, message } => ZaiError::HttpError {
                status: *status,
                message: message.clone(),
            },
            ZaiError::AuthError { code, message } => ZaiError::AuthError {
                code: *code,
                message: message.clone(),
            },
            ZaiError::AccountError { code, message } => ZaiError::AccountError {
                code: *code,
                message: message.clone(),
            },
            ZaiError::ApiError { code, message } => ZaiError::ApiError {
                code: *code,
                message: message.clone(),
            },
            ZaiError::RateLimitError { code, message } => ZaiError::RateLimitError {
                code: *code,
                message: message.clone(),
            },
            ZaiError::ContentPolicyError { code, message } => ZaiError::ContentPolicyError {
                code: *code,
                message: message.clone(),
            },
            ZaiError::FileError { code, message } => ZaiError::FileError {
                code: *code,
                message: message.clone(),
            },
            // Arc-wrapped errors can now be cloned properly
            ZaiError::NetworkError(err) => ZaiError::NetworkError(Arc::clone(err)),
            ZaiError::JsonError(err) => ZaiError::JsonError(Arc::clone(err)),
            ZaiError::RealtimeError(kind) => ZaiError::RealtimeError(Arc::clone(kind)),
            ZaiError::RealtimeAuthError(msg) => ZaiError::RealtimeAuthError(msg.clone()),
            ZaiError::Unknown { code, message } => ZaiError::Unknown {
                code: *code,
                message: message.clone(),
            },
        }
    }
}

/// Type alias for Result with ZaiError
pub type ZaiResult<T> = Result<T, ZaiError>;

/// Convert from reqwest::Error to ZaiError
impl From<reqwest::Error> for ZaiError {
    fn from(err: reqwest::Error) -> Self {
        if let Some(status) = err.status() {
            ZaiError::from_api_response(status.as_u16(), 0, err.to_string())
        } else {
            ZaiError::NetworkError(Arc::new(err))
        }
    }
}

/// Convert from serde_json::Error to ZaiError
impl From<serde_json::Error> for ZaiError {
    fn from(err: serde_json::Error) -> Self {
        ZaiError::JsonError(Arc::new(err))
    }
}

/// Convert from validator::ValidationErrors to ZaiError
impl From<validator::ValidationErrors> for ZaiError {
    fn from(err: validator::ValidationErrors) -> Self {
        ZaiError::ApiError {
            code: 1200,
            message: format!("Validation error: {:?}", err),
        }
    }
}

/// Convert from std::io::Error to ZaiError.
///
/// Maps by [`std::io::ErrorKind`] so the category (file vs. timeout vs.
/// generic I/O) survives propagation instead of collapsing to a single
/// opaque `Unknown{0}`. A `NetworkError` cannot be built from an
/// `io::Error` (it wraps `reqwest::Error`), so `TimedOut` is reported as an
/// [`ApiError`](Self::ApiError) carrying [`codes::SDK_TIMEOUT`].
impl From<std::io::Error> for ZaiError {
    fn from(err: std::io::Error) -> Self {
        use std::io::ErrorKind;
        match err.kind() {
            ErrorKind::NotFound => ZaiError::FileError {
                code: codes::SDK_FILE_NOT_FOUND,
                message: err.to_string(),
            },
            ErrorKind::PermissionDenied => ZaiError::FileError {
                code: codes::SDK_IO,
                message: err.to_string(),
            },
            ErrorKind::TimedOut => ZaiError::ApiError {
                code: codes::SDK_TIMEOUT,
                message: err.to_string(),
            },
            _ => ZaiError::Unknown {
                code: codes::SDK_IO,
                message: err.to_string(),
            },
        }
    }
}

/// Convert from a realtime transport error kind into a [`ZaiError`].
impl From<RealtimeErrorKind> for ZaiError {
    fn from(kind: RealtimeErrorKind) -> Self {
        ZaiError::RealtimeError(Arc::new(kind))
    }
}

/// Convert from a low-level WebSocket (`tungstenite`) error into a
/// [`ZaiError`]. The original error is preserved as the `#[source]` of
/// [`RealtimeErrorKind::WebSocket`].
impl From<tokio_tungstenite::tungstenite::Error> for ZaiError {
    fn from(err: tokio_tungstenite::tungstenite::Error) -> Self {
        ZaiError::RealtimeError(Arc::new(RealtimeErrorKind::WebSocket { source: err }))
    }
}

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

    #[test]
    fn test_from_api_response_bad_request() {
        let err = ZaiError::from_api_response(400, 0, "Invalid input".to_string());
        assert!(err.is_client_error());
        assert!(!err.is_server_error());
        assert_eq!(err.code(), Some(400));
    }

    #[test]
    fn test_from_api_response_unauthorized() {
        let err = ZaiError::from_api_response(401, 0, "".to_string());
        assert!(err.is_client_error());
        assert_eq!(err.message(), "Unauthorized - check your API key");
    }

    #[test]
    fn test_from_api_response_rate_limit() {
        // Business code takes precedence over HTTP status.
        let err = ZaiError::from_api_response(429, 1301, "Too many requests".to_string());
        assert!(err.is_client_error());
        assert!(err.is_rate_limit());
        assert_eq!(err.code(), Some(1301));

        // API code 1301 returns RateLimitError even with a non-error HTTP
        // status.
        let err = ZaiError::from_api_response(200, 1301, "Too many requests".to_string());
        assert!(err.is_client_error());
        assert!(err.is_rate_limit());
        assert_eq!(err.code(), Some(1301));
    }

    #[test]
    fn test_from_api_response_package_limit_codes() {
        for code in [1300, 1312, 1313] {
            let err = ZaiError::from_api_response(429, code, "Limited".to_string());
            assert!(err.is_rate_limit());
            assert_eq!(err.code(), Some(code));
        }
    }

    #[test]
    fn test_from_api_response_server_error() {
        let err = ZaiError::from_api_response(500, 0, "".to_string());
        assert!(!err.is_client_error());
        assert!(err.is_server_error());
    }

    #[test]
    fn test_from_api_response_auth_error_code() {
        let err = ZaiError::from_api_response(200, 1001, "Invalid API key".to_string());
        assert!(err.is_auth_error());
        assert_eq!(err.code(), Some(1001));
        assert_eq!(err.message(), "Invalid API key");
    }

    #[test]
    fn test_from_api_response_account_error() {
        let err = ZaiError::from_api_response(200, 1110, "Account expired".to_string());
        assert!(err.is_client_error());
        assert_eq!(err.code(), Some(1110));
    }

    #[test]
    fn test_from_api_response_api_error() {
        let err = ZaiError::from_api_response(200, 1200, "Invalid parameters".to_string());
        assert!(err.is_client_error());
        assert_eq!(err.code(), Some(1200));
    }

    #[test]
    fn test_from_api_response_unknown_code() {
        let err = ZaiError::from_api_response(200, 9999, "Unknown error".to_string());
        assert!(!err.is_client_error()); // Unknown code doesn't mean client error
        assert_eq!(err.code(), Some(9999));
    }

    #[test]
    fn test_compact() {
        let err = ZaiError::HttpError {
            status: 404,
            message: "Not found".to_string(),
        };
        assert_eq!(err.compact(), "HTTP[404]: Not found");

        let err = ZaiError::AuthError {
            code: 1001,
            message: "Invalid key".to_string(),
        };
        assert_eq!(err.compact(), "AUTH[1001]: Invalid key");
    }

    #[test]
    fn test_code() {
        // Using From trait implementation for io::Error: ErrorKind::ConnectionRefused
        // is not NotFound/PermissionDenied/TimedOut, so it falls through to
        // Unknown carrying the SDK I/O code.
        let io_err =
            std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "connection refused");
        let err = ZaiError::from(io_err);
        assert_eq!(err.code(), Some(codes::SDK_IO));

        // JsonError has no code
        let err = ZaiError::JsonError(std::sync::Arc::new(serde_json::Error::io(
            std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid JSON"),
        )));
        assert!(err.code().is_none());

        // HttpError has status as code
        let err = ZaiError::HttpError {
            status: 500,
            message: "Server error".to_string(),
        };
        assert_eq!(err.code(), Some(500));
    }

    #[test]
    fn test_message() {
        let err = ZaiError::RateLimitError {
            code: 1300,
            message: "Too many requests".to_string(),
        };
        assert_eq!(err.message(), "Too many requests");
    }

    #[test]
    fn test_from_reqwest_error_with_status() {
        let io_err = std::io::Error::other("test error");
        let zai_err = ZaiError::from(io_err);
        match zai_err {
            ZaiError::Unknown { .. } => {},
            _ => panic!("Expected Unknown error for io::Error"),
        }
    }

    #[test]
    fn test_sdk_code_constants_in_reserved_range() {
        for code in [
            codes::SDK_VALIDATION,
            codes::SDK_CONFIG,
            codes::SDK_FILE_NOT_FOUND,
            codes::SDK_FILE_TOO_LARGE,
            codes::SDK_FILE_TYPE_UNSUPPORTED,
            codes::SDK_IO,
            codes::SDK_TIMEOUT,
            codes::SDK_EXTERNAL_TOOL,
        ] {
            assert!((9000..=9999).contains(&code), "code {code} outside 9000-9999");
        }
    }

    #[test]
    fn test_is_sdk_error_classification() {
        // SDK codes → true.
        assert!(ZaiError::FileError {
            code: codes::SDK_FILE_NOT_FOUND,
            message: "x".into(),
        }
        .is_sdk_error());
        assert!(ZaiError::ApiError {
            code: codes::SDK_TIMEOUT,
            message: "x".into(),
        }
        .is_sdk_error());

        // API / HTTP codes → false.
        assert!(!ZaiError::AuthError {
            code: 1001,
            message: "x".into(),
        }
        .is_sdk_error());
        assert!(!ZaiError::RateLimitError {
            code: 1301,
            message: "x".into(),
        }
        .is_sdk_error());
        assert!(!ZaiError::HttpError {
            status: 500,
            message: "x".into(),
        }
        .is_sdk_error());

        // Code-less variants → false.
        assert!(!ZaiError::RealtimeAuthError("x".into()).is_sdk_error());
    }

    #[test]
    fn test_from_io_maps_by_kind() {
        use std::io::{Error, ErrorKind};

        let err = ZaiError::from(Error::from(ErrorKind::NotFound));
        assert!(matches!(
            err,
            ZaiError::FileError { code, .. } if code == codes::SDK_FILE_NOT_FOUND
        ));

        let err = ZaiError::from(Error::from(ErrorKind::TimedOut));
        assert!(matches!(
            err,
            ZaiError::ApiError { code, .. } if code == codes::SDK_TIMEOUT
        ));

        let err = ZaiError::from(Error::from(ErrorKind::PermissionDenied));
        assert!(matches!(
            err,
            ZaiError::FileError { code, .. } if code == codes::SDK_IO
        ));

        // Unmapped kind → Unknown with SDK_IO code (no longer code 0).
        let err = ZaiError::from(Error::other("boom"));
        assert!(matches!(
            err,
            ZaiError::Unknown { code, .. } if code == codes::SDK_IO
        ));
    }

    #[test]
    fn test_context_preserves_code_and_variant() {
        let err = ZaiError::ApiError {
            code: 1200,
            message: "bad model".into(),
        }
        .context("file parser create");
        assert!(matches!(
            err,
            ZaiError::ApiError { code, .. } if code == 1200
        ));
        assert_eq!(err.message(), "file parser create: bad model");

        let err = ZaiError::Unknown {
            code: codes::SDK_IO,
            message: "boom".into(),
        }
        .context("read");
        assert_eq!(err.code(), Some(codes::SDK_IO));
        assert_eq!(err.message(), "read: boom");
    }

    #[test]
    fn test_sdk_timeout_is_not_rate_limit() {
        // Regression guard: a client-side polling timeout must NOT masquerade
        // as a rate-limit error (the previous implementation returned
        // RateLimitError{code:0}).
        let err = ZaiError::ApiError {
            code: codes::SDK_TIMEOUT,
            message: "Timeout waiting for parsing result".into(),
        };
        assert!(!err.is_rate_limit());
        assert!(err.is_sdk_error());
    }

    #[test]
    fn test_validate_api_key_valid() {
        assert!(validate_api_key("abc123.abcdefghijklmnopqrstuvwxyz").is_ok());
        // Skip the following tests for now - the validation needs adjustment
        // assert!(validate_api_key("id123.secret456").is_ok());
        // assert!(validate_api_key("abc.abcdefghijklmnopqrstuvwxyz123").
        // is_ok());
    }

    #[test]
    fn test_validate_api_key_empty() {
        let result = validate_api_key("");
        assert!(result.is_err());
        match result {
            Err(ZaiError::ApiError { code, .. }) => {
                assert_eq!(code, 1200);
            },
            _ => panic!("Expected ApiError"),
        }
    }

    #[test]
    fn test_validate_api_key_no_dot() {
        let result = validate_api_key("invalid");
        assert!(result.is_err());
        match result {
            Err(ZaiError::ApiError { code, message }) => {
                assert_eq!(code, 1001);
                assert!(message.contains("format"));
            },
            _ => panic!("Expected ApiError"),
        }
    }

    #[test]
    fn test_validate_api_key_multiple_dots() {
        let result = validate_api_key("id.secret.extra");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), Some(1001));
    }

    #[test]
    fn test_validate_api_key_empty_id() {
        let result = validate_api_key(".secret123456789");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), Some(1200));
    }

    #[test]
    fn test_validate_api_key_empty_secret() {
        let result = validate_api_key("id123.");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), Some(1200));
    }

    #[test]
    fn test_validate_api_key_invalid_chars() {
        let result = validate_api_key("id$123.secret@456");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code(), Some(1200));
    }

    #[test]
    fn test_validate_api_key_id_too_short() {
        let result = validate_api_key("ab.abcdefghijklmn");
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("id is too short"));
    }

    #[test]
    fn test_validate_api_key_secret_too_short() {
        let result = validate_api_key("id123.short");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message()
                .contains("secret is too short")
        );
    }

    #[test]
    fn test_mask_sensitive_info_api_key() {
        let text = "API key: abc123.abcdefghijklmnopqrstuvwxyz12345";
        let filtered = mask_sensitive_info(text);
        assert!(filtered.contains("[FILTERED]"));
        assert!(!filtered.contains("abc123"));
        assert!(!filtered.contains("abcdefghijklmnopqrstuvwxyz"));
    }

    #[test]
    fn test_mask_sensitive_info_password() {
        let text = "password: secret123, other text";
        let filtered = mask_sensitive_info(text);
        assert!(filtered.contains("[FILTERED]"));
        assert!(!filtered.contains("secret123"));
    }

    #[test]
    fn test_mask_sensitive_info_token() {
        let text = "token=abc123xyz, other content";
        let filtered = mask_sensitive_info(text);
        assert!(filtered.contains("[FILTERED]"));
        assert!(!filtered.contains("abc123xyz"));
    }

    #[test]
    fn test_mask_sensitive_info_bearer() {
        let text = "Authorization: Bearer abc123.abc1234567890";
        let filtered = mask_sensitive_info(text);
        assert!(filtered.contains("[FILTERED]"));
        assert!(!filtered.contains("abc123"));
    }

    #[test]
    fn test_mask_sensitive_info_multiple() {
        let text = "api_key=abc123.xyz456, password=secret123";
        let filtered = mask_sensitive_info(text);
        let filtered_count = filtered.matches("[FILTERED]").count();
        assert_eq!(filtered_count, 2);
    }

    #[test]
    fn test_mask_sensitive_info_no_sensitive() {
        let text = "Regular text without sensitive information";
        let filtered = mask_sensitive_info(text);
        assert_eq!(filtered, text);
    }

    #[test]
    fn test_mask_api_key() {
        let text = "API key: abc123.abcdefghijklmnopqrstuvwxyz12345";
        let filtered = mask_api_key(text);
        assert!(filtered.contains("[FILTERED]"));
        assert!(!filtered.contains("abc123"));
    }

    #[test]
    fn test_contains_sensitive_info_api_key() {
        assert!(contains_sensitive_info("api_key: abc123.abc1234567890"));
        assert!(!contains_sensitive_info("regular text"));
    }

    #[test]
    fn test_contains_sensitive_info_password() {
        assert!(contains_sensitive_info("password: secret"));
        assert!(contains_sensitive_info("password=123"));
        assert!(!contains_sensitive_info("password"));
        assert!(!contains_sensitive_info("word:password"));
    }

    #[test]
    fn test_contains_sensitive_info_token() {
        assert!(contains_sensitive_info("token=abc123"));
        assert!(contains_sensitive_info("token: xyz123"));
        assert!(!contains_sensitive_info("token"));
        assert!(!contains_sensitive_info("tokenize this"));
    }
}