adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
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
// Unified structured error envelope for all ADK-Rust operations.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;

/// The subsystem that produced the error — the origin, not the boundary it surfaces through.
///
/// Choose the variant matching where the failure actually happened, not which trait
/// boundary returned it. For example:
/// - A code-execution timeout inside `python_code_tool.rs` → [`Code`](Self::Code)
/// - An auth denial inside middleware → [`Auth`](Self::Auth)
/// - A missing API key detected in model config → [`Model`](Self::Model) with `InvalidInput`
/// - A database write failure in session persistence → [`Session`](Self::Session)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorComponent {
    /// Error originated in agent logic.
    Agent,
    /// Error originated in model/LLM interaction.
    Model,
    /// Error originated in tool execution.
    Tool,
    /// Error originated in session management.
    Session,
    /// Error originated in artifact storage.
    Artifact,
    /// Error originated in memory/RAG operations.
    Memory,
    /// Error originated in graph workflow execution.
    Graph,
    /// Error originated in realtime audio/video streaming.
    Realtime,
    /// Error originated in code execution.
    Code,
    /// Error originated in the HTTP server.
    Server,
    /// Error originated in authentication/authorization.
    Auth,
    /// Error originated in guardrail validation.
    Guardrail,
    /// Error originated in evaluation framework.
    Eval,
    /// Error originated in deployment operations.
    Deploy,
}

impl fmt::Display for ErrorComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Agent => "agent",
            Self::Model => "model",
            Self::Tool => "tool",
            Self::Session => "session",
            Self::Artifact => "artifact",
            Self::Memory => "memory",
            Self::Graph => "graph",
            Self::Realtime => "realtime",
            Self::Code => "code",
            Self::Server => "server",
            Self::Auth => "auth",
            Self::Guardrail => "guardrail",
            Self::Eval => "eval",
            Self::Deploy => "deploy",
        };
        f.write_str(s)
    }
}

/// The kind of failure independent of subsystem.
///
/// Choose the variant that best describes what went wrong:
/// - [`InvalidInput`](Self::InvalidInput) — caller provided bad data (config, request body, parameters)
/// - [`Unauthorized`](Self::Unauthorized) — missing or invalid credentials
/// - [`Forbidden`](Self::Forbidden) — valid credentials but insufficient permissions
/// - [`NotFound`](Self::NotFound) — requested resource does not exist
/// - [`RateLimited`](Self::RateLimited) — upstream rate limit hit (retryable by default)
/// - [`Timeout`](Self::Timeout) — operation exceeded time limit (retryable by default)
/// - [`Unavailable`](Self::Unavailable) — upstream service temporarily down (retryable by default)
/// - [`Cancelled`](Self::Cancelled) — operation was cancelled by caller or system
/// - [`Internal`](Self::Internal) — unexpected internal error (bugs, invariant violations)
/// - [`Unsupported`](Self::Unsupported) — requested feature or operation is not supported
/// - [`ResourceExhausted`](Self::ResourceExhausted) — a configured budget (model calls, tokens,
///   cost, wall time, tool calls) or a provider account's quota, credit balance or spend limit
///   is used up; not retryable within the same run
/// - [`Conflict`](Self::Conflict) — the write lost a race or used a stale version; reload and
///   retry, or stop
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCategory {
    /// Caller provided bad data (config, request body, parameters).
    InvalidInput,
    /// Missing or invalid credentials.
    Unauthorized,
    /// Valid credentials but insufficient permissions.
    Forbidden,
    /// Requested resource does not exist.
    NotFound,
    /// Upstream rate limit hit (retryable by default).
    RateLimited,
    /// Operation exceeded time limit (retryable by default).
    Timeout,
    /// Upstream service temporarily down (retryable by default).
    Unavailable,
    /// Operation was cancelled by caller or system.
    Cancelled,
    /// Unexpected internal error (bugs, invariant violations).
    Internal,
    /// Requested feature or operation is not supported.
    Unsupported,
    /// A configured resource budget, or a provider account's quota, credit balance or
    /// spend limit, is used up.
    ///
    /// Not retryable within the same run: retrying spends against the same
    /// exhausted budget, or fails until the account has credit again. See
    /// [`RunBudget`](crate::RunBudget).
    ResourceExhausted,
    /// The write lost a race or used a stale version; reload and retry, or stop.
    ///
    /// Not retryable as is: repeating the same write with the same stale version or
    /// epoch fails again. Maps to HTTP 409.
    Conflict,
}

impl ErrorCategory {
    /// Whether the category describes the call rather than what happened upstream.
    ///
    /// `InvalidInput`, `Forbidden`, `NotFound`, `Unsupported`, `Conflict` and
    /// `ResourceExhausted` say what the call asked for and why it was not done, so their
    /// messages are the guidance the caller needs. The others report an upstream or
    /// internal failure, whose message can quote credentials, hosts or response bodies.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::ErrorCategory;
    ///
    /// assert!(ErrorCategory::Forbidden.is_rejection());
    /// assert!(!ErrorCategory::Unavailable.is_rejection());
    /// ```
    pub fn is_rejection(self) -> bool {
        matches!(
            self,
            Self::InvalidInput
                | Self::Forbidden
                | Self::NotFound
                | Self::Unsupported
                | Self::Conflict
                | Self::ResourceExhausted
        )
    }
}

impl fmt::Display for ErrorCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::InvalidInput => "invalid_input",
            Self::Unauthorized => "unauthorized",
            Self::Forbidden => "forbidden",
            Self::NotFound => "not_found",
            Self::RateLimited => "rate_limited",
            Self::Timeout => "timeout",
            Self::Unavailable => "unavailable",
            Self::Cancelled => "cancelled",
            Self::Internal => "internal",
            Self::Unsupported => "unsupported",
            Self::ResourceExhausted => "resource_exhausted",
            Self::Conflict => "conflict",
        };
        f.write_str(s)
    }
}

/// Structured retry guidance attached to every [`AdkError`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RetryHint {
    /// Whether the operation should be retried.
    pub should_retry: bool,
    /// Suggested delay before retrying, in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    /// Maximum number of retry attempts suggested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_attempts: Option<u32>,
}

impl RetryHint {
    /// Derive a default retry hint from the error category.
    pub fn for_category(category: ErrorCategory) -> Self {
        match category {
            ErrorCategory::RateLimited | ErrorCategory::Unavailable | ErrorCategory::Timeout => {
                Self { should_retry: true, ..Default::default() }
            }
            _ => Self::default(),
        }
    }

    /// Convert `retry_after_ms` to a [`Duration`].
    pub fn retry_after(&self) -> Option<Duration> {
        self.retry_after_ms.map(Duration::from_millis)
    }

    /// Set the retry-after delay from a [`Duration`].
    pub fn with_retry_after(mut self, duration: Duration) -> Self {
        self.retry_after_ms = Some(duration.as_millis() as u64);
        self
    }
}

/// Optional structured metadata carried by an [`AdkError`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ErrorDetails {
    /// HTTP status code from the upstream service, if applicable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upstream_status_code: Option<u16>,
    /// Request ID from the upstream service for correlation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Name of the provider that produced the error (e.g., "openai", "gemini").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Additional key-value metadata for debugging.
    ///
    /// Model providers in `adk-model` store the provider's own error code, such as
    /// `RATE_LIMIT_EXCEEDED` or `context_length_exceeded`, as a string under
    /// `"provider_error_code"`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, Value>,
}

/// Unified structured error type for all ADK-Rust operations.
///
/// # Migration from enum syntax
///
/// Before (0.4.x enum):
/// ```rust,ignore
/// // Construction
/// Err(AdkError::Model("rate limited".into()))
/// // Matching
/// matches!(err, AdkError::Model(_))
/// ```
///
/// After (0.5.x struct):
/// ```rust
/// use adk_core::{AdkError, ErrorComponent, ErrorCategory};
///
/// // Structured construction
/// let err = AdkError::new(
///     ErrorComponent::Model,
///     ErrorCategory::RateLimited,
///     "model.openai.rate_limited",
///     "rate limited",
/// );
/// assert!(err.is_retryable()); // RateLimited → should_retry = true
///
/// // Backward-compat construction (for migration)
/// let err = AdkError::model("rate limited");
/// assert!(err.is_model());
/// ```
pub struct AdkError {
    /// The subsystem that produced the error.
    pub component: ErrorComponent,
    /// The kind of failure.
    pub category: ErrorCategory,
    /// Machine-readable error code (e.g., "model.openai.rate_limited").
    pub code: &'static str,
    /// Human-readable error message.
    pub message: String,
    /// Retry guidance for this error.
    pub retry: RetryHint,
    /// Additional structured metadata.
    pub details: Box<ErrorDetails>,
    source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl fmt::Debug for AdkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("AdkError");
        d.field("component", &self.component)
            .field("category", &self.category)
            .field("code", &self.code)
            .field("message", &self.message)
            .field("retry", &self.retry)
            .field("details", &self.details);
        if let Some(src) = &self.source {
            d.field("source", &format_args!("{src}"));
        }
        d.finish()
    }
}

impl fmt::Display for AdkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}: {}", self.component, self.category, self.message)
    }
}

impl std::error::Error for AdkError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}

const _: () = {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}
    fn _assertions() {
        _assert_send::<AdkError>();
        _assert_sync::<AdkError>();
    }
};

impl AdkError {
    /// Creates a new `AdkError` with the given component, category, code, and message.
    pub fn new(
        component: ErrorComponent,
        category: ErrorCategory,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self {
            component,
            category,
            code,
            message: message.into(),
            retry: RetryHint::for_category(category),
            details: Box::new(ErrorDetails::default()),
            source: None,
        }
    }

    /// Attaches a source error for error chaining.
    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        self.source = Some(Box::new(source));
        self
    }

    /// Overrides the default retry hint.
    pub fn with_retry(mut self, retry: RetryHint) -> Self {
        self.retry = retry;
        self
    }

    /// Replaces the error details.
    pub fn with_details(mut self, details: ErrorDetails) -> Self {
        self.details = Box::new(details);
        self
    }

    /// Sets the upstream HTTP status code in details.
    pub fn with_upstream_status(mut self, status_code: u16) -> Self {
        self.details.upstream_status_code = Some(status_code);
        self
    }

    /// Sets the upstream request ID in details.
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.details.request_id = Some(request_id.into());
        self
    }

    /// Sets the provider name in details.
    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
        self.details.provider = Some(provider.into());
        self
    }
}

impl AdkError {
    /// Creates a `NotFound` error for the given component.
    pub fn not_found(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::NotFound, code, message)
    }

    /// Creates a `RateLimited` error for the given component.
    pub fn rate_limited(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::RateLimited, code, message)
    }

    /// Creates an `Unauthorized` error for the given component.
    pub fn unauthorized(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::Unauthorized, code, message)
    }

    /// Creates an `Internal` error for the given component.
    pub fn internal(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::Internal, code, message)
    }

    /// Creates a `Timeout` error for the given component.
    pub fn timeout(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::Timeout, code, message)
    }

    /// Creates an `Unavailable` error for the given component.
    pub fn unavailable(
        component: ErrorComponent,
        code: &'static str,
        message: impl Into<String>,
    ) -> Self {
        Self::new(component, ErrorCategory::Unavailable, code, message)
    }
}

impl AdkError {
    /// Legacy convenience constructor for agent errors.
    pub fn agent(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Agent, ErrorCategory::Internal, "agent.legacy", message)
    }

    /// Legacy convenience constructor for model errors.
    pub fn model(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Model, ErrorCategory::Internal, "model.legacy", message)
    }

    /// Legacy convenience constructor for tool errors.
    pub fn tool(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Tool, ErrorCategory::Internal, "tool.legacy", message)
    }

    /// Legacy convenience constructor for session errors.
    pub fn session(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Session, ErrorCategory::Internal, "session.legacy", message)
    }

    /// Legacy convenience constructor for memory errors.
    pub fn memory(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Memory, ErrorCategory::Internal, "memory.legacy", message)
    }

    /// Legacy convenience constructor for configuration errors.
    pub fn config(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Server, ErrorCategory::InvalidInput, "config.legacy", message)
    }

    /// Legacy convenience constructor for artifact errors.
    pub fn artifact(message: impl Into<String>) -> Self {
        Self::new(ErrorComponent::Artifact, ErrorCategory::Internal, "artifact.legacy", message)
    }
}

impl AdkError {
    /// Returns `true` if this error originated in agent logic.
    pub fn is_agent(&self) -> bool {
        self.component == ErrorComponent::Agent
    }
    /// Returns `true` if this error originated in model interaction.
    pub fn is_model(&self) -> bool {
        self.component == ErrorComponent::Model
    }
    /// Returns `true` if this error originated in tool execution.
    pub fn is_tool(&self) -> bool {
        self.component == ErrorComponent::Tool
    }
    /// Returns `true` if this error originated in session management.
    pub fn is_session(&self) -> bool {
        self.component == ErrorComponent::Session
    }
    /// Returns `true` if this error originated in artifact storage.
    pub fn is_artifact(&self) -> bool {
        self.component == ErrorComponent::Artifact
    }
    /// Returns `true` if this error originated in memory operations.
    pub fn is_memory(&self) -> bool {
        self.component == ErrorComponent::Memory
    }
    /// Returns `true` if this is a configuration error (legacy code path).
    pub fn is_config(&self) -> bool {
        self.code == "config.legacy"
    }
}

impl AdkError {
    /// Returns `true` if this error should be retried.
    pub fn is_retryable(&self) -> bool {
        self.retry.should_retry
    }
    /// Returns `true` if this is a not-found error.
    pub fn is_not_found(&self) -> bool {
        self.category == ErrorCategory::NotFound
    }
    /// Returns `true` if this is an unauthorized error.
    pub fn is_unauthorized(&self) -> bool {
        self.category == ErrorCategory::Unauthorized
    }
    /// Returns `true` if this is a rate-limited error.
    pub fn is_rate_limited(&self) -> bool {
        self.category == ErrorCategory::RateLimited
    }
    /// Returns `true` if this is a timeout error.
    pub fn is_timeout(&self) -> bool {
        self.category == ErrorCategory::Timeout
    }
    /// Returns `true` if the write lost a race or used a stale version.
    pub fn is_conflict(&self) -> bool {
        self.category == ErrorCategory::Conflict
    }

    /// Describes the error by its component, category, and code, without its message.
    ///
    /// A message can carry credentials, internal hosts, or upstream response bodies, so this
    /// form is what an agent shows a model for a failure whose message stays local. The code is
    /// a compile-time constant, never caller data.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
    ///
    /// let err = AdkError::new(
    ///     ErrorComponent::Tool,
    ///     ErrorCategory::Unavailable,
    ///     "tool.orders_db.unavailable",
    ///     "connect postgres://admin:secret@db.internal/prod failed",
    /// );
    /// assert_eq!(err.redacted(), "tool.unavailable (tool.orders_db.unavailable)");
    /// ```
    pub fn redacted(&self) -> String {
        format!("{}.{} ({})", self.component, self.category, self.code)
    }

    /// Describes the error for a log line or span field without its message.
    ///
    /// The form is [`redacted`](Self::redacted) followed by the upstream status, provider,
    /// provider error code, and request ID when they are set. A provider error code or
    /// request ID is shown only when it is a short identifier, since both come from the
    /// upstream response.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
    ///
    /// let err = AdkError::new(
    ///     ErrorComponent::Model,
    ///     ErrorCategory::InvalidInput,
    ///     "model.gemini.bad_request",
    ///     "Invalid value at 'contents[0]' (acct-7731)",
    /// )
    /// .with_upstream_status(400)
    /// .with_provider("gemini");
    /// assert_eq!(
    ///     err.diagnostics().to_string(),
    ///     "model.invalid_input (model.gemini.bad_request); status 400; provider gemini"
    /// );
    /// ```
    pub fn diagnostics(&self) -> ErrorDiagnostics<'_> {
        ErrorDiagnostics(self)
    }
}

/// An [`AdkError`] described by everything but its message, from [`AdkError::diagnostics`].
#[derive(Debug, Clone, Copy)]
pub struct ErrorDiagnostics<'a>(&'a AdkError);

impl fmt::Display for ErrorDiagnostics<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let error = self.0;
        write!(f, "{}.{} ({})", error.component, error.category, error.code)?;
        let details = &error.details;
        if let Some(status) = details.upstream_status_code {
            write!(f, "; status {status}")?;
        }
        if let Some(provider) = details.provider.as_deref().filter(|value| is_identifier(value)) {
            write!(f, "; provider {provider}")?;
        }
        if let Some(code) = details
            .metadata
            .get("provider_error_code")
            .and_then(Value::as_str)
            .filter(|value| is_identifier(value))
        {
            write!(f, "; provider code {code}")?;
        }
        if let Some(request_id) = details.request_id.as_deref().filter(|value| is_identifier(value))
        {
            write!(f, "; request id {request_id}")?;
        }
        Ok(())
    }
}

/// Whether `value` is short and limited to ASCII alphanumerics, `_`, `.`, `-`, and `:`.
fn is_identifier(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_.-:".contains(&byte))
}

/// Longest excerpt of upstream text, such as a provider's HTTP error body, that an error
/// message quotes.
pub const UPSTREAM_EXCERPT_BYTES: usize = 512;

/// Returns `text` trimmed and cut to at most [`UPSTREAM_EXCERPT_BYTES`] at a character
/// boundary.
///
/// Provider error bodies can echo the request — prompts, tool arguments, file contents — and
/// can be arbitrarily long, so an error message quotes at most this much of one.
///
/// # Example
///
/// ```rust
/// use adk_core::{UPSTREAM_EXCERPT_BYTES, upstream_excerpt};
///
/// let body = "x".repeat(4 * UPSTREAM_EXCERPT_BYTES);
/// assert_eq!(upstream_excerpt(&body).len(), UPSTREAM_EXCERPT_BYTES);
/// assert_eq!(upstream_excerpt("  bad request \n"), "bad request");
/// ```
pub fn upstream_excerpt(text: &str) -> &str {
    let text = text.trim();
    &text[..text.floor_char_boundary(UPSTREAM_EXCERPT_BYTES)]
}

/// Describes a JSON decoding error by its class and position, without the text it quotes.
///
/// A `serde_json` data error quotes the offending value, such as `invalid type: string
/// "..."`, and a provider response carries generated text and tool arguments, so an error
/// message about an undecodable response uses this description instead.
///
/// # Example
///
/// ```rust
/// use adk_core::json_error_summary;
///
/// let error = serde_json::from_str::<u32>(r#""acct-7731""#).unwrap_err();
/// assert_eq!(json_error_summary(&error), "schema error at line 1 column 11");
/// ```
pub fn json_error_summary(error: &serde_json::Error) -> String {
    let class = match error.classify() {
        serde_json::error::Category::Io => "io",
        serde_json::error::Category::Syntax => "syntax",
        serde_json::error::Category::Data => "schema",
        serde_json::error::Category::Eof => "truncated input",
    };
    match error.line() {
        0 => format!("{class} error"),
        line => format!("{class} error at line {line} column {}", error.column()),
    }
}

impl AdkError {
    /// Maps the error category to an appropriate HTTP status code.
    #[allow(unreachable_patterns)]
    pub fn http_status_code(&self) -> u16 {
        match self.category {
            ErrorCategory::InvalidInput => 400,
            ErrorCategory::Unauthorized => 401,
            ErrorCategory::Forbidden => 403,
            ErrorCategory::NotFound => 404,
            ErrorCategory::RateLimited => 429,
            ErrorCategory::Timeout => 408,
            ErrorCategory::Unavailable => 503,
            ErrorCategory::Cancelled => 499,
            ErrorCategory::Internal => 500,
            ErrorCategory::Unsupported => 501,
            ErrorCategory::ResourceExhausted => 429,
            ErrorCategory::Conflict => 409,
            _ => 500,
        }
    }
}

impl AdkError {
    /// Serializes the error as a JSON Problem Details object.
    pub fn to_problem_json(&self) -> Value {
        json!({
            "error": {
                "code": self.code,
                "message": self.message,
                "component": self.component,
                "category": self.category,
                "requestId": self.details.request_id,
                "retryAfter": self.retry.retry_after_ms,
                "upstreamStatusCode": self.details.upstream_status_code,
            }
        })
    }
}

/// Convenience alias used throughout ADK crates.
pub type Result<T> = std::result::Result<T, AdkError>;

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

    #[test]
    fn test_new_sets_fields() {
        let err = AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::RateLimited,
            "model.rate_limited",
            "too many requests",
        );
        assert_eq!(err.component, ErrorComponent::Model);
        assert_eq!(err.category, ErrorCategory::RateLimited);
        assert_eq!(err.code, "model.rate_limited");
        assert_eq!(err.message, "too many requests");
        assert!(err.retry.should_retry);
    }

    #[test]
    fn test_display_format() {
        let err = AdkError::new(
            ErrorComponent::Session,
            ErrorCategory::NotFound,
            "session.not_found",
            "session xyz not found",
        );
        assert_eq!(err.to_string(), "session.not_found: session xyz not found");
    }

    #[test]
    fn diagnostics_name_every_detail_but_the_message() {
        let mut err = AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::InvalidInput,
            "model.openai.bad_request",
            "Invalid value: 'acct-7731-secret'",
        )
        .with_upstream_status(400)
        .with_provider("openai")
        .with_request_id("req_123");
        err.details.metadata.insert("provider_error_code".into(), json!("invalid_value"));

        assert_eq!(
            err.diagnostics().to_string(),
            "model.invalid_input (model.openai.bad_request); status 400; provider openai; \
             provider code invalid_value; request id req_123"
        );
    }

    #[test]
    fn diagnostics_omit_upstream_values_that_are_not_identifiers() {
        let mut err =
            AdkError::new(ErrorComponent::Model, ErrorCategory::Internal, "model.x", "boom")
                .with_request_id("req 1 acct-7731-secret")
                .with_provider("open\u{1b}]ai");
        err.details.metadata.insert("provider_error_code".into(), json!("a b"));

        assert_eq!(err.diagnostics().to_string(), "model.internal (model.x)");
    }

    #[test]
    fn upstream_excerpt_trims_and_cuts_at_a_character_boundary() {
        let long = format!("  {}🙂tail", "x".repeat(UPSTREAM_EXCERPT_BYTES - 2));
        assert_eq!(upstream_excerpt(&long), "x".repeat(UPSTREAM_EXCERPT_BYTES - 2));
        assert_eq!(upstream_excerpt(" short \n"), "short");
        assert_eq!(upstream_excerpt(""), "");
    }

    #[test]
    fn json_error_summary_never_quotes_the_input() {
        let data = serde_json::from_str::<u32>(r#""acct-7731-secret""#).unwrap_err();
        assert_eq!(json_error_summary(&data), "schema error at line 1 column 18");
        let syntax = serde_json::from_str::<Value>("{acct-7731-secret").unwrap_err();
        assert_eq!(json_error_summary(&syntax), "syntax error at line 1 column 2");
        let eof = serde_json::from_str::<Value>(r#"{"a": "acct"#).unwrap_err();
        assert_eq!(json_error_summary(&eof), "truncated input error at line 1 column 11");
        let from_value = serde_json::from_value::<u32>(json!("acct-7731-secret")).unwrap_err();
        assert_eq!(json_error_summary(&from_value), "schema error");
    }

    #[test]
    fn test_convenience_not_found() {
        let err = AdkError::not_found(ErrorComponent::Session, "session.not_found", "gone");
        assert_eq!(err.category, ErrorCategory::NotFound);
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_convenience_rate_limited() {
        let err = AdkError::rate_limited(ErrorComponent::Model, "model.rate_limited", "slow down");
        assert!(err.is_retryable());
        assert!(err.is_rate_limited());
    }

    #[test]
    fn test_convenience_unauthorized() {
        let err = AdkError::unauthorized(ErrorComponent::Auth, "auth.unauthorized", "bad token");
        assert!(err.is_unauthorized());
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_convenience_internal() {
        let err = AdkError::internal(ErrorComponent::Agent, "agent.internal", "oops");
        assert_eq!(err.category, ErrorCategory::Internal);
    }

    #[test]
    fn test_convenience_timeout() {
        let err = AdkError::timeout(ErrorComponent::Model, "model.timeout", "timed out");
        assert!(err.is_timeout());
        assert!(err.is_retryable());
    }

    #[test]
    fn test_convenience_unavailable() {
        let err = AdkError::unavailable(ErrorComponent::Model, "model.unavailable", "503");
        assert!(err.is_retryable());
    }

    #[test]
    fn test_backward_compat_agent() {
        let err = AdkError::agent("test error");
        assert!(err.is_agent());
        assert_eq!(err.code, "agent.legacy");
        assert_eq!(err.category, ErrorCategory::Internal);
        assert_eq!(err.to_string(), "agent.internal: test error");
    }

    #[test]
    fn test_backward_compat_model() {
        let err = AdkError::model("model fail");
        assert!(err.is_model());
        assert_eq!(err.code, "model.legacy");
    }

    #[test]
    fn test_backward_compat_tool() {
        let err = AdkError::tool("tool fail");
        assert!(err.is_tool());
        assert_eq!(err.code, "tool.legacy");
    }

    #[test]
    fn test_backward_compat_session() {
        let err = AdkError::session("session fail");
        assert!(err.is_session());
        assert_eq!(err.code, "session.legacy");
    }

    #[test]
    fn test_backward_compat_memory() {
        let err = AdkError::memory("memory fail");
        assert!(err.is_memory());
        assert_eq!(err.code, "memory.legacy");
    }

    #[test]
    fn test_backward_compat_artifact() {
        let err = AdkError::artifact("artifact fail");
        assert!(err.is_artifact());
        assert_eq!(err.code, "artifact.legacy");
    }

    #[test]
    fn test_backward_compat_config() {
        let err = AdkError::config("bad config");
        assert!(err.is_config());
        assert_eq!(err.code, "config.legacy");
        assert_eq!(err.component, ErrorComponent::Server);
        assert_eq!(err.category, ErrorCategory::InvalidInput);
    }

    #[test]
    fn test_backward_compat_codes_end_with_legacy() {
        let errors = [
            AdkError::agent("a"),
            AdkError::model("m"),
            AdkError::tool("t"),
            AdkError::session("s"),
            AdkError::memory("mem"),
            AdkError::config("c"),
            AdkError::artifact("art"),
        ];
        for err in &errors {
            assert!(err.code.ends_with(".legacy"), "code '{}' should end with .legacy", err.code);
        }
    }

    #[test]
    fn test_is_config_false_for_non_config() {
        assert!(!AdkError::agent("not config").is_config());
    }

    #[test]
    fn test_retryable_categories_default_true() {
        for cat in [ErrorCategory::RateLimited, ErrorCategory::Unavailable, ErrorCategory::Timeout]
        {
            let err = AdkError::new(ErrorComponent::Model, cat, "test", "msg");
            assert!(err.is_retryable(), "expected is_retryable() == true for {cat}");
        }
    }

    #[test]
    fn test_retryable_override_to_false() {
        let err =
            AdkError::new(ErrorComponent::Model, ErrorCategory::RateLimited, "m.rl", "overridden")
                .with_retry(RetryHint { should_retry: false, ..Default::default() });
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_non_retryable_categories_default_false() {
        for cat in [
            ErrorCategory::InvalidInput,
            ErrorCategory::Unauthorized,
            ErrorCategory::Forbidden,
            ErrorCategory::NotFound,
            ErrorCategory::Cancelled,
            ErrorCategory::Internal,
            ErrorCategory::Unsupported,
            ErrorCategory::ResourceExhausted,
            ErrorCategory::Conflict,
        ] {
            let err = AdkError::new(ErrorComponent::Model, cat, "test", "msg");
            assert!(!err.is_retryable(), "expected is_retryable() == false for {cat}");
        }
    }

    #[test]
    fn test_http_status_code_mapping() {
        let cases = [
            (ErrorCategory::InvalidInput, 400),
            (ErrorCategory::Unauthorized, 401),
            (ErrorCategory::Forbidden, 403),
            (ErrorCategory::NotFound, 404),
            (ErrorCategory::RateLimited, 429),
            (ErrorCategory::Timeout, 408),
            (ErrorCategory::Unavailable, 503),
            (ErrorCategory::Cancelled, 499),
            (ErrorCategory::Internal, 500),
            (ErrorCategory::Unsupported, 501),
            (ErrorCategory::ResourceExhausted, 429),
            (ErrorCategory::Conflict, 409),
        ];
        for (cat, expected) in &cases {
            let err = AdkError::new(ErrorComponent::Server, *cat, "test", "msg");
            assert_eq!(err.http_status_code(), *expected, "wrong status for {cat}");
        }
    }

    #[test]
    fn test_source_returns_some_when_set() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = AdkError::new(ErrorComponent::Session, ErrorCategory::NotFound, "s.f", "missing")
            .with_source(io_err);
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn test_source_returns_none_when_not_set() {
        assert!(std::error::Error::source(&AdkError::agent("no source")).is_none());
    }

    #[test]
    fn test_retry_hint_for_category() {
        assert!(RetryHint::for_category(ErrorCategory::RateLimited).should_retry);
        assert!(RetryHint::for_category(ErrorCategory::Unavailable).should_retry);
        assert!(RetryHint::for_category(ErrorCategory::Timeout).should_retry);
        assert!(!RetryHint::for_category(ErrorCategory::Internal).should_retry);
        assert!(!RetryHint::for_category(ErrorCategory::NotFound).should_retry);
    }

    #[test]
    fn test_retry_hint_with_retry_after() {
        let hint = RetryHint::default().with_retry_after(Duration::from_secs(5));
        assert_eq!(hint.retry_after_ms, Some(5000));
        assert_eq!(hint.retry_after(), Some(Duration::from_secs(5)));
    }

    #[test]
    fn test_to_problem_json() {
        let err = AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::RateLimited,
            "model.rate_limited",
            "slow down",
        )
        .with_request_id("req-123")
        .with_upstream_status(429);
        let j = err.to_problem_json();
        let o = &j["error"];
        assert_eq!(o["code"], "model.rate_limited");
        assert_eq!(o["message"], "slow down");
        assert_eq!(o["component"], "model");
        assert_eq!(o["category"], "rate_limited");
        assert_eq!(o["requestId"], "req-123");
        assert_eq!(o["upstreamStatusCode"], 429);
    }

    #[test]
    fn test_conflict_category() {
        let err = AdkError::new(
            ErrorComponent::Agent,
            ErrorCategory::Conflict,
            "run_store.stale_epoch",
            "stale",
        );
        assert!(err.is_conflict());
        assert!(!err.is_retryable());
        assert_eq!(err.http_status_code(), 409);
        assert_eq!(ErrorCategory::Conflict.to_string(), "conflict");
        assert_eq!(err.to_problem_json()["error"]["category"], "conflict");
    }

    #[test]
    fn test_to_problem_json_null_optionals() {
        let j = AdkError::agent("simple").to_problem_json();
        let o = &j["error"];
        assert!(o["requestId"].is_null());
        assert!(o["retryAfter"].is_null());
        assert!(o["upstreamStatusCode"].is_null());
    }

    #[test]
    fn test_builder_chaining() {
        let err = AdkError::new(ErrorComponent::Model, ErrorCategory::Unavailable, "m.u", "down")
            .with_provider("openai")
            .with_request_id("req-456")
            .with_upstream_status(503)
            .with_retry(RetryHint {
                should_retry: true,
                retry_after_ms: Some(1000),
                max_attempts: Some(3),
            });
        assert_eq!(err.details.provider.as_deref(), Some("openai"));
        assert_eq!(err.details.request_id.as_deref(), Some("req-456"));
        assert_eq!(err.details.upstream_status_code, Some(503));
        assert!(err.is_retryable());
        assert_eq!(err.retry.retry_after_ms, Some(1000));
        assert_eq!(err.retry.max_attempts, Some(3));
    }

    #[test]
    fn test_error_component_display() {
        assert_eq!(ErrorComponent::Agent.to_string(), "agent");
        assert_eq!(ErrorComponent::Model.to_string(), "model");
        assert_eq!(ErrorComponent::Graph.to_string(), "graph");
        assert_eq!(ErrorComponent::Realtime.to_string(), "realtime");
        assert_eq!(ErrorComponent::Deploy.to_string(), "deploy");
    }

    #[test]
    fn test_error_category_display() {
        assert_eq!(ErrorCategory::InvalidInput.to_string(), "invalid_input");
        assert_eq!(ErrorCategory::RateLimited.to_string(), "rate_limited");
        assert_eq!(ErrorCategory::NotFound.to_string(), "not_found");
        assert_eq!(ErrorCategory::Internal.to_string(), "internal");
    }

    #[test]
    #[allow(clippy::unnecessary_literal_unwrap)]
    fn test_result_type() {
        let ok: Result<i32> = Ok(42);
        assert_eq!(ok.unwrap(), 42);
        let err: Result<i32> = Err(AdkError::config("invalid"));
        assert!(err.is_err());
    }

    #[test]
    fn test_with_details() {
        let d = ErrorDetails {
            upstream_status_code: Some(502),
            request_id: Some("abc".into()),
            provider: Some("gemini".into()),
            metadata: HashMap::new(),
        };
        let err = AdkError::agent("test").with_details(d);
        assert_eq!(err.details.upstream_status_code, Some(502));
        assert_eq!(err.details.request_id.as_deref(), Some("abc"));
        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
    }

    #[test]
    fn test_debug_impl() {
        let s = format!("{:?}", AdkError::agent("debug test"));
        assert!(s.contains("AdkError"));
        assert!(s.contains("agent.legacy"));
    }

    #[test]
    fn test_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        assert_send::<AdkError>();
        assert_sync::<AdkError>();
    }
}