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
use crate::{
    CallbackContext, Event, EventActions, LlmRequest, Memory, MemoryEntry, ReadonlyContext, Result,
    RunConfig, Session,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;

/// The core trait for all tools that agents can invoke.
///
/// Tools extend agent capabilities with custom functions. Each tool has a name,
/// description, optional parameter schema, and an async `execute` method.
#[async_trait]
pub trait Tool: Send + Sync {
    /// Returns the unique name of this tool.
    fn name(&self) -> &str;
    /// Returns a human-readable description of what this tool does.
    fn description(&self) -> &str;

    /// Returns the tool declaration that should be exposed to model providers.
    ///
    /// The default implementation produces the standard ADK function-tool
    /// declaration (`name`, `description`, optional `parameters`, optional
    /// `response`). Provider-specific built-in tools may override this to attach
    /// additional metadata that the provider adapters understand.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn declaration(&self) -> serde_json::Value {
    ///     serde_json::json!({
    ///         "name": self.name(),
    ///         "description": self.description(),
    ///         "x-adk-openai-tool": {
    ///             "type": "web_search"
    ///         }
    ///     })
    /// }
    /// ```
    fn declaration(&self) -> Value {
        let mut decl = serde_json::json!({
            "name": self.name(),
            "description": self.enhanced_description(),
        });

        if let Some(params) = self.parameters_schema() {
            decl["parameters"] = params;
        }

        if let Some(response) = self.response_schema() {
            decl["response"] = response;
        }

        decl
    }

    /// Returns an enhanced description that may include additional notes.
    /// For long-running tools, this includes a warning not to call the tool
    /// again if it has already returned a pending status.
    /// Default implementation returns the base description.
    fn enhanced_description(&self) -> String {
        self.description().to_string()
    }

    /// Indicates whether the tool is a long-running operation.
    /// Long-running tools typically return a task ID immediately and
    /// complete the operation asynchronously.
    fn is_long_running(&self) -> bool {
        false
    }

    /// Indicates whether this tool is a built-in server-side tool (e.g., `google_search`, `url_context`).
    ///
    /// Built-in tools are executed server-side by the model provider and should not be
    /// executed locally by the agent. The default implementation returns `false`.
    fn is_builtin(&self) -> bool {
        false
    }

    /// Returns the JSON Schema for this tool's parameters, if any.
    fn parameters_schema(&self) -> Option<Value> {
        None
    }
    /// Returns the JSON Schema for this tool's response, if any.
    fn response_schema(&self) -> Option<Value> {
        None
    }

    /// Returns the behaviour annotations the tool's publisher declared, if any.
    ///
    /// MCP tools return the server's `annotations` object unchanged, with its
    /// camelCase keys: `title`, `readOnlyHint`, `destructiveHint`,
    /// `idempotentHint`, and `openWorldHint`. The values are hints from the
    /// publisher, not guarantees, so trust them only as far as the publisher.
    /// The default returns `None`; tools that wrap another tool forward it.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Result, Tool, ToolContext};
    /// use serde_json::{Value, json};
    /// use std::sync::{Arc, LazyLock};
    ///
    /// static HINTS: LazyLock<Value> =
    ///     LazyLock::new(|| json!({ "destructiveHint": true, "openWorldHint": false }));
    ///
    /// struct DeleteLogs;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for DeleteLogs {
    ///     fn name(&self) -> &str {
    ///         "delete_logs"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Deletes the service logs"
    ///     }
    ///     fn annotations(&self) -> Option<&Value> {
    ///         Some(&HINTS)
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    ///         Ok(Value::Null)
    ///     }
    /// }
    ///
    /// let destructive = DeleteLogs
    ///     .annotations()
    ///     .and_then(|hints| hints["destructiveHint"].as_bool())
    ///     .unwrap_or(true);
    /// assert!(destructive);
    /// ```
    fn annotations(&self) -> Option<&Value> {
        None
    }

    /// Returns who publishes this tool: the toolset or server it comes from.
    ///
    /// A call held for approval records it in the call's [`ToolOrigin`](crate::ToolOrigin),
    /// with a digest of [`declaration`](Self::declaration) and
    /// [`annotations`](Self::annotations), and a decision applies only to calls to a tool
    /// with the same origin and declaration. A held call that resumes against a tool with
    /// another origin is answered as not run. MCP tools return `mcp:{toolset name}`; tools
    /// that wrap another tool forward it. The default,
    /// [`STATIC_TOOL_ORIGIN`](crate::STATIC_TOOL_ORIGIN), fits a tool compiled into the
    /// agent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Result, Tool, ToolContext};
    /// use serde_json::Value;
    /// use std::sync::Arc;
    ///
    /// /// A tool fetched from a plugin registry, identified by the registry entry.
    /// struct RegistryTool {
    ///     origin: String,
    /// }
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for RegistryTool {
    ///     fn name(&self) -> &str {
    ///         "lookup"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Looks up a customer"
    ///     }
    ///     fn origin(&self) -> &str {
    ///         &self.origin
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    ///         Ok(Value::Null)
    ///     }
    /// }
    ///
    /// let tool = RegistryTool { origin: "registry:crm@4".into() };
    /// assert_eq!(tool.origin(), "registry:crm@4");
    /// ```
    fn origin(&self) -> &str {
        crate::STATIC_TOOL_ORIGIN
    }

    /// Returns the scopes required to execute this tool.
    ///
    /// When non-empty, the framework can enforce that the calling user
    /// possesses **all** listed scopes before dispatching `execute()`.
    /// The default implementation returns an empty slice (no scopes required).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn required_scopes(&self) -> &[&str] {
    ///     &["finance:write", "verified"]
    /// }
    /// ```
    fn required_scopes(&self) -> &[&str] {
        &[]
    }

    /// Indicates whether this tool performs no side effects.
    ///
    /// [`ToolExecutionStrategy::Auto`] overlaps a call with its adjacent
    /// neighbours only when the selected tool is both read-only and
    /// concurrency-safe.
    fn is_read_only(&self) -> bool {
        false
    }

    /// Returns the side-effect class of this tool.
    ///
    /// The runtime retries a failed call only when the effect is
    /// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] and the error is
    /// retryable, and records [`ToolEffect::NonIdempotent`] calls in the
    /// [`ActionLedger`](crate::ActionLedger) when one is configured. The default
    /// derives the effect from [`Tool::is_read_only`], so a tool that declares
    /// nothing is treated as non-idempotent and never retried.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Result, Tool, ToolContext, ToolEffect};
    /// use serde_json::{Value, json};
    /// use std::sync::Arc;
    ///
    /// struct SetThermostat;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for SetThermostat {
    ///     fn name(&self) -> &str {
    ///         "set_thermostat"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Sets the target temperature"
    ///     }
    ///     // Setting the same target twice leaves the same state as setting it once.
    ///     fn effect(&self) -> ToolEffect {
    ///         ToolEffect::Idempotent
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
    ///         Ok(json!({ "target": args["celsius"] }))
    ///     }
    /// }
    ///
    /// assert_eq!(SetThermostat.effect(), ToolEffect::Idempotent);
    /// ```
    fn effect(&self) -> ToolEffect {
        if self.is_read_only() { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent }
    }

    /// Overrides the per-call timeout the agent applies to this tool.
    ///
    /// | Value | Timeout applied to each call |
    /// |-------|------------------------------|
    /// | `None` (default) | The agent's own tool timeout |
    /// | `Some(None)` | None; the call runs until it finishes or the run is cancelled |
    /// | `Some(Some(duration))` | `duration` instead of the agent's tool timeout |
    ///
    /// Agent-as-tool delegations use this so a long sub-agent run is bounded by
    /// its own configuration rather than by a timeout sized for ordinary calls.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Result, Tool, ToolContext};
    /// use serde_json::Value;
    /// use std::{sync::Arc, time::Duration};
    ///
    /// struct BuildReport;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for BuildReport {
    ///     fn name(&self) -> &str {
    ///         "build_report"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Builds the quarterly report"
    ///     }
    ///     fn timeout_override(&self) -> Option<Option<Duration>> {
    ///         Some(Some(Duration::from_secs(30 * 60)))
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    ///         Ok(Value::Null)
    ///     }
    /// }
    ///
    /// assert_eq!(BuildReport.timeout_override(), Some(Some(Duration::from_secs(1800))));
    /// ```
    fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
        None
    }

    /// Indicates whether this tool is safe for concurrent execution.
    ///
    /// [`ToolExecutionStrategy::Auto`] requires this signal in addition to
    /// [`Tool::is_read_only`]. [`ToolExecutionStrategy::Parallel`] is an
    /// explicit caller override and does not inspect either signal.
    fn is_concurrency_safe(&self) -> bool {
        false
    }

    /// The ordered batch this tool's calls belong to, if any.
    ///
    /// Calls to tools that name the same group run in the order the model listed them, one
    /// at a time. The first call in the group that does not succeed — it fails, is refused,
    /// does not run, or is held for approval — stops the group for the rest of the model's
    /// turn: every later call in the group is answered with the group's
    /// [`halt_text`](BatchGroup::halt_text) instead of running, because the model planned it
    /// assuming the earlier calls succeeded. Computer use and browser use actions need this.
    /// `None` by default.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{BatchGroup, Result, Tool, ToolContext};
    /// use async_trait::async_trait;
    /// use serde_json::Value;
    /// use std::sync::Arc;
    ///
    /// struct Click;
    ///
    /// #[async_trait]
    /// impl Tool for Click {
    ///     fn name(&self) -> &str {
    ///         "click"
    ///     }
    ///
    ///     fn description(&self) -> &str {
    ///         "Clicks at a position"
    ///     }
    ///
    ///     fn batch_group(&self) -> Option<BatchGroup> {
    ///         Some(BatchGroup::new("desktop", "Not executed: an earlier action failed."))
    ///     }
    ///
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    ///         Ok(Value::Null)
    ///     }
    /// }
    ///
    /// assert_eq!(Click.batch_group().unwrap().name, "desktop");
    /// ```
    fn batch_group(&self) -> Option<BatchGroup> {
        None
    }

    /// Indicates whether this tool delegates work to another agent.
    ///
    /// Agent implementations can use this marker to overlap consecutive
    /// delegation calls while preserving sequential execution for ordinary
    /// tools.
    fn is_agent_delegation(&self) -> bool {
        false
    }

    /// The network destinations a call with `args` reaches.
    ///
    /// Under a run egress policy ([`RunConfig::egress_policy`]),
    /// [`authorize_tool_call`](crate::authorize_tool_call) refuses the call before it runs
    /// unless the policy admits the declaration; the default,
    /// [`ToolEgress::Undeclared`](crate::egress::ToolEgress::Undeclared), is refused. A wrapper
    /// forwards its inner tool's declaration. See [`ToolEgress`](crate::egress::ToolEgress).
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use adk_core::egress::ToolEgress;
    /// use adk_core::{Result, Tool, ToolContext};
    /// use serde_json::{Value, json};
    ///
    /// struct FetchIssue;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for FetchIssue {
    ///     fn name(&self) -> &str {
    ///         "fetch_issue"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Reads one GitHub issue"
    ///     }
    ///     fn egress(&self, _args: &Value) -> ToolEgress {
    ///         ToolEgress::for_urls(["https://api.github.com/"])
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
    ///         Ok(json!({ "issue": args["number"] }))
    ///     }
    /// }
    ///
    /// let declared = FetchIssue.egress(&json!({ "number": 7 }));
    /// assert_eq!(declared, ToolEgress::for_urls(["https://api.github.com/"]));
    /// ```
    fn egress(&self, _args: &Value) -> crate::egress::ToolEgress {
        crate::egress::ToolEgress::Undeclared
    }

    /// What an approver sees with a call with `args` when it is held, such as the exact image
    /// it would send ([`Evidence`](crate::Evidence)).
    ///
    /// [`GovernedCall::for_tool`](crate::GovernedCall::for_tool) records it on the call, the
    /// held request carries it, and its digests are part of the call's
    /// [fingerprint](crate::ToolConfirmationRequest::fingerprint): a decision applies only to
    /// a call with the same evidence, so an image that changes before the call runs holds it
    /// again. The default is no evidence. A wrapper forwards its inner tool's evidence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use adk_core::{ArtifactLocator, Evidence, ImageEvidence, Result, Tool, ToolContext};
    /// use serde_json::{Value, json};
    ///
    /// struct SendCrop;
    ///
    /// #[async_trait::async_trait]
    /// impl Tool for SendCrop {
    ///     fn name(&self) -> &str {
    ///         "send_crop"
    ///     }
    ///     fn description(&self) -> &str {
    ///         "Sends a redacted crop to a cloud model"
    ///     }
    ///     fn approval_evidence(&self, args: &Value) -> Vec<Evidence> {
    ///         let digest = args["digest"].as_str().unwrap_or_default();
    ///         let file = args["file"].as_str().unwrap_or_default();
    ///         let locator = ArtifactLocator::new("desk", "ana", "s1", file, 1);
    ///         vec![ImageEvidence::new(digest, locator, "image/png", 640, 180).into()]
    ///     }
    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
    ///         Ok(json!({ "sent": args["digest"] }))
    ///     }
    /// }
    ///
    /// let evidence = SendCrop.approval_evidence(&json!({ "digest": "sha256:aa", "file": "crop.png" }));
    /// assert_eq!(evidence[0].digest(), "sha256:aa");
    /// ```
    fn approval_evidence(&self, _args: &Value) -> Vec<crate::Evidence> {
        Vec::new()
    }

    /// Executes the tool with the given context and arguments.
    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
}

/// An ordered batch of tool calls that stops at its first failure; see
/// [`Tool::batch_group`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BatchGroup {
    /// The group's name; tools that return the same name share one batch.
    pub name: std::borrow::Cow<'static, str>,
    /// The exact result text for each call skipped after a failure.
    pub halt_text: std::borrow::Cow<'static, str>,
}

impl BatchGroup {
    /// A group called `name` that answers skipped calls with `halt_text`.
    pub fn new(
        name: impl Into<std::borrow::Cow<'static, str>>,
        halt_text: impl Into<std::borrow::Cow<'static, str>>,
    ) -> Self {
        Self { name: name.into(), halt_text: halt_text.into() }
    }
}

/// Context available to tools during execution.
///
/// Extends [`CallbackContext`] with tool-specific operations like accessing
/// the function call ID, managing event actions, and searching memory.
#[async_trait]
pub trait ToolContext: CallbackContext {
    /// Returns the function call ID for this tool invocation.
    fn function_call_id(&self) -> &str;
    /// Returns the key that identifies this tool call across retries and replays.
    ///
    /// The default is `"{app}/{user}/{session}/{invocation}/{function_call_id}"`.
    /// Every attempt of one call shares the key and no other call has it, so a
    /// tool can pass it to a downstream API that accepts an idempotency key, and
    /// the [`ActionLedger`](crate::ActionLedger) records non-idempotent calls
    /// under it.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
    ///     let key = ctx.idempotency_key();
    ///     self.payments.charge(&args, &key).await
    /// }
    /// ```
    fn idempotency_key(&self) -> String {
        format!(
            "{}/{}/{}/{}/{}",
            self.app_name(),
            self.user_id(),
            self.session_id(),
            self.invocation_id(),
            self.function_call_id()
        )
    }
    /// Get the current event actions. Returns an owned copy for thread safety.
    fn actions(&self) -> EventActions;
    /// Set the event actions (e.g., to trigger escalation or skip summarization).
    fn set_actions(&self, actions: EventActions);
    /// Searches memory for entries matching the query.
    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>>;

    /// Returns the memory service backing the parent invocation, when exposed.
    ///
    /// The default keeps contexts written before this capability backward
    /// compatible. Agent-as-tool adapters use it only when memory forwarding is
    /// explicitly enabled.
    fn memory(&self) -> Option<Arc<dyn Memory>> {
        None
    }

    /// Returns the parent session, when exposed by the runtime tool context.
    ///
    /// Agent-as-tool adapters can snapshot its history and state for a child
    /// invocation without sharing mutable session ownership.
    fn session(&self) -> Option<&dyn Session> {
        None
    }

    /// Returns the parent run configuration, when exposed by the runtime.
    fn run_config(&self) -> Option<&RunConfig> {
        None
    }

    /// The run's egress policy ([`RunConfig::egress_policy`]), which a tool that opens its own
    /// connections enforces, for example by building a
    /// [`GuardedClient`](crate::egress::GuardedClient) from it. `None` when the run has none or
    /// the runtime does not expose its configuration.
    fn egress_policy(&self) -> Option<&crate::egress::EgressPolicy> {
        self.run_config().and_then(|config| config.egress_policy.as_ref())
    }

    /// The names of the tools the agent making this call has, when its runtime says: a tool
    /// that names another tool for a person to ask for, such as a drawn form's action, checks
    /// the name against them (spec 3.3 §7.4 rule 5). `None`, the default, when it does not.
    fn agent_tool_names(&self) -> Option<Vec<String>> {
        None
    }

    /// Returns whether the parent invocation has been cancelled.
    fn is_cancelled(&self) -> bool {
        false
    }

    /// Returns the request metadata inherited from the parent run
    /// ([`InvocationContext::request_metadata`](crate::InvocationContext::request_metadata)):
    /// authenticated only when [`is_authenticated`](crate::ReadonlyContext::is_authenticated)
    /// says so.
    fn request_metadata(&self) -> std::collections::HashMap<String, Value> {
        std::collections::HashMap::new()
    }

    /// Returns the current nested agent-as-tool delegation depth.
    fn delegation_depth(&self) -> u32 {
        0
    }

    /// Returns the maximum nested agent-as-tool delegation depth.
    fn max_delegation_depth(&self) -> Option<u32> {
        None
    }

    /// Returns the root invocation that owns this orchestration tree.
    fn orchestration_root_invocation_id(&self) -> &str {
        self.invocation_id()
    }

    /// Returns the causal relationship execution containing this tool call.
    fn orchestration_edge_id(&self) -> Option<&str> {
        None
    }

    /// Emits a nested agent event through the parent agent's event stream.
    ///
    /// The default is a no-op. AgentTool uses this only when event forwarding is
    /// explicitly enabled, preserving existing callers' output behavior.
    async fn emit_event(&self, _event: Event) {}

    /// Emit streaming progress output during long-running tool execution.
    ///
    /// Tools call this to push intermediate stdout/stderr to the UI layer
    /// as it arrives, rather than waiting for the tool to finish. This enables
    /// streaming terminal output for shell commands, build logs, etc.
    ///
    /// # Arguments
    ///
    /// * `stream` - The output stream: `"stdout"`, `"stderr"`, or a custom label
    /// * `chunk` - The text chunk to emit
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Inside a tool's execute() method:
    /// ctx.emit_progress("stdout", "Compiling project...\n").await;
    /// ctx.emit_progress("stdout", "Build successful!\n").await;
    /// ctx.emit_progress("stderr", "warning: unused variable\n").await;
    /// ```
    ///
    /// The default implementation is a no-op. Runners and UI layers that support
    /// streaming output override this to forward chunks to the client.
    async fn emit_progress(&self, _stream: &str, _chunk: &str) {
        // Default: discard. Override in runners that support streaming tool output.
    }

    /// Returns the scopes granted to the current user for this invocation.
    ///
    /// Implementations may resolve scopes from session state, JWT claims,
    /// or an external identity provider. The default returns an empty set
    /// (no scopes granted), which means scope-protected tools will be denied
    /// unless the implementation is overridden.
    fn user_scopes(&self) -> Vec<String> {
        vec![]
    }

    /// Retrieve a secret by name from the configured secret provider.
    ///
    /// Returns `Ok(Some(value))` if a secret provider is configured and the
    /// secret exists, `Ok(None)` if no secret provider is configured, or an
    /// error if the provider fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn use_secret(ctx: &dyn ToolContext) -> adk_core::Result<()> {
    ///     if let Some(api_key) = ctx.get_secret("slack-bot-token").await? {
    ///         // use the secret
    ///     }
    ///     Ok(())
    /// }
    /// ```
    async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
        Ok(None)
    }

    /// Resolves a secret, stating why it is needed.
    ///
    /// The tool identity is added by the framework, not taken from the tool, so a
    /// purpose is the only part a tool contributes. An authorizing
    /// [`SecretService`](crate::SecretService) sees both.
    async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
        let _ = purpose;
        self.get_secret(name).await
    }
}

/// The side-effect class of a tool, reported by [`Tool::effect`].
///
/// | Effect | Retried after a retryable error | Recorded in the action ledger |
/// |--------|---------------------------------|-------------------------------|
/// | `ReadOnly` | Yes | No |
/// | `Idempotent` | Yes | No |
/// | `NonIdempotent` | No | Yes, when a ledger is configured |
///
/// # Example
///
/// ```rust
/// use adk_core::ToolEffect;
///
/// assert!(ToolEffect::Idempotent.is_retry_safe());
/// assert!(!ToolEffect::NonIdempotent.is_retry_safe());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ToolEffect {
    /// Reads without changing anything.
    ReadOnly,
    /// Changes state, but repeating a call with the same arguments leaves the
    /// same state as making it once.
    Idempotent,
    /// Changes state, and repeating a call repeats the change — a payment, an
    /// email, an order.
    NonIdempotent,
}

impl ToolEffect {
    /// Returns `true` when repeating a call cannot repeat a side effect.
    pub fn is_retry_safe(self) -> bool {
        match self {
            Self::ReadOnly | Self::Idempotent => true,
            Self::NonIdempotent => false,
        }
    }
}

/// Configuration for automatic tool retry on failure.
///
/// A failed call is retried only when its tool's [`Tool::effect`] is
/// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] and the error is
/// [retryable](crate::AdkError::is_retryable) — a rate limit, an unavailable
/// dependency, or a timeout. The delay before retry `n` is
/// `delay * 2^(n - 1)`, capped at `max_delay`, with jitter; see
/// [`RetryBudget::backoff_delay`].
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// use adk_core::RetryBudget;
///
/// // Retry up to 2 times, starting at 500ms (3 total attempts)
/// let budget = RetryBudget::new(2, Duration::from_millis(500))
///     .with_max_delay(Duration::from_secs(5));
/// assert_eq!(budget.max_retries, 2);
/// assert!(budget.backoff_delay(1) <= Duration::from_millis(500));
/// ```
#[derive(Debug, Clone)]
pub struct RetryBudget {
    /// Maximum number of retry attempts (not counting the initial attempt).
    /// E.g., `max_retries: 2` means up to 3 total attempts.
    pub max_retries: u32,
    /// Base delay before the first retry. Each later retry doubles it.
    pub delay: std::time::Duration,
    /// Upper bound on the delay before any one retry.
    pub max_delay: std::time::Duration,
}

impl RetryBudget {
    /// The `max_delay` that [`RetryBudget::new`] applies.
    pub const DEFAULT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);

    /// Create a new retry budget.
    ///
    /// `max_delay` is [`RetryBudget::DEFAULT_MAX_DELAY`], or `delay` when that is
    /// larger.
    ///
    /// # Arguments
    ///
    /// * `max_retries` - Maximum retry attempts (not counting the initial attempt)
    /// * `delay` - Base delay before the first retry
    pub fn new(max_retries: u32, delay: std::time::Duration) -> Self {
        Self { max_retries, delay, max_delay: delay.max(Self::DEFAULT_MAX_DELAY) }
    }

    /// Sets the upper bound on the delay before any one retry.
    pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self {
        self.max_delay = max_delay;
        self
    }

    /// Returns the delay before retry number `retry`, where `1` is the first retry.
    ///
    /// The ceiling is `delay * 2^(retry - 1)`, capped at `max_delay`. The
    /// returned delay is drawn uniformly from the upper half of that ceiling, so
    /// callers that failed together do not retry in lockstep.
    pub fn backoff_delay(&self, retry: u32) -> std::time::Duration {
        let exponent = retry.saturating_sub(1).min(31);
        let ceiling = self.delay.saturating_mul(1u32 << exponent).min(self.max_delay);
        let ceiling_nanos = ceiling.as_nanos();
        if ceiling_nanos == 0 {
            return std::time::Duration::ZERO;
        }
        let half = ceiling_nanos / 2;
        let jitter = uuid::Uuid::new_v4().as_u128() % (ceiling_nanos - half + 1);
        let nanos = u64::try_from(half + jitter).unwrap_or(u64::MAX);
        std::time::Duration::from_nanos(nanos)
    }
}

/// A collection of tools that can be resolved dynamically from context.
#[async_trait]
pub trait Toolset: Send + Sync {
    /// Returns the name of this toolset.
    fn name(&self) -> &str;
    /// Returns the tools available in this toolset for the given context.
    async fn tools(&self, ctx: Arc<dyn crate::ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>>;

    /// Applies toolset-specific context to an LLM request before each model call.
    ///
    /// Toolsets can use this hook to describe a dynamic tool protocol without
    /// requiring every agent that installs the toolset to repeat that guidance
    /// in its instruction. The default implementation leaves the request
    /// unchanged.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn process_llm_request(
    ///     &self,
    ///     _ctx: std::sync::Arc<dyn adk_core::ReadonlyContext>,
    ///     request: &mut adk_core::LlmRequest,
    /// ) -> adk_core::Result<()> {
    ///     request.contents.insert(0, adk_core::Content::new("user").with_text("Tool guidance"));
    ///     Ok(())
    /// }
    /// ```
    async fn process_llm_request(
        &self,
        _ctx: Arc<dyn ReadonlyContext>,
        _request: &mut LlmRequest,
    ) -> Result<()> {
        Ok(())
    }

    /// Releases what the toolset holds open, such as a server connection or a subprocess.
    ///
    /// The agent that owns the toolset calls this from [`Agent::close`](crate::Agent::close),
    /// which `adk_runner::Runner::close` reaches for every agent in its tree. Closing twice
    /// must be harmless. The default does nothing.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn close(&self) {
    ///     self.connection.lock().await.take();
    /// }
    /// ```
    async fn close(&self) {}
}

/// Controls how multiple tool calls from a single LLM response are dispatched.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ToolExecutionStrategy {
    /// Execute tools one at a time in LLM-returned order. Default.
    #[default]
    Sequential,
    /// Execute all tools concurrently without inspecting tool metadata.
    ///
    /// This is an explicit caller override. The caller is responsible for
    /// ensuring every selected tool is safe to execute concurrently.
    Parallel,
    /// Execute calls in LLM-returned order, overlapping only a run of adjacent
    /// calls whose tools report both read-only and concurrency-safe. Any other
    /// call runs alone, in its place: it starts after the calls listed before it
    /// finish, and the calls listed after it wait for it.
    Auto,
}

/// Controls how the framework handles skills/agents that request unavailable tools.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValidationMode {
    /// Reject the operation entirely if any requested tool is missing from the registry.
    #[default]
    Strict,
    /// Bind available tools, omit missing ones, and log a warning.
    Permissive,
}

/// A registry that maps tool names to concrete tool instances.
///
/// Implementations resolve string identifiers (e.g. from a skill or config)
/// into executable `Arc<dyn Tool>` instances.
pub trait ToolRegistry: Send + Sync {
    /// Resolve a tool name to a concrete tool instance.
    /// Returns `None` if the tool is not available in this registry.
    fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>>;

    /// Returns a list of all tool names available in this registry.
    fn available_tools(&self) -> Vec<String> {
        vec![]
    }
}

/// A predicate function for filtering tools.
pub type ToolPredicate = Box<dyn Fn(&dyn Tool) -> bool + Send + Sync>;

/// The error code for an agent built with two static tools of one name.
pub const DUPLICATE_TOOL_NAME_CODE: &str = "agent.duplicate_tool_name";

/// Checks that no two of `tools` share a name.
///
/// A model calls a tool by name, so with two tools of one name only one can
/// ever be called. Agent builders call this on their static tool list, naming
/// the agent being built as `agent_name`.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use adk_core::{DUPLICATE_TOOL_NAME_CODE, Result, Tool, ToolContext, ensure_unique_tool_names};
/// use async_trait::async_trait;
/// use serde_json::Value;
///
/// struct Lookup;
///
/// #[async_trait]
/// impl Tool for Lookup {
///     fn name(&self) -> &str {
///         "lookup"
///     }
///     fn description(&self) -> &str {
///         "Looks things up"
///     }
///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
///         Ok(args)
///     }
/// }
///
/// let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(Lookup), Arc::new(Lookup)];
/// let err = ensure_unique_tool_names("support", &tools).unwrap_err();
/// assert_eq!(err.code, DUPLICATE_TOOL_NAME_CODE);
/// assert!(ensure_unique_tool_names("support", &tools[..1]).is_ok());
/// ```
///
/// # Errors
///
/// Returns an [`ErrorCategory::InvalidInput`](crate::ErrorCategory::InvalidInput)
/// error with code [`DUPLICATE_TOOL_NAME_CODE`] naming the first repeated name.
pub fn ensure_unique_tool_names(agent_name: &str, tools: &[Arc<dyn Tool>]) -> Result<()> {
    let mut seen = std::collections::HashSet::new();
    match tools.iter().map(|tool| tool.name()).find(|name| !seen.insert(*name)) {
        Some(name) => Err(crate::AdkError::new(
            crate::ErrorComponent::Agent,
            crate::ErrorCategory::InvalidInput,
            DUPLICATE_TOOL_NAME_CODE,
            format!(
                "agent '{agent_name}' has two tools named '{name}'; the model calls tools by \
                 name, so only one could ever run. Rename one of them or register it once."
            ),
        )),
        None => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Content, EventActions, ReadonlyContext, RunConfig};
    use std::sync::Mutex;

    struct TestTool {
        name: String,
    }

    #[allow(dead_code)]
    struct TestContext {
        content: Content,
        config: RunConfig,
        actions: Mutex<EventActions>,
    }

    impl TestContext {
        fn new() -> Self {
            Self {
                content: Content::new("user"),
                config: RunConfig::default(),
                actions: Mutex::new(EventActions::default()),
            }
        }
    }

    #[async_trait]
    impl ReadonlyContext for TestContext {
        fn invocation_id(&self) -> &str {
            "test"
        }
        fn agent_name(&self) -> &str {
            "test"
        }
        fn user_id(&self) -> &str {
            "user"
        }
        fn app_name(&self) -> &str {
            "app"
        }
        fn session_id(&self) -> &str {
            "session"
        }
        fn branch(&self) -> &str {
            ""
        }
        fn user_content(&self) -> &Content {
            &self.content
        }
    }

    #[async_trait]
    impl CallbackContext for TestContext {
        fn artifacts(&self) -> Option<Arc<dyn crate::Artifacts>> {
            None
        }
    }

    #[async_trait]
    impl ToolContext for TestContext {
        fn function_call_id(&self) -> &str {
            "call-123"
        }
        fn actions(&self) -> EventActions {
            self.actions.lock().unwrap().clone()
        }
        fn set_actions(&self, actions: EventActions) {
            *self.actions.lock().unwrap() = actions;
        }
        async fn search_memory(&self, _query: &str) -> Result<Vec<crate::MemoryEntry>> {
            Ok(vec![])
        }
    }

    #[async_trait]
    impl Tool for TestTool {
        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            "test tool"
        }

        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
            Ok(Value::String("result".to_string()))
        }
    }

    #[test]
    fn test_tool_trait() {
        let tool = TestTool { name: "test".to_string() };
        assert_eq!(tool.name(), "test");
        assert_eq!(tool.description(), "test tool");
        assert!(!tool.is_long_running());
    }

    struct ReadOnlyTool;

    #[async_trait]
    impl Tool for ReadOnlyTool {
        fn name(&self) -> &str {
            "lookup"
        }
        fn description(&self) -> &str {
            "reads"
        }
        fn is_read_only(&self) -> bool {
            true
        }
        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
            Ok(Value::Null)
        }
    }

    #[test]
    fn effect_defaults_follow_is_read_only() {
        let tool = TestTool { name: "test".to_string() };
        assert_eq!(tool.effect(), ToolEffect::NonIdempotent);
        assert_eq!(ReadOnlyTool.effect(), ToolEffect::ReadOnly);
        assert_eq!(tool.timeout_override(), None);
    }

    #[test]
    fn idempotency_key_joins_identity_and_call_id() {
        let ctx = TestContext::new();
        assert_eq!(ctx.idempotency_key(), "app/user/session/test/call-123");
    }

    #[test]
    fn backoff_grows_exponentially_with_jitter_and_respects_the_cap() {
        let budget = RetryBudget::new(5, std::time::Duration::from_millis(100))
            .with_max_delay(std::time::Duration::from_millis(350));
        for _ in 0..50 {
            let first = budget.backoff_delay(1);
            assert!(first >= std::time::Duration::from_millis(50));
            assert!(first <= std::time::Duration::from_millis(100));
            let second = budget.backoff_delay(2);
            assert!(second >= std::time::Duration::from_millis(100));
            assert!(second <= std::time::Duration::from_millis(200));
            let capped = budget.backoff_delay(10);
            assert!(capped >= std::time::Duration::from_millis(175));
            assert!(capped <= std::time::Duration::from_millis(350));
        }
        let zero = RetryBudget::new(1, std::time::Duration::ZERO);
        assert_eq!(zero.backoff_delay(1), std::time::Duration::ZERO);
        assert_eq!(zero.max_delay, RetryBudget::DEFAULT_MAX_DELAY);
    }

    #[tokio::test]
    async fn test_tool_execute() {
        let tool = TestTool { name: "test".to_string() };
        let ctx = Arc::new(TestContext::new()) as Arc<dyn ToolContext>;
        let result = tool.execute(ctx, Value::Null).await.unwrap();
        assert_eq!(result, Value::String("result".to_string()));
    }
}