areev 0.2.0

Rust SDK for the Areev knowledge database — gRPC and HTTP transports
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
//! Typed error hierarchy raised by the Areev SDK.
//!
//! Customer code typically matches on the variant — e.g.
//! `Err(AreevError::HipaaPolicyViolation { .. }) => …` — to branch on the
//! kind of failure. [`AreevError::from_response_status`] maps a server
//! response (HTTP status + optional `AAA-Ennn` error code) onto the
//! appropriate variant. The dispatch table mirrors the Python SDK's
//! `_exception_for` so behaviour is consistent across languages.
//!
//! ## Variant cheat sheet
//!
//! | HTTP | Code prefix     | Variant                                |
//! |------|-----------------|----------------------------------------|
//! | 401  | any             | [`AreevError::Authentication`]         |
//! | 403  | `HRN-E04*`      | [`AreevError::HipaaPolicyViolation`]   |
//! | 403  | `FTR-E001`      | [`AreevError::FeatureNotAvailable`]    |
//! | 403  | `FTR-E002`      | [`AreevError::PlanLimit`]              |
//! | 402/403 | `CRD-E003`   | [`AreevError::InsufficientCredits`]    |
//! | 402  | other           | [`AreevError::InsufficientCredits`]    |
//! | 403  | other           | [`AreevError::Authorization`]          |
//! | 404  | any             | [`AreevError::NotFound`]               |
//! | 409  | any             | [`AreevError::Conflict`]               |
//! | 429  | any             | [`AreevError::RateLimit`]              |
//! | 400/422 | any          | [`AreevError::Validation`]             |
//! | 5xx  | any             | [`AreevError::Server`]                 |
//! | —    | transport error | [`AreevError::Transport`]              |
//! | other| any             | [`AreevError::Other`]                  |
//!
//! ## Structured response body
//!
//! Status-carrying variants additionally expose the server's structured
//! error body via [`AreevError::body`] — e.g. `retry_after_ms` on a 429,
//! or per-field validation detail on a 422. The body is **redacted** (an
//! allowlist of secret-bearing keys is replaced with `"[redacted]"`)
//! before it is stored, so it is safe to log. Mirrors the Python SDK's
//! `response_body` attribute and the TS SDK's `responseBody`.

use serde_json::Value;

/// Maximum recursion depth when redacting an error body. Caps work on
/// adversarial/cyclic-looking input. Mirrors the Python SDK.
const REDACT_MAX_DEPTH: usize = 16;

/// Secret-bearing keys whose values are scrubbed from any error body
/// before it is stored on an [`AreevError`]. Lower-cased; matched
/// case-insensitively. Kept in sync with the Python SDK's
/// `_SENSITIVE_KEYS`.
const SENSITIVE_KEYS: &[&str] = &[
    "authorization",
    "cookie",
    "set-cookie",
    "x-areev-system-key",
    "x-axtion-service-token",
    "access_token",
    "refresh_token",
    "bearer_token",
    "id_token",
    "client_secret",
    "axtion_credential_id",
    "api_key",
    "apikey",
    "secret",
    "password",
    "private_key",
];

/// Walk a JSON value and replace the values of secret-bearing keys with
/// `"[redacted]"`. Pure — never mutates the input. Recursion is capped
/// at [`REDACT_MAX_DEPTH`] levels. Mirrors the Python SDK's
/// `_redact_sensitive`.
fn redact_body(value: &Value, depth: usize) -> Value {
    if depth > REDACT_MAX_DEPTH {
        return value.clone();
    }
    match value {
        Value::Object(map) => {
            let mut out = serde_json::Map::with_capacity(map.len());
            for (k, v) in map {
                if SENSITIVE_KEYS.contains(&k.to_ascii_lowercase().as_str()) {
                    out.insert(k.clone(), Value::String("[redacted]".to_string()));
                } else {
                    out.insert(k.clone(), redact_body(v, depth + 1));
                }
            }
            Value::Object(out)
        }
        Value::Array(items) => {
            Value::Array(items.iter().map(|v| redact_body(v, depth + 1)).collect())
        }
        other => other.clone(),
    }
}

/// All errors raised by the Areev SDK.
///
/// Variants carry the HTTP status, optional server error code (`AAA-Ennn`),
/// a human-readable message, the structured (redacted) response body, and
/// the server's `x-request-id` when present — match on the variant to
/// branch and inspect the fields for diagnostics.
#[derive(Debug, thiserror::Error)]
pub enum AreevError {
    /// HTTP 401 — missing, invalid, or expired credentials.
    ///
    /// Common causes: no `Authorization` header, malformed API key,
    /// expired Pilot session token. The caller should re-authenticate.
    #[error("[{code}] authentication failed: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("AUTH"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Authentication {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (always 401 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 403 — authenticated but not permitted.
    ///
    /// Common error codes: `AUT-E003` (missing scope), `FTR-E001`
    /// (tier gate). The caller either lacks the right scope or needs to
    /// upgrade plan. See [`AreevError::HipaaPolicyViolation`] for the
    /// HIPAA-specific subcase.
    #[error("[{code}] authorization failed: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("AUTHZ"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Authorization {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (always 403 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 403 with HIPAA-domain error code (`HRN-E04x`) — the
    /// operation was rejected because the memory is HIPAA-bound and
    /// the action would expose PHI without a BAA on file.
    ///
    /// Semantically a sub-case of [`AreevError::Authorization`] — callers
    /// that want a single catch-all can simply check for either variant.
    #[error("[{code}] HIPAA policy violation: {message} (http {http_status}{rid})",
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    HipaaPolicyViolation {
        /// Server-side error code in `AAA-Ennn` format (always `HRN-E04*`).
        code: String,
        /// HTTP status code (always 403 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 403 with `FTR-E001` — the operation requires a feature the
    /// org's plan tier does not include (e.g. Knowledge Sources, hooks,
    /// predicate hints, harness management are Scale/Custom only).
    ///
    /// The SDK never gates on tier client-side — this variant is only
    /// raised from the server's verdict. Upgrade the plan to proceed.
    #[error("[{code}] feature not available on this plan: {message} (http {http_status}{rid})",
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    FeatureNotAvailable {
        /// Server-side error code (always `FTR-E001`).
        code: String,
        /// HTTP status code (403 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 403 with `FTR-E002` — a per-plan resource limit was reached
    /// (e.g. max memories, max namespaces, max bound tools). The
    /// operation is allowed by the tier but capped by quota.
    #[error("[{code}] plan limit reached: {message} (http {http_status}{rid})",
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    PlanLimit {
        /// Server-side error code (always `FTR-E002`).
        code: String,
        /// HTTP status code (403 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 402 / 403 with `CRD-E003` — the org has insufficient credits
    /// for a billed operation. Data-subject-rights paths (forget,
    /// crypto-erase, audit, export, verify) are never credit-gated, so
    /// this variant only surfaces on billed write/recall/chat paths.
    #[error("[{code}] insufficient credits: {message} (http {http_status}{rid})",
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    InsufficientCredits {
        /// Server-side error code (typically `CRD-E003`).
        code: String,
        /// HTTP status code (402 or 403 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 404 — the requested memory, harness, grain, or tool does
    /// not exist (or the caller is not allowed to see that it does).
    #[error("[{code}] not found: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("NOTFOUND"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    NotFound {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (always 404 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 400 / 422 — request body or arguments failed server-side
    /// validation. Common codes: `MEM-E10x` (tool schema), `HRN-E019`
    /// (tool-output schema mismatch). [`AreevError::body`] carries the
    /// per-field validation detail when the server supplies it.
    #[error("[{code}] validation error: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("VALIDATION"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Validation {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (400 or 422 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 429 — per-endpoint or global rate limit exceeded.
    ///
    /// Auto-retry will retry this with backoff; callers see this variant
    /// only when retries are exhausted. [`AreevError::body`] may carry
    /// `retry_after_ms`.
    #[error("[{code}] rate limited: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("RATELIMIT"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    RateLimit {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (always 429 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 409 — concurrent write conflict (e.g. `If-Match`
    /// precondition failed, supersede race lost). The caller should
    /// re-read and retry the operation.
    #[error("[{code}] conflict: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("CONFLICT"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Conflict {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (always 409 for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// HTTP 5xx — server-side failure. Auto-retry handles transient
    /// ones (3 attempts with backoff); callers see this variant only
    /// when retries are exhausted.
    #[error("[{code}] server error: {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("SERVER"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Server {
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// HTTP status code (5xx for this variant).
        http_status: u16,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },

    /// Network-layer failure before a response was received
    /// (connection refused, DNS failure, request timeout, TLS handshake
    /// failure). Wraps the underlying [`reqwest::Error`].
    #[cfg(feature = "http")]
    #[error("transport error: {source}")]
    Transport {
        /// The underlying transport-layer failure from reqwest.
        #[from]
        source: reqwest::Error,
    },

    /// gRPC transport failure (only present with the `grpc` feature).
    #[cfg(feature = "grpc")]
    #[error("gRPC error: {0}")]
    Grpc(#[from] tonic::Status),

    /// JSON (de)serialisation failure.
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// Any response that doesn't fit the other variants — typically a
    /// 3xx, an unknown 4xx, or a malformed error body. Carries whatever
    /// information was available on the wire.
    #[error("[{code}] {message} (http {http_status}{rid})",
        code = code.as_deref().unwrap_or("OTHER"),
        rid = request_id.as_deref().map(|r| format!(" request_id={r}")).unwrap_or_default()
    )]
    Other {
        /// HTTP status code as observed on the wire (0 for synthetic errors).
        http_status: u16,
        /// Server-side error code in `AAA-Ennn` format when present.
        code: Option<String>,
        /// Human-readable, non-PII error description.
        message: String,
        /// Redacted structured response body, if the server sent JSON.
        body: Value,
        /// `x-request-id` header when present, for cross-system tracing.
        request_id: Option<String>,
    },
}

impl AreevError {
    /// Build the most specific variant for an error response.
    ///
    /// This is the canonical dispatch table — every error coming off
    /// the HTTP layer is routed through this function. The Python SDK's
    /// `_exception_for` is the reference implementation: same status
    /// codes, same `HRN-E04*` HIPAA carve-out, same fall-through.
    ///
    /// The structured `body` defaults to [`Value::Null`]; use
    /// [`AreevError::from_response_with_body`] to attach the server's
    /// parsed (and redacted) error body.
    pub fn from_response_status(
        http_status: u16,
        code: Option<&str>,
        message: impl Into<String>,
        request_id: Option<String>,
    ) -> Self {
        Self::from_response_with_body(http_status, code, message, Value::Null, request_id)
    }

    /// Like [`AreevError::from_response_status`] but attaches the server's
    /// structured error `body`. The body is redacted (secret-bearing keys
    /// scrubbed) before it is stored, so the resulting error is safe to
    /// log. Mirrors the Python SDK's `response_body` plumbing.
    pub fn from_response_with_body(
        http_status: u16,
        code: Option<&str>,
        message: impl Into<String>,
        body: Value,
        request_id: Option<String>,
    ) -> Self {
        let code_owned = code.map(|c| c.to_string());
        let message = message.into();
        let body = redact_body(&body, 0);

        // Code-keyed variants take precedence over the status fallback —
        // mirrors the Python SDK's `_exception_for` which branches on the
        // `AAA-Ennn` code first for the feature/credit gates.
        if let Some(c) = code {
            match c {
                "FTR-E001" => {
                    return AreevError::FeatureNotAvailable {
                        code: c.to_string(),
                        http_status,
                        message,
                        body,
                        request_id,
                    }
                }
                "FTR-E002" => {
                    return AreevError::PlanLimit {
                        code: c.to_string(),
                        http_status,
                        message,
                        body,
                        request_id,
                    }
                }
                "CRD-E003" => {
                    return AreevError::InsufficientCredits {
                        code: c.to_string(),
                        http_status,
                        message,
                        body,
                        request_id,
                    }
                }
                _ => {}
            }
        }

        match http_status {
            401 => AreevError::Authentication {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            402 => AreevError::InsufficientCredits {
                // A bare 402 (no `CRD-E003`) is still a payment-required
                // signal — route it to InsufficientCredits to match the
                // doc table. Preserve the server code when present.
                code: code_owned.unwrap_or_else(|| "CRD-E003".to_string()),
                http_status,
                message,
                body,
                request_id,
            },
            403 => {
                if let Some(c) = code {
                    if c.starts_with("HRN-E04") {
                        return AreevError::HipaaPolicyViolation {
                            code: c.to_string(),
                            http_status,
                            message,
                            body,
                            request_id,
                        };
                    }
                }
                AreevError::Authorization {
                    code: code_owned,
                    http_status,
                    message,
                    body,
                    request_id,
                }
            }
            404 => AreevError::NotFound {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            409 => AreevError::Conflict {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            429 => AreevError::RateLimit {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            400 | 422 => AreevError::Validation {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            s if (500..600).contains(&s) => AreevError::Server {
                code: code_owned,
                http_status,
                message,
                body,
                request_id,
            },
            _ => AreevError::Other {
                http_status,
                code: code_owned,
                message,
                body,
                request_id,
            },
        }
    }

    /// The HTTP status code that produced this error, or `0` for
    /// transport-layer errors that never received a response.
    pub fn http_status(&self) -> u16 {
        match self {
            AreevError::Authentication { http_status, .. }
            | AreevError::Authorization { http_status, .. }
            | AreevError::HipaaPolicyViolation { http_status, .. }
            | AreevError::FeatureNotAvailable { http_status, .. }
            | AreevError::PlanLimit { http_status, .. }
            | AreevError::InsufficientCredits { http_status, .. }
            | AreevError::NotFound { http_status, .. }
            | AreevError::Validation { http_status, .. }
            | AreevError::RateLimit { http_status, .. }
            | AreevError::Conflict { http_status, .. }
            | AreevError::Server { http_status, .. }
            | AreevError::Other { http_status, .. } => *http_status,
            #[cfg(feature = "http")]
            AreevError::Transport { source } => source.status().map(|s| s.as_u16()).unwrap_or(0),
            #[cfg(feature = "grpc")]
            AreevError::Grpc(_) => 0,
            AreevError::Serialization(_) => 0,
        }
    }

    /// The server-side error code in `AAA-Ennn` format, when present.
    pub fn code(&self) -> Option<&str> {
        match self {
            AreevError::Authentication { code, .. }
            | AreevError::Authorization { code, .. }
            | AreevError::NotFound { code, .. }
            | AreevError::Validation { code, .. }
            | AreevError::RateLimit { code, .. }
            | AreevError::Conflict { code, .. }
            | AreevError::Server { code, .. }
            | AreevError::Other { code, .. } => code.as_deref(),
            AreevError::HipaaPolicyViolation { code, .. }
            | AreevError::FeatureNotAvailable { code, .. }
            | AreevError::PlanLimit { code, .. }
            | AreevError::InsufficientCredits { code, .. } => Some(code.as_str()),
            #[cfg(feature = "http")]
            AreevError::Transport { .. } => None,
            #[cfg(feature = "grpc")]
            AreevError::Grpc(_) => None,
            AreevError::Serialization(_) => None,
        }
    }

    /// The server's `x-request-id` header value when present.
    pub fn request_id(&self) -> Option<&str> {
        match self {
            AreevError::Authentication { request_id, .. }
            | AreevError::Authorization { request_id, .. }
            | AreevError::NotFound { request_id, .. }
            | AreevError::Validation { request_id, .. }
            | AreevError::RateLimit { request_id, .. }
            | AreevError::Conflict { request_id, .. }
            | AreevError::Server { request_id, .. }
            | AreevError::Other { request_id, .. } => request_id.as_deref(),
            AreevError::HipaaPolicyViolation { request_id, .. }
            | AreevError::FeatureNotAvailable { request_id, .. }
            | AreevError::PlanLimit { request_id, .. }
            | AreevError::InsufficientCredits { request_id, .. } => request_id.as_deref(),
            #[cfg(feature = "http")]
            AreevError::Transport { .. } => None,
            #[cfg(feature = "grpc")]
            AreevError::Grpc(_) => None,
            AreevError::Serialization(_) => None,
        }
    }

    /// The error message — same string as the variant's `message` field.
    pub fn message(&self) -> &str {
        match self {
            AreevError::Authentication { message, .. }
            | AreevError::Authorization { message, .. }
            | AreevError::NotFound { message, .. }
            | AreevError::Validation { message, .. }
            | AreevError::RateLimit { message, .. }
            | AreevError::Conflict { message, .. }
            | AreevError::Server { message, .. }
            | AreevError::Other { message, .. } => message,
            AreevError::HipaaPolicyViolation { message, .. }
            | AreevError::FeatureNotAvailable { message, .. }
            | AreevError::PlanLimit { message, .. }
            | AreevError::InsufficientCredits { message, .. } => message,
            #[cfg(feature = "http")]
            AreevError::Transport { .. } => "transport error",
            #[cfg(feature = "grpc")]
            AreevError::Grpc(_) => "gRPC error",
            AreevError::Serialization(_) => "serialization error",
        }
    }

    /// The server's structured (redacted) error body, when one was sent.
    ///
    /// Returns [`Value::Null`] for synthetic / client-side errors and the
    /// transport / gRPC / serialization variants (which carry no HTTP
    /// body). Read structured detail here — e.g.
    /// `err.body().get("retry_after_ms")` on a 429, or per-field
    /// validation errors on a 422. Secret-bearing keys are already
    /// scrubbed, so the value is safe to log. Mirrors the Python SDK's
    /// `response_body` and the TS SDK's `responseBody`.
    pub fn body(&self) -> &Value {
        match self {
            AreevError::Authentication { body, .. }
            | AreevError::Authorization { body, .. }
            | AreevError::NotFound { body, .. }
            | AreevError::Validation { body, .. }
            | AreevError::RateLimit { body, .. }
            | AreevError::Conflict { body, .. }
            | AreevError::Server { body, .. }
            | AreevError::Other { body, .. }
            | AreevError::HipaaPolicyViolation { body, .. }
            | AreevError::FeatureNotAvailable { body, .. }
            | AreevError::PlanLimit { body, .. }
            | AreevError::InsufficientCredits { body, .. } => body,
            #[cfg(feature = "http")]
            AreevError::Transport { .. } => &Value::Null,
            #[cfg(feature = "grpc")]
            AreevError::Grpc(_) => &Value::Null,
            AreevError::Serialization(_) => &Value::Null,
        }
    }

    /// Whether this error should be retried by the auto-retry layer
    /// (5xx, 408, 429, transport). 4xx other than 408/429 are not retried.
    pub(crate) fn is_retryable(&self) -> bool {
        match self {
            AreevError::Server { .. } | AreevError::RateLimit { .. } => true,
            AreevError::Other { http_status, .. } => *http_status == 408,
            #[cfg(feature = "http")]
            AreevError::Transport { .. } => true,
            _ => false,
        }
    }
}

/// Convenient `Result` alias used throughout the SDK.
pub type Result<T> = std::result::Result<T, AreevError>;