adk-core 2.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
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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
use crate::identity::{AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId};
use crate::{AdkError, Agent, Result, Toolset, types::Content};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

/// Policy for handling excess tool calls when the concurrency limit is reached.
///
/// Determines whether tool calls that exceed the configured concurrency limit
/// should wait in a queue or fail immediately.
///
/// # Example
///
/// ```rust
/// use adk_core::BackpressurePolicy;
///
/// // Default is Queue
/// let policy = BackpressurePolicy::default();
/// assert!(matches!(policy, BackpressurePolicy::Queue));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BackpressurePolicy {
    /// Queue excess calls until a permit becomes available.
    ///
    /// This is the default policy. Tool calls will await until a semaphore
    /// permit is released by a completing tool execution.
    #[default]
    Queue,

    /// Fail immediately with a concurrency limit error when no permit is available.
    ///
    /// Use this when latency is more important than throughput — callers receive
    /// an immediate error rather than waiting indefinitely.
    Fail,
}

/// Configuration for tool execution concurrency.
///
/// Controls how many tool calls can execute simultaneously, with support for
/// global limits, per-tool overrides, and configurable backpressure behavior.
///
/// # Example
///
/// ```rust
/// use adk_core::{BackpressurePolicy, ToolConcurrencyConfig};
/// use std::collections::HashMap;
///
/// let config = ToolConcurrencyConfig {
///     max_concurrency: Some(10),
///     per_tool: HashMap::from([
///         ("web_scraper".to_string(), 2),
///         ("calculator".to_string(), 8),
///     ]),
///     backpressure: BackpressurePolicy::Fail,
/// };
///
/// assert_eq!(config.max_concurrency, Some(10));
/// assert_eq!(config.per_tool.get("web_scraper"), Some(&2));
/// ```
#[derive(Debug, Clone, Default)]
pub struct ToolConcurrencyConfig {
    /// Global maximum concurrent tool calls. `None` means unlimited.
    pub max_concurrency: Option<usize>,

    /// Per-tool concurrency overrides. When a tool name is present in this map,
    /// its individual limit takes precedence over the global `max_concurrency`.
    pub per_tool: HashMap<String, usize>,

    /// What to do when the concurrency limit is reached.
    pub backpressure: BackpressurePolicy,
}

/// Read-only access to invocation metadata.
///
/// Provides identity information (user, app, session, invocation) and the
/// current user content. Implemented by all context types.
#[async_trait]
pub trait ReadonlyContext: Send + Sync {
    /// Returns the current invocation identifier.
    fn invocation_id(&self) -> &str;
    /// Returns the name of the currently executing agent.
    fn agent_name(&self) -> &str;
    /// Returns the user identifier for this session.
    fn user_id(&self) -> &str;
    /// Returns the application name for this session.
    fn app_name(&self) -> &str;
    /// Returns the session identifier.
    fn session_id(&self) -> &str;
    /// Returns the current conversation branch.
    fn branch(&self) -> &str;
    /// Returns the user's input content for this invocation.
    fn user_content(&self) -> &Content;

    /// Returns the application name as a typed [`AppName`].
    ///
    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
    /// error if the raw string fails validation (empty, null bytes, or exceeds
    /// the maximum length).
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_app_name(&self) -> Result<AppName> {
        Ok(AppName::try_from(self.app_name())?)
    }

    /// Returns the user identifier as a typed [`UserId`].
    ///
    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
    /// error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_user_id(&self) -> Result<UserId> {
        Ok(UserId::try_from(self.user_id())?)
    }

    /// Returns the session identifier as a typed [`SessionId`].
    ///
    /// Parses the value returned by [`session_id()`](Self::session_id).
    /// Returns an error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_session_id(&self) -> Result<SessionId> {
        Ok(SessionId::try_from(self.session_id())?)
    }

    /// Returns the invocation identifier as a typed [`InvocationId`].
    ///
    /// Parses the value returned by [`invocation_id()`](Self::invocation_id).
    /// Returns an error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_invocation_id(&self) -> Result<InvocationId> {
        Ok(InvocationId::try_from(self.invocation_id())?)
    }

    /// Returns the stable session-scoped [`AdkIdentity`] triple.
    ///
    /// Combines [`try_app_name()`](Self::try_app_name),
    /// [`try_user_id()`](Self::try_user_id), and
    /// [`try_session_id()`](Self::try_session_id) into a single composite
    /// identity value.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the three constituent identifiers fail
    /// validation.
    fn try_identity(&self) -> Result<AdkIdentity> {
        Ok(AdkIdentity {
            app_name: self.try_app_name()?,
            user_id: self.try_user_id()?,
            session_id: self.try_session_id()?,
        })
    }

    /// Returns the full per-invocation [`ExecutionIdentity`].
    ///
    /// Combines [`try_identity()`](Self::try_identity) with the invocation,
    /// branch, and agent name from this context.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the four typed identifiers fail validation.
    fn try_execution_identity(&self) -> Result<ExecutionIdentity> {
        Ok(ExecutionIdentity {
            adk: self.try_identity()?,
            invocation_id: self.try_invocation_id()?,
            branch: self.branch().to_string(),
            agent_name: self.agent_name().to_string(),
        })
    }
}

// State management traits

/// Maximum allowed length for state keys (256 bytes).
pub const MAX_STATE_KEY_LEN: usize = 256;

/// Validates a state key. Returns `Ok(())` if the key is safe, or an error message.
///
/// Rules:
/// - Must not be empty
/// - Must not exceed [`MAX_STATE_KEY_LEN`] bytes
/// - Must not contain path separators (`/`, `\`) or `..`
/// - Must not contain null bytes
pub fn validate_state_key(key: &str) -> std::result::Result<(), &'static str> {
    if key.is_empty() {
        return Err("state key must not be empty");
    }
    if key.len() > MAX_STATE_KEY_LEN {
        return Err("state key exceeds maximum length of 256 bytes");
    }
    if key.contains('/') || key.contains('\\') || key.contains("..") {
        return Err("state key must not contain path separators or '..'");
    }
    if key.contains('\0') {
        return Err("state key must not contain null bytes");
    }
    Ok(())
}

/// Mutable session state with key-value storage.
///
/// Implementations persist state across turns within a session.
pub trait State: Send + Sync {
    /// Returns the value for the given key, or `None` if not present.
    fn get(&self, key: &str) -> Option<Value>;
    /// Set a state value. Implementations should call [`validate_state_key`] and
    /// reject invalid keys (e.g., by logging a warning or panicking).
    fn set(&mut self, key: String, value: Value);
    /// Returns all key-value pairs in the state.
    fn all(&self) -> HashMap<String, Value>;
}

/// Read-only view of session state.
pub trait ReadonlyState: Send + Sync {
    /// Returns the value for the given key, or `None` if not present.
    fn get(&self, key: &str) -> Option<Value>;
    /// Returns all key-value pairs in the state.
    fn all(&self) -> HashMap<String, Value>;
}

// Session trait
/// Represents an active conversation session with identity and state.
pub trait Session: Send + Sync {
    /// Returns the session identifier.
    fn id(&self) -> &str;
    /// Returns the application name this session belongs to.
    fn app_name(&self) -> &str;
    /// Returns the user identifier for this session.
    fn user_id(&self) -> &str;
    /// Returns the mutable state associated with this session.
    fn state(&self) -> &dyn State;
    /// Returns the conversation history from this session as Content items
    fn conversation_history(&self) -> Vec<Content>;
    /// Returns conversation history filtered for a specific agent.
    ///
    /// When provided, events authored by other agents (not "user", not the
    /// named agent, and not function/tool responses) are excluded. This
    /// prevents a transferred sub-agent from seeing the parent's tool calls
    /// mapped as "model" role, which would cause the LLM to think work is
    /// already done.
    ///
    /// Default implementation delegates to [`conversation_history`](Self::conversation_history).
    fn conversation_history_for_agent(&self, _agent_name: &str) -> Vec<Content> {
        self.conversation_history()
    }
    /// Returns conversation history scoped to an agent and a conversation branch.
    ///
    /// `branch` is the invocation branch of the agent asking for history. An
    /// event is visible when its branch equals that branch or is an *ancestor*
    /// of it, so a sub-agent sees the conversation that led to it but not what
    /// its siblings produced. `ParallelAgent` relies on this to keep concurrent
    /// branches from contaminating each other's context, mirroring ADK Python's
    /// `_is_event_belongs_to_branch` and ADK Go's `eventBelongsToBranch`.
    ///
    /// An empty `branch` on either side means "unscoped" and matches everything,
    /// so implementations that never set [`crate::Event::branch`] are unaffected.
    ///
    /// Default implementation ignores `branch` and preserves the agent-name
    /// filtering behaviour, so existing [`Session`] implementations keep working.
    fn conversation_history_scoped(&self, agent_name: Option<&str>, _branch: &str) -> Vec<Content> {
        match agent_name {
            Some(name) => self.conversation_history_for_agent(name),
            None => self.conversation_history(),
        }
    }
    /// Append content to conversation history (for sequential agent support)
    fn append_to_history(&self, _content: Content) {
        // Default no-op - implementations can override to track history
    }

    /// Returns the application name as a typed [`AppName`].
    ///
    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
    /// error if the raw string fails validation (empty, null bytes, or exceeds
    /// the maximum length).
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_app_name(&self) -> Result<AppName> {
        Ok(AppName::try_from(self.app_name())?)
    }

    /// Returns the user identifier as a typed [`UserId`].
    ///
    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
    /// error if the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_user_id(&self) -> Result<UserId> {
        Ok(UserId::try_from(self.user_id())?)
    }

    /// Returns the session identifier as a typed [`SessionId`].
    ///
    /// Parses the value returned by [`id()`](Self::id). Returns an error if
    /// the raw string fails validation.
    ///
    /// # Errors
    ///
    /// Returns an error when the
    /// underlying string is not a valid identifier.
    fn try_session_id(&self) -> Result<SessionId> {
        Ok(SessionId::try_from(self.id())?)
    }

    /// Returns the stable session-scoped [`AdkIdentity`] triple.
    ///
    /// Combines [`try_app_name()`](Self::try_app_name),
    /// [`try_user_id()`](Self::try_user_id), and
    /// [`try_session_id()`](Self::try_session_id) into a single composite
    /// identity value.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the three constituent identifiers fail
    /// validation.
    fn try_identity(&self) -> Result<AdkIdentity> {
        Ok(AdkIdentity {
            app_name: self.try_app_name()?,
            user_id: self.try_user_id()?,
            session_id: self.try_session_id()?,
        })
    }
}

/// Structured metadata about a completed tool execution.
///
/// Available via [`CallbackContext::tool_outcome()`] in after-tool callbacks,
/// plugins, and telemetry hooks. Provides structured access to execution
/// results without requiring JSON error parsing.
///
/// # Fields
///
/// - `tool_name` — Name of the tool that was executed.
/// - `tool_args` — Arguments passed to the tool as a JSON value.
/// - `success` — Whether the tool execution succeeded. Derived from the
///   Rust `Result` / timeout path, never from JSON content inspection.
/// - `duration` — Wall-clock duration of the tool execution.
/// - `error_message` — Error message if the tool failed; `None` on success.
/// - `attempt` — Retry attempt number (0 = first attempt, 1 = first retry, etc.).
///   Always 0 when retries are not configured.
#[derive(Debug, Clone)]
pub struct ToolOutcome {
    /// Name of the tool that was executed.
    pub tool_name: String,
    /// Arguments passed to the tool (JSON value).
    pub tool_args: serde_json::Value,
    /// Whether the tool execution succeeded.
    pub success: bool,
    /// Wall-clock duration of the tool execution.
    pub duration: std::time::Duration,
    /// Error message if the tool failed. `None` on success.
    pub error_message: Option<String>,
    /// Retry attempt number (0 = first attempt, 1 = first retry, etc.).
    /// Always 0 when retries are not configured.
    pub attempt: u32,
}

/// Context available to agent lifecycle callbacks.
///
/// Extends [`ReadonlyContext`] with access to artifacts and tool execution metadata.
#[async_trait]
pub trait CallbackContext: ReadonlyContext {
    /// Returns the artifact store, if one is configured.
    fn artifacts(&self) -> Option<Arc<dyn Artifacts>>;

    /// Returns structured metadata about the most recent tool execution.
    /// Available in after-tool callbacks and plugin hooks.
    /// Returns `None` when not in a tool execution context.
    fn tool_outcome(&self) -> Option<ToolOutcome> {
        None // default for backward compatibility
    }

    /// Returns the name of the tool about to be executed.
    /// Available in before-tool and after-tool callback contexts.
    fn tool_name(&self) -> Option<&str> {
        None
    }

    /// Returns the input arguments for the tool about to be executed.
    /// Available in before-tool and after-tool callback contexts.
    fn tool_input(&self) -> Option<&serde_json::Value> {
        None
    }

    /// Returns the shared state for parallel agent coordination.
    /// Returns `None` when not running inside a `ParallelAgent` with shared state enabled.
    fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
        None
    }
}

/// Wraps a [`CallbackContext`] to inject tool name and input for before-tool
/// and after-tool callbacks.
///
/// Used by the agent runtime to provide tool context to `BeforeToolCallback`
/// and `AfterToolCallback` invocations.
///
/// # Example
///
/// ```rust,ignore
/// let tool_ctx = Arc::new(ToolCallbackContext::new(
///     ctx.clone(),
///     "search".to_string(),
///     serde_json::json!({"query": "hello"}),
/// ));
/// callback(tool_ctx as Arc<dyn CallbackContext>).await;
/// ```
pub struct ToolCallbackContext {
    /// The inner callback context to delegate to.
    pub inner: Arc<dyn CallbackContext>,
    /// The name of the tool being executed.
    pub tool_name: String,
    /// The input arguments for the tool being executed.
    pub tool_input: serde_json::Value,
}

impl ToolCallbackContext {
    /// Creates a new `ToolCallbackContext` wrapping the given inner context.
    pub fn new(
        inner: Arc<dyn CallbackContext>,
        tool_name: String,
        tool_input: serde_json::Value,
    ) -> Self {
        Self { inner, tool_name, tool_input }
    }
}

#[async_trait]
impl ReadonlyContext for ToolCallbackContext {
    fn invocation_id(&self) -> &str {
        self.inner.invocation_id()
    }

    fn agent_name(&self) -> &str {
        self.inner.agent_name()
    }

    fn user_id(&self) -> &str {
        self.inner.user_id()
    }

    fn app_name(&self) -> &str {
        self.inner.app_name()
    }

    fn session_id(&self) -> &str {
        self.inner.session_id()
    }

    fn branch(&self) -> &str {
        self.inner.branch()
    }

    fn user_content(&self) -> &Content {
        self.inner.user_content()
    }
}

#[async_trait]
impl CallbackContext for ToolCallbackContext {
    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
        self.inner.artifacts()
    }

    fn tool_outcome(&self) -> Option<ToolOutcome> {
        self.inner.tool_outcome()
    }

    fn tool_name(&self) -> Option<&str> {
        Some(&self.tool_name)
    }

    fn tool_input(&self) -> Option<&serde_json::Value> {
        Some(&self.tool_input)
    }

    fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
        self.inner.shared_state()
    }
}

/// Full invocation context available to agents during execution.
///
/// Extends [`CallbackContext`] with access to the agent itself, memory,
/// session, and run configuration.
#[async_trait]
pub trait InvocationContext: CallbackContext {
    /// Returns the agent being executed.
    fn agent(&self) -> Arc<dyn Agent>;
    /// Returns the memory service, if one is configured.
    fn memory(&self) -> Option<Arc<dyn Memory>>;
    /// Returns the current session.
    fn session(&self) -> &dyn Session;
    /// Returns the run configuration for this invocation.
    fn run_config(&self) -> &RunConfig;
    /// Signals that this invocation should end after the current turn.
    fn end_invocation(&self);
    /// Returns whether the invocation has been ended.
    fn ended(&self) -> bool;

    /// Returns `true` if this invocation has been cancelled.
    ///
    /// Agents and tools can poll this during long-running work (LLM streaming,
    /// HTTP I/O, tool execution) to detect an external cancellation request —
    /// for example, a user pressing "Stop" or a call to
    /// [`Runner::interrupt`](https://docs.rs/adk-runner). Checking it at chunk
    /// or tool boundaries lets an agent exit promptly and perform any graceful
    /// cleanup instead of running to natural completion.
    ///
    /// The default returns `false`. The runtime sets the underlying token when
    /// `Runner::interrupt()` is called or `RunConfig::cancellation_token` fires.
    fn is_cancelled(&self) -> bool {
        false
    }

    /// Returns the scopes granted to the current user for this invocation.
    ///
    /// When a [`RequestContext`](crate::RequestContext) is present (set by the
    /// server's auth middleware bridge), this returns the scopes from that
    /// context. The default returns an empty vec (no scopes granted).
    fn user_scopes(&self) -> Vec<String> {
        vec![]
    }

    /// Returns the request metadata from the auth middleware bridge, if present.
    ///
    /// This provides access to custom key-value pairs extracted from the HTTP
    /// request by the [`RequestContextExtractor`](crate::RequestContext).
    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
        HashMap::new()
    }

    /// Retrieve a secret by name from the configured secret provider.
    ///
    /// Returns `Ok(Some(value))` when a provider is configured and the secret
    /// exists, `Ok(None)` when no provider is configured, or an error on
    /// provider failure. The default returns `Ok(None)`.
    async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
        Ok(None)
    }

    /// Resolves a secret for a described access.
    ///
    /// A wrapper context must forward this, and a tool context builds the request from
    /// the identity the framework gave it. The default drops the description and calls
    /// [`InvocationContext::get_secret`], which keeps a context that predates the
    /// request object working.
    async fn get_secret_for(&self, request: &SecretRequest) -> Result<Option<String>> {
        self.get_secret(&request.name).await
    }
}

// Placeholder service traits
/// Binary artifact storage for agents.
#[async_trait]
pub trait Artifacts: Send + Sync {
    /// Saves a binary artifact and returns its version number.
    async fn save(&self, name: &str, data: &crate::Part) -> Result<i64>;
    /// Loads a binary artifact by name.
    async fn load(&self, name: &str) -> Result<crate::Part>;
    /// Lists all artifact names.
    async fn list(&self) -> Result<Vec<String>>;
}

/// Semantic memory search for agents.
#[async_trait]
pub trait Memory: Send + Sync {
    /// Searches memory for entries matching the query.
    async fn search(&self, query: &str) -> Result<Vec<MemoryEntry>>;

    /// Verify backend connectivity.
    ///
    /// The default implementation succeeds, which is suitable for in-memory
    /// implementations and adapters without an external dependency.
    async fn health_check(&self) -> Result<()> {
        Ok(())
    }

    /// Add a single memory entry.
    ///
    /// The default implementation returns an "not implemented" error, which is
    /// suitable for read-only memory backends.
    async fn add(&self, entry: MemoryEntry) -> Result<()> {
        let _ = entry;
        Err(AdkError::memory("add not implemented"))
    }

    /// Delete entries matching a query. Returns count of deleted entries.
    ///
    /// The default implementation returns an "not implemented" error, which is
    /// suitable for read-only memory backends.
    async fn delete(&self, query: &str) -> Result<u64> {
        let _ = query;
        Err(AdkError::memory("delete not implemented"))
    }

    /// Whether this memory keeps project-scoped entries isolated.
    ///
    /// Returns `false` by default, so a caller can tell real isolation apart from a
    /// memory that has no project support instead of inferring it from data.
    fn supports_project_scoping(&self) -> bool {
        false
    }

    /// Searches memories within a specific project.
    ///
    /// # Errors
    ///
    /// The default implementation returns an error. Delegating to the global search
    /// would return entries the project boundary is meant to exclude, and nothing in
    /// the result would say the boundary was ignored.
    async fn search_in_project(&self, query: &str, project_id: &str) -> Result<Vec<MemoryEntry>> {
        let _ = (query, project_id);
        Err(AdkError::memory(
            "this memory does not implement project scoping, so `search_in_project` cannot \
             honour the project boundary; check `supports_project_scoping` first, or call \
             `search` if global scope is intended",
        ))
    }

    /// Adds a memory entry scoped to a specific project.
    ///
    /// # Errors
    ///
    /// Returns an error by default. Writing the entry globally would make data
    /// intended for one project visible everywhere under the same app and user.
    async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> Result<()> {
        let _ = (entry, project_id);
        Err(AdkError::memory(
            "this memory does not implement project scoping, so `add_to_project` cannot honour \
             the project boundary; check `supports_project_scoping` first, or call `add` if \
             global scope is intended",
        ))
    }
}

/// Trait for retrieving secrets at runtime.
///
/// This is the core-level abstraction used by `ToolContext::get_secret` and
/// `InvocationContext::get_secret`. Concrete implementations (e.g., AWS
/// Secrets Manager, Azure Key Vault, GCP Secret Manager) live in `adk-auth`
/// behind feature flags and implement this trait via the `SecretProvider`
/// adapter.
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::SecretService;
///
/// struct EnvSecretService;
///
/// #[async_trait::async_trait]
/// impl SecretService for EnvSecretService {
///     async fn get_secret(&self, name: &str) -> adk_core::Result<String> {
///         std::env::var(name).map_err(|_| adk_core::AdkError::not_found(
///             format!("secret '{name}' not found in environment"),
///         ))
///     }
/// }
/// ```
#[async_trait]
pub trait SecretService: Send + Sync {
    /// Retrieve a secret value by name.
    ///
    /// Returns the secret string on success, or an [`AdkError`] on failure.
    async fn get_secret(&self, name: &str) -> Result<String>;

    /// Retrieve a secret for a described access.
    ///
    /// This is the form an authorizing service implements: the request carries who is
    /// asking and why, so a decision can be made before the value is fetched. The
    /// default implementation ignores the context and calls
    /// [`SecretService::get_secret`], which is correct for a service that has no
    /// policy of its own.
    ///
    /// Every field on [`SecretRequest`] is set by the framework at the call site, not
    /// supplied by the tool, so a tool cannot present another tool's identity.
    async fn get_secret_for(&self, request: &SecretRequest) -> Result<String> {
        self.get_secret(&request.name).await
    }
}

/// A described secret access.
///
/// Carries the requested name plus the identity the framework observed at the call
/// site, so a [`SecretService`] can authorize and audit rather than being handed a
/// bare name with no context.
///
/// # Example
///
/// ```rust
/// use adk_core::SecretRequest;
///
/// let request = SecretRequest::new("payments-api-key")
///     .with_tool_name("charge_card")
///     .with_purpose("authorize a customer payment");
///
/// assert_eq!(request.tool_name.as_deref(), Some("charge_card"));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SecretRequest {
    /// Name of the requested secret.
    pub name: String,
    /// The tool making the request, when the access came from a tool.
    ///
    /// Set by the framework from the tool it dispatched, never from a value the tool
    /// provided.
    pub tool_name: Option<String>,
    /// Application the run belongs to.
    pub app_name: Option<String>,
    /// Authenticated user the run belongs to.
    pub user_id: Option<String>,
    /// Session the run belongs to.
    pub session_id: Option<String>,
    /// Invocation the access happened in, for correlating audit records.
    pub invocation_id: Option<String>,
    /// Why the secret is needed, when the caller states it.
    pub purpose: Option<String>,
}

impl SecretRequest {
    /// Creates a request for `name` with no identity attached.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into(), ..Default::default() }
    }

    /// Attaches the requesting tool's name.
    #[must_use]
    pub fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_name = Some(tool_name.into());
        self
    }

    /// Attaches the run's identity.
    #[must_use]
    pub fn with_identity(
        mut self,
        app_name: impl Into<String>,
        user_id: impl Into<String>,
        session_id: impl Into<String>,
    ) -> Self {
        self.app_name = Some(app_name.into());
        self.user_id = Some(user_id.into());
        self.session_id = Some(session_id.into());
        self
    }

    /// Attaches the invocation the access happened in.
    #[must_use]
    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
        self.invocation_id = Some(invocation_id.into());
        self
    }

    /// Attaches a stated purpose.
    #[must_use]
    pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
        self.purpose = Some(purpose.into());
        self
    }
}

/// A single entry returned from memory search.
#[derive(Debug, Clone)]
pub struct MemoryEntry {
    /// The content of this memory entry.
    pub content: Content,
    /// The author who created this memory entry.
    pub author: String,
}

/// Streaming mode for agent responses.
/// Matches ADK Python/Go specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StreamingMode {
    /// No streaming; responses delivered as complete units.
    /// Agent collects all chunks internally and yields a single final event.
    None,
    /// Server-Sent Events streaming; one-way streaming from server to client.
    /// Agent yields each chunk as it arrives with stable event ID.
    #[default]
    SSE,
    /// Bidirectional streaming; simultaneous communication in both directions.
    /// Used for realtime audio/video agents.
    Bidi,
}

/// Controls what parts of prior conversation history is received by llmagent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IncludeContents {
    /// The llmagent operates solely on its current turn (latest user input + any following agent events)
    None,
    /// Default - The llmagent receives the relevant conversation history
    #[default]
    Default,
}

/// Decision applied when a tool execution requires human confirmation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationDecision {
    /// Approve the tool execution.
    Approve,
    /// Deny the tool execution.
    Deny,
}

/// Produces a canonical fingerprint of a tool call.
///
/// The fingerprint is the tool name followed by its arguments in canonical JSON
/// form, with object keys sorted at every level so that two structurally equal
/// argument sets always produce the same string. It is deliberately readable
/// rather than hashed, so a mismatch can be diagnosed by inspection.
///
/// Use it with
/// [`RunConfig::tool_confirmation_fingerprints`](RunConfig::tool_confirmation_fingerprints)
/// to bind an approval to the exact arguments it was granted for.
///
/// # Example
///
/// ```rust
/// use adk_core::tool_call_fingerprint;
/// use serde_json::json;
///
/// // Key order does not change the fingerprint.
/// let a = tool_call_fingerprint("delete_file", &json!({ "path": "/tmp/a", "force": true }));
/// let b = tool_call_fingerprint("delete_file", &json!({ "force": true, "path": "/tmp/a" }));
/// assert_eq!(a, b);
///
/// // A different path does not.
/// let c = tool_call_fingerprint("delete_file", &json!({ "path": "/etc/passwd", "force": true }));
/// assert_ne!(a, c);
/// ```
pub fn tool_call_fingerprint(tool_name: &str, args: &Value) -> String {
    let mut out = String::with_capacity(tool_name.len() + 32);
    out.push_str(tool_name);
    out.push('\u{1f}');
    write_canonical(args, &mut out);
    out
}

/// Writes `value` as canonical JSON, with object keys sorted at every level.
fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, key) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String((*key).clone()).to_string());
                out.push(':');
                write_canonical(&map[*key], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

/// Policy defining which tools require human confirmation before execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationPolicy {
    /// No tool confirmation is required.
    #[default]
    Never,
    /// Every tool call requires confirmation.
    Always,
    /// Only the listed tool names require confirmation.
    PerTool(BTreeSet<String>),
}

impl ToolConfirmationPolicy {
    /// Returns true when the given tool name must be confirmed before execution.
    pub fn requires_confirmation(&self, tool_name: &str) -> bool {
        match self {
            Self::Never => false,
            Self::Always => true,
            Self::PerTool(tools) => tools.contains(tool_name),
        }
    }

    /// Add one tool name to the confirmation policy (converts `Never` to `PerTool`).
    pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
        let tool_name = tool_name.into();
        match &mut self {
            Self::Never => {
                let mut tools = BTreeSet::new();
                tools.insert(tool_name);
                Self::PerTool(tools)
            }
            Self::Always => Self::Always,
            Self::PerTool(tools) => {
                tools.insert(tool_name);
                self
            }
        }
    }
}

/// Payload describing a tool call awaiting human confirmation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfirmationRequest {
    /// Name of the tool awaiting confirmation.
    pub tool_name: String,
    /// The function call ID from the LLM, if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call_id: Option<String>,
    /// Arguments the tool would be called with.
    pub args: Value,
}

/// Asynchronous decision source for tool calls that require confirmation.
///
/// Front ends and protocol adapters can implement this trait to pause an
/// invocation while a person or an external policy service reviews the exact
/// tool call. When no handler is configured, agents preserve the existing
/// behavior and emit an interrupted confirmation event for a later run.
#[async_trait]
pub trait ToolConfirmationHandler: std::fmt::Debug + Send + Sync {
    /// Approve or deny one pending tool call.
    async fn decide(&self, request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision>;
}

/// A toolset attached to one runner invocation rather than compiled into the
/// agent definition.
///
/// Protocol adapters use this wrapper for session-scoped capabilities such as
/// MCP servers supplied by an ACP client. The wrapper keeps [`RunConfig`]
/// debuggable without requiring every toolset implementation to implement
/// [`std::fmt::Debug`].
#[derive(Clone)]
pub struct RuntimeToolset(Arc<dyn Toolset>);

impl RuntimeToolset {
    /// Wrap a toolset for use during one runner invocation.
    pub fn new(toolset: Arc<dyn Toolset>) -> Self {
        Self(toolset)
    }

    /// Borrow the wrapped toolset.
    pub fn toolset(&self) -> &Arc<dyn Toolset> {
        &self.0
    }
}

impl std::fmt::Debug for RuntimeToolset {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_tuple("RuntimeToolset").field(&self.0.name()).finish()
    }
}

/// Configuration for a single agent run.
///
/// Controls streaming behavior, tool confirmation, caching, transfer targets,
/// and concurrency settings. Use [`RunConfig::builder()`] to construct from
#[derive(Debug, Clone)]
pub struct RunConfig {
    /// The streaming mode for agent responses.
    pub streaming_mode: StreamingMode,
    /// Static confirmation decisions for the current run, keyed by **function
    /// call ID**.
    ///
    /// The ID is the one reported on
    /// [`ToolConfirmationRequest::function_call_id`], so a decision authorizes the
    /// exact call it was requested for. A decision under a tool *name* is not
    /// consulted, because one name can cover materially different calls — a
    /// `delete_file` approval for a scratch path must not authorize a call that
    /// targets a different path.
    ///
    /// Use [`tool_confirmation_fingerprints`](Self::tool_confirmation_fingerprints)
    /// to additionally bind a decision to the arguments it was granted for. For
    /// name-wide or policy-driven decisions, supply a
    /// [`tool_confirmation_handler`](Self::tool_confirmation_handler) instead.
    pub tool_confirmation_decisions: HashMap<String, ToolConfirmationDecision>,
    /// Optional argument binding for entries in
    /// [`tool_confirmation_decisions`](Self::tool_confirmation_decisions), keyed by
    /// the same function call ID.
    ///
    /// The value is the fingerprint produced by [`tool_call_fingerprint`] for the
    /// call the decision was granted for. When an entry is present and the actual
    /// call does not match it, the decision is ignored and the call is treated as
    /// unconfirmed — the safe direction. Use this when a decision travels through
    /// an untrusted round trip, such as a browser, where the arguments could be
    /// changed while the call ID is replayed.
    pub tool_confirmation_fingerprints: HashMap<String, String>,
    /// Optional live decision source for confirmations that have no static
    /// entry in [`tool_confirmation_decisions`](Self::tool_confirmation_decisions).
    pub tool_confirmation_handler: Option<Arc<dyn ToolConfirmationHandler>>,
    /// Toolsets made available only for this invocation.
    pub runtime_toolsets: Vec<RuntimeToolset>,
    /// Optional cached content name for automatic prompt caching.
    /// When set by the runner's cache lifecycle manager, agents should attach
    /// this name to their `GenerateContentConfig` so the LLM provider can
    /// reuse cached system instructions and tool definitions.
    pub cached_content: Option<String>,
    /// Valid agent names this agent can transfer to (parent, peers, children).
    /// Set by the runner when invoking agents in a multi-agent tree.
    /// When non-empty, the `transfer_to_agent` tool is injected and validation
    /// uses this list instead of only checking `sub_agents`.
    pub transfer_targets: Vec<String>,
    /// The name of the parent agent, if this agent was invoked via transfer.
    /// Used by the agent to apply `disallow_transfer_to_parent` filtering.
    pub parent_agent: Option<String>,
    /// Enable automatic prompt caching for all providers that support it.
    ///
    /// When `true` (the default), the runner enables provider-level caching:
    /// - Anthropic: sets `prompt_caching = true` on the config
    /// - Bedrock: sets `prompt_caching = Some(BedrockCacheConfig::default())`
    /// - OpenAI / DeepSeek: no action needed (caching is automatic)
    /// - Gemini: handled separately via `ContextCacheConfig`
    pub auto_cache: bool,
    /// Maximum number of recent persisted events to load at the start of a run.
    ///
    /// `None` preserves the previous behavior and loads the full session
    /// history. Set this for chat surfaces that already summarize older turns
    /// and need predictable startup latency.
    pub history_max_events: Option<usize>,
    /// Tool concurrency configuration controlling parallel tool dispatch limits,
    /// per-tool overrides, and backpressure behavior.
    ///
    /// The default (`ToolConcurrencyConfig::default()`) imposes no limits,
    /// preserving backward compatibility with the previous `max_tool_concurrency: None`.
    pub tool_concurrency: ToolConcurrencyConfig,
    /// Whether tracing spans may include full request, response, and tool
    /// payloads when the `record-payloads` crate feature is enabled.
    pub record_payloads: bool,
    /// Maximum serialized bytes recorded for tracing payload fields when full
    /// payload recording is disabled.
    pub trace_payload_max_bytes: usize,
    /// Maximum number of agent-to-agent transfers allowed in a single run.
    ///
    /// Prevents infinite transfer loops when agents transfer back and forth.
    /// Defaults to 10 when `None`.
    pub max_transfer_depth: Option<u32>,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            streaming_mode: StreamingMode::SSE,
            tool_confirmation_decisions: HashMap::new(),
            tool_confirmation_fingerprints: HashMap::new(),
            tool_confirmation_handler: None,
            runtime_toolsets: Vec::new(),
            cached_content: None,
            transfer_targets: Vec::new(),
            parent_agent: None,
            auto_cache: true,
            history_max_events: None,
            tool_concurrency: ToolConcurrencyConfig::default(),
            record_payloads: false,
            trace_payload_max_bytes: 2048,
            max_transfer_depth: None,
        }
    }
}

impl RunConfig {
    /// Creates a new [`RunConfigBuilder`] initialized with default values.
    ///
    /// Use the builder to construct a `RunConfig` when struct literal syntax
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{RunConfig, StreamingMode};
    ///
    /// let config = RunConfig::builder()
    ///     .streaming_mode(StreamingMode::None)
    ///     .auto_cache(false)
    ///     .build();
    ///
    /// assert_eq!(config.streaming_mode, StreamingMode::None);
    /// assert!(!config.auto_cache);
    /// ```
    pub fn builder() -> RunConfigBuilder {
        RunConfigBuilder::default()
    }
}

/// Builder for [`RunConfig`].
///
/// Provides a fluent API for constructing `RunConfig` instances. All fields
/// start with their default values and can be overridden individually.
///
/// # Example
///
/// ```rust
/// use adk_core::{RunConfig, RunConfigBuilder, StreamingMode, ToolConcurrencyConfig};
///
/// let config = RunConfigBuilder::default()
///     .streaming_mode(StreamingMode::Bidi)
///     .history_max_events(Some(50))
///     .build();
/// ```
#[derive(Debug, Clone, Default)]
pub struct RunConfigBuilder {
    config: RunConfig,
}

impl RunConfigBuilder {
    /// Sets the streaming mode for the run.
    pub fn streaming_mode(mut self, mode: StreamingMode) -> Self {
        self.config.streaming_mode = mode;
        self
    }

    /// Sets static confirmation decisions for the current run, keyed by function
    /// call ID.
    ///
    /// The ID is the one carried on `ToolConfirmationRequest::function_call_id`.
    pub fn tool_confirmation_decisions(
        mut self,
        decisions: HashMap<String, ToolConfirmationDecision>,
    ) -> Self {
        self.config.tool_confirmation_decisions = decisions;
        self
    }

    /// Binds confirmation decisions to the arguments they were granted for.
    ///
    /// Keys are function call IDs and values are fingerprints from
    /// [`tool_call_fingerprint`]. A decision whose fingerprint does not match the
    /// actual call is ignored and the call is treated as unconfirmed.
    pub fn tool_confirmation_fingerprints(mut self, fingerprints: HashMap<String, String>) -> Self {
        self.config.tool_confirmation_fingerprints = fingerprints;
        self
    }

    /// Sets an asynchronous tool confirmation handler for the current run.
    pub fn tool_confirmation_handler(mut self, handler: Arc<dyn ToolConfirmationHandler>) -> Self {
        self.config.tool_confirmation_handler = Some(handler);
        self
    }

    /// Adds a toolset that is resolved only for this runner invocation.
    pub fn runtime_toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
        self.config.runtime_toolsets.push(RuntimeToolset::new(toolset));
        self
    }

    /// Adds several toolsets that are resolved only for this runner invocation.
    pub fn runtime_toolsets(
        mut self,
        toolsets: impl IntoIterator<Item = Arc<dyn Toolset>>,
    ) -> Self {
        self.config.runtime_toolsets.extend(toolsets.into_iter().map(RuntimeToolset::new));
        self
    }

    /// Sets the cached content name for automatic prompt caching.
    pub fn cached_content(mut self, name: impl Into<String>) -> Self {
        self.config.cached_content = Some(name.into());
        self
    }

    /// Sets the valid agent names this agent can transfer to.
    pub fn transfer_targets(mut self, targets: Vec<String>) -> Self {
        self.config.transfer_targets = targets;
        self
    }

    /// Sets the parent agent name.
    pub fn parent_agent(mut self, name: impl Into<String>) -> Self {
        self.config.parent_agent = Some(name.into());
        self
    }

    /// Enables or disables automatic prompt caching for supported providers.
    pub fn auto_cache(mut self, enabled: bool) -> Self {
        self.config.auto_cache = enabled;
        self
    }

    /// Sets the maximum number of recent persisted events to load at run start.
    pub fn history_max_events(mut self, max: Option<usize>) -> Self {
        self.config.history_max_events = max;
        self
    }

    /// Sets the tool concurrency configuration.
    pub fn tool_concurrency(mut self, config: ToolConcurrencyConfig) -> Self {
        self.config.tool_concurrency = config;
        self
    }

    /// Enables or disables full payload recording in tracing spans.
    pub fn record_payloads(mut self, enabled: bool) -> Self {
        self.config.record_payloads = enabled;
        self
    }

    /// Sets the maximum serialized bytes for tracing payload fields.
    pub fn trace_payload_max_bytes(mut self, max: usize) -> Self {
        self.config.trace_payload_max_bytes = max;
        self
    }

    /// Sets the maximum number of agent-to-agent transfers allowed in a single run.
    ///
    /// Prevents infinite transfer loops. Defaults to 10 when `None`.
    pub fn max_transfer_depth(mut self, depth: u32) -> Self {
        self.config.max_transfer_depth = Some(depth);
        self
    }

    /// Consumes the builder and returns the configured [`RunConfig`].
    pub fn build(self) -> RunConfig {
        self.config
    }
}

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

    #[test]
    fn test_run_config_default() {
        let config = RunConfig::default();
        assert_eq!(config.streaming_mode, StreamingMode::SSE);
        assert_eq!(config.history_max_events, None);
        assert_eq!(config.tool_concurrency.max_concurrency, None);
        assert!(config.tool_concurrency.per_tool.is_empty());
        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Queue);
        assert!(!config.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, 2048);
        assert!(config.tool_confirmation_decisions.is_empty());
        assert_eq!(config.max_transfer_depth, None);
    }

    #[test]
    fn test_streaming_mode() {
        assert_eq!(StreamingMode::SSE, StreamingMode::SSE);
        assert_ne!(StreamingMode::SSE, StreamingMode::None);
        assert_ne!(StreamingMode::None, StreamingMode::Bidi);
    }

    #[test]
    fn test_tool_confirmation_policy() {
        let policy = ToolConfirmationPolicy::default();
        assert!(!policy.requires_confirmation("search"));

        let policy = policy.with_tool("search");
        assert!(policy.requires_confirmation("search"));
        assert!(!policy.requires_confirmation("write_file"));

        assert!(ToolConfirmationPolicy::Always.requires_confirmation("any_tool"));
    }

    #[test]
    fn test_validate_state_key_valid() {
        assert!(validate_state_key("user_name").is_ok());
        assert!(validate_state_key("app:config").is_ok());
        assert!(validate_state_key("temp:data").is_ok());
        assert!(validate_state_key("a").is_ok());
    }

    #[test]
    fn test_validate_state_key_empty() {
        assert_eq!(validate_state_key(""), Err("state key must not be empty"));
    }

    #[test]
    fn test_validate_state_key_too_long() {
        let long_key = "a".repeat(MAX_STATE_KEY_LEN + 1);
        assert!(validate_state_key(&long_key).is_err());
    }

    #[test]
    fn test_validate_state_key_path_traversal() {
        assert!(validate_state_key("../etc/passwd").is_err());
        assert!(validate_state_key("foo/bar").is_err());
        assert!(validate_state_key("foo\\bar").is_err());
        assert!(validate_state_key("..").is_err());
    }

    #[test]
    fn test_validate_state_key_null_byte() {
        assert!(validate_state_key("foo\0bar").is_err());
    }

    #[test]
    fn test_run_config_builder_defaults() {
        let config = RunConfig::builder().build();
        let default = RunConfig::default();
        assert_eq!(config.streaming_mode, default.streaming_mode);
        assert_eq!(config.auto_cache, default.auto_cache);
        assert_eq!(config.history_max_events, default.history_max_events);
        assert_eq!(config.record_payloads, default.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, default.trace_payload_max_bytes);
        assert!(config.tool_confirmation_decisions.is_empty());
        assert!(config.transfer_targets.is_empty());
        assert!(config.cached_content.is_none());
        assert!(config.parent_agent.is_none());
    }

    #[test]
    fn test_run_config_builder_all_fields() {
        let mut decisions = HashMap::new();
        decisions.insert("delete".to_string(), ToolConfirmationDecision::Approve);

        let config = RunConfig::builder()
            .streaming_mode(StreamingMode::None)
            .tool_confirmation_decisions(decisions.clone())
            .cached_content("my-cache")
            .transfer_targets(vec!["agent_a".to_string(), "agent_b".to_string()])
            .parent_agent("parent")
            .auto_cache(false)
            .history_max_events(Some(50))
            .tool_concurrency(ToolConcurrencyConfig {
                max_concurrency: Some(4),
                per_tool: HashMap::new(),
                backpressure: BackpressurePolicy::Fail,
            })
            .record_payloads(true)
            .trace_payload_max_bytes(4096)
            .build();

        assert_eq!(config.streaming_mode, StreamingMode::None);
        assert_eq!(config.tool_confirmation_decisions, decisions);
        assert_eq!(config.cached_content.as_deref(), Some("my-cache"));
        assert_eq!(config.transfer_targets, vec!["agent_a", "agent_b"]);
        assert_eq!(config.parent_agent.as_deref(), Some("parent"));
        assert!(!config.auto_cache);
        assert_eq!(config.history_max_events, Some(50));
        assert_eq!(config.tool_concurrency.max_concurrency, Some(4));
        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Fail);
        assert!(config.record_payloads);
        assert_eq!(config.trace_payload_max_bytes, 4096);
    }
}