Skip to main content

adk_tool/
agent_tool.rs

1//! AgentTool - Use agents as callable tools
2//!
3//! This module provides `AgentTool` which wraps an `Agent` instance to make it
4//! callable as a `Tool`. This enables powerful composition patterns where a
5//! coordinator agent can invoke specialized sub-agents.
6//!
7//! # Example
8//!
9//! ```rust
10//! use std::sync::Arc;
11//!
12//! use adk_agent::{LlmAgent, LlmAgentBuilder};
13//! use adk_core::Llm;
14//! use adk_tool::AgentTool;
15//!
16//! fn coordinator(model: Arc<dyn Llm>) -> adk_core::Result<LlmAgent> {
17//!     // Create a specialized agent
18//!     let math_agent = LlmAgentBuilder::new("math_expert")
19//!         .description("Solves mathematical problems")
20//!         .instruction("You are a math expert. Solve problems step by step.")
21//!         .model(model.clone())
22//!         .build()?;
23//!
24//!     // Wrap it as a tool and give it to a coordinator agent
25//!     let math_tool = AgentTool::new(Arc::new(math_agent));
26//!     LlmAgentBuilder::new("coordinator")
27//!         .instruction("Help users by delegating to specialists")
28//!         .model(model)
29//!         .tool(Arc::new(math_tool))
30//!         .build()
31//! }
32//! ```
33
34use adk_core::{
35    Agent, Artifacts, CallbackContext, Content, Event, InvocationContext, Memory, Part,
36    ReadonlyContext, Result, RunConfig, Session, State, Tool, ToolConfirmationRequest, ToolContext,
37};
38use async_trait::async_trait;
39use futures::StreamExt;
40use serde::{Deserialize, Serialize};
41use serde_json::{Value, json};
42use std::collections::{HashMap, HashSet};
43use std::sync::{Arc, atomic::AtomicBool};
44use std::time::Duration;
45
46/// Controls which parent session data is copied into an agent-tool invocation.
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
48pub enum AgentToolSessionSnapshot {
49    /// Start each delegated invocation with empty history and state.
50    #[default]
51    Isolated,
52    /// Copy the parent's current conversation history and state into the isolated child session.
53    Parent,
54}
55
56/// Controls how an [`AgentTool`] reports delegated execution failures.
57#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
58pub enum AgentToolFailureMode {
59    /// Return the legacy JSON error object as a successful tool result.
60    #[default]
61    ReturnErrorObject,
62    /// Propagate the failure through the tool's [`Result`].
63    Propagate,
64}
65
66/// Merge behavior for state produced by an agent-as-tool invocation.
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
68pub enum AgentToolStateMergePolicy {
69    /// Preserve legacy last-writer-wins behavior.
70    #[default]
71    Overwrite,
72    /// Reject a child write when the parent value changed after delegation began.
73    RejectConflicts,
74}
75
76#[derive(Clone)]
77struct AgentToolRuntimeConfig {
78    session_snapshot: AgentToolSessionSnapshot,
79    failure_mode: AgentToolFailureMode,
80    forward_memory: bool,
81    forward_shared_state: bool,
82    forward_events: bool,
83    max_delegation_depth: Option<u32>,
84    reject_child_handoffs: bool,
85    execute_child_handoffs: bool,
86    handoff_agents: Arc<HashMap<String, Arc<dyn Agent>>>,
87    history_max_events: Option<usize>,
88    state_keys: Option<Arc<HashSet<String>>>,
89    output_state_keys: Option<Arc<HashSet<String>>>,
90    state_merge_policy: AgentToolStateMergePolicy,
91    state_merge_exempt_keys: Arc<HashSet<String>>,
92    artifact_prefixes: Option<Arc<Vec<String>>>,
93    principal: Option<adk_core::AgentPrincipal>,
94    expose_error_messages: bool,
95}
96
97impl Default for AgentToolRuntimeConfig {
98    fn default() -> Self {
99        Self {
100            session_snapshot: AgentToolSessionSnapshot::Isolated,
101            failure_mode: AgentToolFailureMode::ReturnErrorObject,
102            forward_memory: false,
103            forward_shared_state: true,
104            forward_events: false,
105            max_delegation_depth: None,
106            reject_child_handoffs: false,
107            execute_child_handoffs: false,
108            handoff_agents: Arc::new(HashMap::new()),
109            history_max_events: None,
110            state_keys: None,
111            output_state_keys: None,
112            state_merge_policy: AgentToolStateMergePolicy::Overwrite,
113            state_merge_exempt_keys: Arc::new(HashSet::new()),
114            artifact_prefixes: None,
115            principal: None,
116            expose_error_messages: false,
117        }
118    }
119}
120
121struct AgentToolChildConfig {
122    forward_artifacts: bool,
123    artifact_prefixes: Option<Arc<Vec<String>>>,
124    forward_memory: bool,
125    forward_shared_state: bool,
126    session: Arc<AgentToolSession>,
127    run_config: RunConfig,
128    delegation_depth: u32,
129    max_delegation_depth: Option<u32>,
130    orchestration_root_invocation_id: String,
131    orchestration_edge_id: String,
132}
133
134/// How much later than its caller the agent tool enforces its own timeout.
135///
136/// Timers fire on whole milliseconds, so the margin puts the agent tool's deadline on a later
137/// tick than that of a caller enforcing the same limit.
138const CALLER_TIMEOUT_GRACE: Duration = Duration::from_millis(5);
139
140/// Session-state key prefix of the record a held delegation resumes from.
141const HELD_DELEGATION_STATE_PREFIX: &str = "adk:agent_tool:held:";
142
143/// A delegation that held one of its delegate's calls for confirmation.
144///
145/// Stored in the caller's session state, under the caller's call, so a later run that
146/// resumes that call rebuilds the delegate's session and the delegate resumes its own
147/// held call as the same call, without asking its model again.
148#[derive(Debug, Serialize, Deserialize)]
149#[serde(rename_all = "camelCase")]
150struct HeldDelegation {
151    /// Fingerprint of the agent-tool call the delegation ran for.
152    call: String,
153    /// The agent that held the call: the wrapped agent or one of its handoff targets.
154    agent: String,
155    /// The delegate's request, under the delegate's own call ID.
156    request: ToolConfirmationRequest,
157    /// The delegate's other held requests, when it holds more than one call.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    more: Vec<ToolConfirmationRequest>,
160    /// The state the delegation started with.
161    state: HashMap<String, Value>,
162    /// The history the delegation started with.
163    history: Vec<Content>,
164    /// The request the delegation was given.
165    user_content: Content,
166    /// The delegate's events so far.
167    events: Vec<Event>,
168}
169
170/// Every request the delegate's events still hold, in the order they were held.
171///
172/// A delegation's events can hold calls of several agents (a handoff target, a workflow's
173/// sub-agents), each on its own branch.
174fn delegate_held_requests(events: &[Event]) -> Vec<ToolConfirmationRequest> {
175    let mut holders = Vec::<(&str, &str)>::new();
176    for event in events {
177        if event.actions.tool_confirmation.is_some()
178            && !holders.contains(&(event.author.as_str(), event.branch.as_str()))
179        {
180            holders.push((event.author.as_str(), event.branch.as_str()));
181        }
182    }
183    let mut requests = Vec::<ToolConfirmationRequest>::new();
184    for (author, branch) in holders {
185        for held in adk_core::held_tool_calls(events, author, branch) {
186            let fingerprint = held.request.fingerprint();
187            if !requests.iter().any(|known| known.fingerprint() == fingerprint) {
188                requests.push(held.request);
189            }
190        }
191    }
192    requests
193}
194
195/// The event that surfaces one of a delegate's held requests as the caller's own hold, as
196/// the caller's agent surfaces the request it ends its run on.
197fn surfaced_confirmation_event(ctx: &dyn ToolContext, request: ToolConfirmationRequest) -> Event {
198    let mut event = Event::new(ctx.invocation_id());
199    event.author = ctx.agent_name().to_string();
200    event.llm_response.interrupted = true;
201    event.llm_response.turn_complete = true;
202    event.llm_response.content = Some(Content::new("model").with_text(format!(
203        "Tool confirmation required for '{}'. Provide approve/deny decision to continue.",
204        request.tool_name
205    )));
206    event.actions.tool_confirmation = Some(request);
207    event
208}
209
210/// Builds the run config of a delegated invocation from its caller's.
211///
212/// Every field is named, so a new one has to be classed as shared with the delegate or as
213/// belonging to the caller's own agent.
214/// The output text of a delegation that produced nothing.
215const NO_RESPONSE: &str = "No response from agent";
216
217fn delegated_run_config(parent: RunConfig) -> RunConfig {
218    let RunConfig {
219        streaming_mode: _,
220        tool_confirmation_decisions: _,
221        tool_confirmation_fingerprints: _,
222        tool_confirmation_handler,
223        tool_reviewer,
224        requested_call_seal,
225        runtime_toolsets: _,
226        cached_content: _,
227        transfer_targets: _,
228        transfer_target_descriptions: _,
229        parent_agent: _,
230        auto_cache,
231        history_max_events,
232        tool_concurrency,
233        record_payloads,
234        trace_payload_max_bytes,
235        max_transfer_depth,
236        invocation_hooks,
237        budget,
238        budget_tracker,
239        action_ledger,
240        tool_policy,
241        egress_policy,
242        governance,
243        tool_approvals,
244        approval_store,
245        approval_service,
246        durable_run_id,
247        request_context,
248        request_metadata,
249        consent_gate,
250        tool_confirmation_timeout,
251        spend_ledger,
252        llm_spend_estimate,
253        audit,
254        acting,
255        deny_on_confirmation_timeout,
256        requested_call: _,
257        intra_compaction,
258        history_compactor,
259    } = parent;
260    RunConfig {
261        // The delegate's output is read whole.
262        streaming_mode: adk_core::StreamingMode::None,
263        // Call-ID decisions name the caller's calls; the delegate's calls have their own IDs.
264        tool_confirmation_decisions: HashMap::new(),
265        tool_confirmation_fingerprints: HashMap::new(),
266        // The handoff topology, the invocation's toolsets and the context cache were built
267        // for the caller's agent. The delegate's own topology is applied by the caller.
268        runtime_toolsets: Vec::new(),
269        cached_content: None,
270        transfer_targets: Vec::new(),
271        transfer_target_descriptions: std::collections::HashMap::new(),
272        parent_agent: None,
273        // Limits, governance, approvals, ledgers and identity span the whole invocation.
274        tool_confirmation_handler,
275        tool_reviewer,
276        requested_call_seal,
277        auto_cache,
278        history_max_events,
279        tool_concurrency,
280        record_payloads,
281        trace_payload_max_bytes,
282        max_transfer_depth,
283        invocation_hooks,
284        budget,
285        budget_tracker,
286        action_ledger,
287        tool_policy,
288        egress_policy,
289        governance,
290        tool_approvals,
291        approval_store,
292        approval_service,
293        durable_run_id,
294        // The delegate acts for the caller's authenticated user, in the same request.
295        request_context,
296        request_metadata,
297        // The delegate acts for the same subject, under the same consent.
298        consent_gate,
299        tool_confirmation_timeout,
300        spend_ledger,
301        llm_spend_estimate,
302        audit,
303        acting,
304        deny_on_confirmation_timeout,
305        // The person asked the caller's agent; a delegate never takes the call.
306        requested_call: None,
307        // The delegate compacts as its caller does; the runner's compactor records a
308        // compaction only for its own invocation, so the delegate's stays in its history.
309        intra_compaction,
310        history_compactor,
311    }
312}
313
314/// Configuration options for AgentTool behavior.
315#[derive(Debug, Clone)]
316pub struct AgentToolConfig {
317    /// Skip summarization after sub-agent execution.
318    /// When true, returns the raw output from the sub-agent.
319    pub skip_summarization: bool,
320
321    /// Forward artifacts between parent and sub-agent.
322    /// When true, the sub-agent can access parent's artifacts.
323    pub forward_artifacts: bool,
324
325    /// Optional timeout for sub-agent execution.
326    ///
327    /// The parent agent applies this instead of its own tool timeout, so a
328    /// delegation is not cut short by a limit sized for ordinary tool calls.
329    /// `None` imposes no limit beyond the run's own budget and cancellation.
330    pub timeout: Option<Duration>,
331
332    /// Custom input schema for the tool.
333    /// If None, defaults to `{"request": "string"}`.
334    pub input_schema: Option<Value>,
335
336    /// Custom output schema for the tool.
337    pub output_schema: Option<Value>,
338}
339
340impl Default for AgentToolConfig {
341    fn default() -> Self {
342        Self {
343            skip_summarization: false,
344            forward_artifacts: true,
345            timeout: None,
346            input_schema: None,
347            output_schema: None,
348        }
349    }
350}
351
352/// AgentTool wraps an Agent to make it callable as a Tool.
353///
354/// When the parent LLM generates a function call targeting this tool,
355/// the framework executes the wrapped agent, captures its final response,
356/// and returns it as the tool's result.
357///
358/// The wrapped agent runs as a delegate of its caller. It shares the caller's budget,
359/// governance, tool policy, approvals, ledgers, audit trail and session scope, and acts for
360/// the caller's subject. It does not inherit the caller's handoff targets, context cache,
361/// invocation toolsets or call-ID decisions; its own topology comes from
362/// [`Agent::configure_run`] and [`Agent::transfer_targets_for`].
363///
364/// Every call the delegate holds for confirmation holds this call too: the tool surfaces
365/// each of the delegate's requests under the caller's call ID — the last through
366/// [`EventActions::tool_confirmation`](adk_core::EventActions::tool_confirmation), the
367/// others before it through [`ToolContext::emit_event`] — and records the delegate's session
368/// in the caller's session state. When the caller resumes the call, the delegate resumes
369/// each held call that has a decision from that session; a call still undecided keeps this
370/// call held (spec 3.1 §10 F4).
371pub struct AgentTool {
372    agent: Arc<dyn Agent>,
373    config: AgentToolConfig,
374    runtime: AgentToolRuntimeConfig,
375}
376
377impl AgentTool {
378    /// Create a new AgentTool wrapping the given agent.
379    pub fn new(agent: Arc<dyn Agent>) -> Self {
380        Self {
381            agent,
382            config: AgentToolConfig::default(),
383            runtime: AgentToolRuntimeConfig::default(),
384        }
385    }
386
387    /// Create a new AgentTool with custom configuration.
388    pub fn with_config(agent: Arc<dyn Agent>, config: AgentToolConfig) -> Self {
389        Self { agent, config, runtime: AgentToolRuntimeConfig::default() }
390    }
391
392    /// Set whether to skip summarization.
393    pub fn skip_summarization(mut self, skip: bool) -> Self {
394        self.config.skip_summarization = skip;
395        self
396    }
397
398    /// Set whether to forward artifacts.
399    pub fn forward_artifacts(mut self, forward: bool) -> Self {
400        self.config.forward_artifacts = forward;
401        self
402    }
403
404    /// Set timeout for sub-agent execution.
405    ///
406    /// The parent agent applies this instead of its own tool timeout. Without
407    /// one, the delegation runs until it finishes or the run is cancelled.
408    ///
409    /// A delegation that runs past it is a failed call with an
410    /// [`ErrorCategory::Timeout`](adk_core::ErrorCategory::Timeout) error in every
411    /// [`AgentToolFailureMode`]: `tool.timeout` from a calling agent that enforces the
412    /// limit, or `tool.agent.timeout` when the tool is executed directly.
413    ///
414    /// # Example
415    ///
416    /// ```rust,ignore
417    /// use adk_tool::AgentTool;
418    /// use std::time::Duration;
419    ///
420    /// let research = AgentTool::new(researcher).timeout(Duration::from_secs(20 * 60));
421    /// ```
422    pub fn timeout(mut self, timeout: Duration) -> Self {
423        self.config.timeout = Some(timeout);
424        self
425    }
426
427    /// Set custom input schema.
428    pub fn input_schema(mut self, schema: Value) -> Self {
429        self.config.input_schema = Some(schema);
430        self
431    }
432
433    /// Set custom output schema.
434    pub fn output_schema(mut self, schema: Value) -> Self {
435        self.config.output_schema = Some(schema);
436        self
437    }
438
439    /// Choose which parent session data is snapshotted into the isolated child session.
440    pub fn session_snapshot(mut self, snapshot: AgentToolSessionSnapshot) -> Self {
441        self.runtime.session_snapshot = snapshot;
442        self
443    }
444
445    /// Set whether the wrapped agent can access the parent's memory service.
446    pub fn forward_memory(mut self, forward: bool) -> Self {
447        self.runtime.forward_memory = forward;
448        self
449    }
450
451    /// Set whether the wrapped agent can access the parent's parallel shared state.
452    ///
453    /// This defaults to `true` to preserve the historical AgentTool behavior.
454    pub fn forward_shared_state(mut self, forward: bool) -> Self {
455        self.runtime.forward_shared_state = forward;
456        self
457    }
458
459    /// Set whether child events are emitted through the parent tool context.
460    ///
461    /// The default is `false` for backward compatibility. State and artifact
462    /// deltas are merged regardless of this setting.
463    ///
464    /// Forwarded events carry the tool's branch, `{caller branch}.{tool}@{call id}`
465    /// ([`adk_core::history::tool_branch`]), so observers can follow the delegate's progress
466    /// while the caller's history leaves it out: the caller's model gets the delegate's answer
467    /// once, as the tool's response.
468    pub fn forward_events(mut self, forward: bool) -> Self {
469        self.runtime.forward_events = forward;
470        self
471    }
472
473    /// Choose whether delegated failures are returned as JSON or propagated.
474    pub fn failure_mode(mut self, mode: AgentToolFailureMode) -> Self {
475        self.runtime.failure_mode = mode;
476        self
477    }
478
479    /// Set whether a delegate's error message is included in the result it fails with.
480    ///
481    /// By default ([`AgentToolFailureMode::ReturnErrorObject`]) a failed delegation returns
482    /// `{"error": "agent execution failed: <component>.<category> (<code>)", "agent": ...}`
483    /// ([`AdkError::redacted`](adk_core::AdkError::redacted)), because the message can quote
484    /// credentials, internal hosts, or upstream bodies, and the result is sent to the calling
485    /// agent's model provider and stored in its session. An error with code
486    /// [`TOOL_INVALID_ARGUMENTS_CODE`](adk_core::TOOL_INVALID_ARGUMENTS_CODE) keeps its message.
487    /// This matches `LlmAgentBuilder::expose_tool_error_messages`. In
488    /// [`AgentToolFailureMode::Propagate`] the calling agent applies its own setting.
489    ///
490    /// Enable this only when every error the delegate can fail with is safe to send to the
491    /// provider.
492    ///
493    /// # Example
494    ///
495    /// ```rust
496    /// use std::sync::Arc;
497    ///
498    /// use adk_core::Agent;
499    /// use adk_tool::AgentTool;
500    ///
501    /// fn billing_tool(billing_agent: Arc<dyn Agent>) -> AgentTool {
502    ///     AgentTool::new(billing_agent).expose_error_messages(true)
503    /// }
504    /// ```
505    pub fn expose_error_messages(mut self, expose: bool) -> Self {
506        self.runtime.expose_error_messages = expose;
507        self
508    }
509
510    /// Set whether delegated failures should be propagated as tool errors.
511    pub fn propagate_failures(self, propagate: bool) -> Self {
512        self.failure_mode(if propagate {
513            AgentToolFailureMode::Propagate
514        } else {
515            AgentToolFailureMode::ReturnErrorObject
516        })
517    }
518
519    /// Bound the number of nested agent-as-tool delegations.
520    pub fn max_delegation_depth(mut self, max_depth: u32) -> Self {
521        self.runtime.max_delegation_depth = Some(max_depth);
522        self
523    }
524
525    /// Sets the principal the wrapped agent acts as when it is delegated to.
526    ///
527    /// Without one, the delegate acts as
528    /// [`AgentPrincipal::derived`](adk_core::AgentPrincipal::derived) from the app name and
529    /// the wrapped agent's name, in the caller's tenant. Either way it acts for the
530    /// caller's subject, and the caller is appended to its delegation chain.
531    ///
532    /// # Example
533    ///
534    /// ```rust,ignore
535    /// use adk_core::{AgentId, AgentPrincipal};
536    /// use adk_tool::AgentTool;
537    ///
538    /// let tool = AgentTool::new(researcher)
539    ///     .agent_principal(AgentPrincipal::new(AgentId::new("spiffe://acme/agent/researcher")?));
540    /// ```
541    pub fn agent_principal(mut self, principal: adk_core::AgentPrincipal) -> Self {
542        self.runtime.principal = Some(principal);
543        self
544    }
545
546    /// Reject child handoff events that cannot be executed by `AgentTool` itself.
547    pub fn reject_child_handoffs(mut self, reject: bool) -> Self {
548        self.runtime.reject_child_handoffs = reject;
549        self
550    }
551
552    /// Executes child handoffs using the supplied exact target registry.
553    ///
554    /// Disabled by default for backward compatibility. When enabled, a child
555    /// transfer remains inside the nested invocation until the terminal member
556    /// returns, after which its result is returned to the original caller.
557    pub fn execute_child_handoffs(
558        mut self,
559        agents: impl IntoIterator<Item = Arc<dyn Agent>>,
560    ) -> Self {
561        self.runtime.execute_child_handoffs = true;
562        self.runtime.reject_child_handoffs = false;
563        self.runtime.handoff_agents =
564            Arc::new(agents.into_iter().map(|agent| (agent.name().to_string(), agent)).collect());
565        self
566    }
567
568    /// Limits the parent history copied into a delegated session.
569    ///
570    /// A value of zero copies no history while still allowing a filtered state
571    /// snapshot when parent-session forwarding is enabled.
572    pub fn history_max_events(mut self, max_events: usize) -> Self {
573        self.runtime.history_max_events = Some(max_events);
574        self
575    }
576
577    /// Copies only these exact state keys into a delegated session.
578    pub fn state_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
579        self.runtime.state_keys = Some(Arc::new(keys.into_iter().map(Into::into).collect()));
580        self
581    }
582
583    /// Allows delegated state writes only to these exact keys.
584    pub fn output_state_keys(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
585        self.runtime.output_state_keys = Some(Arc::new(keys.into_iter().map(Into::into).collect()));
586        self
587    }
588
589    /// Selects how child state writes merge with concurrent parent updates.
590    pub fn state_merge_policy(mut self, policy: AgentToolStateMergePolicy) -> Self {
591        self.runtime.state_merge_policy = policy;
592        self
593    }
594
595    /// Exempts trusted framework-owned keys from concurrent merge checks.
596    ///
597    /// Output allowlists still apply. This is intended for runtime bookkeeping
598    /// that is deliberately updated by both the parent and delegated context.
599    pub fn state_merge_exempt_keys(
600        mut self,
601        keys: impl IntoIterator<Item = impl Into<String>>,
602    ) -> Self {
603        self.runtime.state_merge_exempt_keys = Arc::new(keys.into_iter().map(Into::into).collect());
604        self
605    }
606
607    /// Allows artifact writes only when their names start with one of these prefixes.
608    pub fn artifact_prefixes(
609        mut self,
610        prefixes: impl IntoIterator<Item = impl Into<String>>,
611    ) -> Self {
612        self.runtime.artifact_prefixes =
613            Some(Arc::new(prefixes.into_iter().map(Into::into).collect()));
614        self
615    }
616
617    fn failure(&self, message: String) -> Result<Value> {
618        match self.runtime.failure_mode {
619            AgentToolFailureMode::ReturnErrorObject => Ok(json!({
620                "error": message,
621                "agent": self.agent.name()
622            })),
623            AgentToolFailureMode::Propagate => Err(adk_core::AdkError::tool(message)),
624        }
625    }
626
627    fn state_policy_failure(&self, message: String) -> Result<Value> {
628        match self.runtime.failure_mode {
629            AgentToolFailureMode::ReturnErrorObject => Ok(json!({
630                "error": message,
631                "agent": self.agent.name(),
632                "code": "tool.agent.state_policy_violation"
633            })),
634            AgentToolFailureMode::Propagate => Err(adk_core::AdkError::new(
635                adk_core::ErrorComponent::Tool,
636                adk_core::ErrorCategory::InvalidInput,
637                "tool.agent.state_policy_violation",
638                message,
639            )),
640        }
641    }
642
643    /// Generate the default parameters schema for this agent tool.
644    fn default_parameters_schema(&self) -> Value {
645        json!({
646            "type": "object",
647            "properties": {
648                "request": {
649                    "type": "string",
650                    "description": format!("The request to send to the {} agent", self.agent.name())
651                }
652            },
653            "required": ["request"]
654        })
655    }
656
657    /// Extract the request text from the tool arguments.
658    fn extract_request(&self, args: &Value) -> String {
659        // Try to get "request" field first
660        if let Some(request) = args.get("request").and_then(|v| v.as_str()) {
661            return request.to_string();
662        }
663
664        // If custom schema, try to serialize the whole args
665        if self.config.input_schema.is_some() {
666            return serde_json::to_string(args).unwrap_or_default();
667        }
668
669        // Fallback: convert args to string
670        match args {
671            Value::String(s) => s.clone(),
672            Value::Object(map) => {
673                // Try to find any string field
674                for value in map.values() {
675                    if let Value::String(s) = value {
676                        return s.clone();
677                    }
678                }
679                serde_json::to_string(args).unwrap_or_default()
680            }
681            _ => serde_json::to_string(args).unwrap_or_default(),
682        }
683    }
684
685    /// Extracts the delegation's output from its events.
686    ///
687    /// The output is the text of the final response, as `{"response": text}`. Results of
688    /// the delegate's provider-side tools, such as Gemini code execution, are added as
689    /// `"server_tool_responses"`: the code's output is often the answer, and the model's
690    /// text may not repeat it. A delegate that ends on a tool result, as one whose tool
691    /// skips summarization does, hands back that result: the payload of a single function
692    /// response, or `{"responses": [{"name", "response"}, ...]}` for several.
693    fn extract_response(events: &[Event]) -> Value {
694        let mut output = Self::final_output(events);
695        let server_tool_responses = Self::server_tool_responses(events);
696        if !server_tool_responses.is_empty()
697            && let Some(map) = output.as_object_mut()
698            && map.len() == 1
699            && map.contains_key("response")
700        {
701            // The code's output is the answer; no placeholder text beside it.
702            if map["response"] == NO_RESPONSE {
703                map.insert("response".to_string(), json!(""));
704            }
705            map.insert("server_tool_responses".to_string(), Value::Array(server_tool_responses));
706        }
707        output
708    }
709
710    /// The `ServerToolResponse` payloads of the delegation, each once.
711    ///
712    /// A streamed turn delivers each part in a partial event and may repeat it in the
713    /// aggregated final event, so complete events are read when they carry any. A provider's
714    /// replay-only copy of its turn ([`adk_core::history::is_replay_only`]) is not a tool
715    /// result and holds the sub-agent's reasoning, so it is left out.
716    fn server_tool_responses(events: &[Event]) -> Vec<Value> {
717        let collect = |partial: bool| -> Vec<Value> {
718            events
719                .iter()
720                .filter(|event| event.llm_response.partial == partial)
721                .flat_map(|event| event.llm_response.content.iter())
722                .flat_map(|content| content.parts.iter())
723                .filter(|part| !adk_core::history::is_replay_only(part))
724                .filter_map(|part| match part {
725                    Part::ServerToolResponse { server_tool_response } => {
726                        Some(server_tool_response.clone())
727                    }
728                    _ => None,
729                })
730                .collect()
731        };
732        let complete = collect(false);
733        if complete.is_empty() { collect(true) } else { complete }
734    }
735
736    fn final_output(events: &[Event]) -> Value {
737        let function_responses = |event: &Event| {
738            let responses: Vec<_> = event
739                .llm_response
740                .content
741                .iter()
742                .flat_map(|content| content.parts.iter())
743                .filter_map(|part| match part {
744                    Part::FunctionResponse { function_response, .. } => Some(function_response),
745                    _ => None,
746                })
747                .collect();
748            match responses.as_slice() {
749                [] => None,
750                [response] => Some(response.response.clone()),
751                responses => Some(json!({
752                    "responses": responses
753                        .iter()
754                        .map(|response| json!({
755                            "name": response.name,
756                            "response": response.response,
757                        }))
758                        .collect::<Vec<_>>()
759                })),
760            }
761        };
762
763        // An `output_key` write or another state-only event follows the answer, so only
764        // events that carry content are read.
765        let carries_content = |event: &&Event| {
766            event.llm_response.content.as_ref().is_some_and(|content| !content.parts.is_empty())
767        };
768        if let Some(event) =
769            events.iter().rev().filter(carries_content).find(|event| event.is_final_response())
770        {
771            let text: String = event
772                .llm_response
773                .content
774                .iter()
775                .flat_map(|content| content.parts.iter())
776                .filter_map(|part| match part {
777                    Part::Text { text } => Some(text.as_str()),
778                    _ => None,
779                })
780                .collect();
781            let has_text =
782                event.llm_response.content.iter().any(|content| {
783                    content.parts.iter().any(|part| matches!(part, Part::Text { .. }))
784                });
785            if has_text {
786                return json!({ "response": text });
787            }
788            if let Some(payload) = function_responses(event) {
789                return payload;
790            }
791        }
792
793        if let Some(last_event) = events.iter().rev().find(carries_content) {
794            if let Some(text) = last_event
795                .llm_response
796                .content
797                .iter()
798                .flat_map(|content| content.parts.iter())
799                .find_map(|part| match part {
800                    Part::Text { text } => Some(text),
801                    _ => None,
802                })
803            {
804                return json!({ "response": text });
805            }
806            if let Some(payload) = function_responses(last_event) {
807                return payload;
808            }
809        }
810        json!({ "response": NO_RESPONSE })
811    }
812
813    fn project_parent_history(history: Vec<Content>, max_events: Option<usize>) -> Vec<Content> {
814        let mut pending_calls = HashMap::<String, usize>::new();
815        let mut projected = Vec::with_capacity(history.len());
816        let mut balanced_boundaries = vec![0];
817        let mut open_group_start = None;
818
819        for content in history {
820            let was_pending = !pending_calls.is_empty();
821            let has_function_call =
822                content.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }));
823            let has_function_response =
824                content.parts.iter().any(|part| matches!(part, Part::FunctionResponse { .. }));
825
826            // Progress from a delegated agent may be emitted while its caller's
827            // tool call is still open. It is useful to stream to observers, but
828            // it is not valid provider history between that call and response.
829            if was_pending && !has_function_call && !has_function_response {
830                continue;
831            }
832            if !was_pending && has_function_response && !has_function_call {
833                continue;
834            }
835
836            if !was_pending && has_function_call {
837                open_group_start = Some(projected.len());
838            }
839            for part in &content.parts {
840                match part {
841                    Part::FunctionCall { name, id, .. } => {
842                        let key = id.as_ref().unwrap_or(name);
843                        *pending_calls.entry(key.clone()).or_default() += 1;
844                    }
845                    Part::FunctionResponse { function_response, id, .. } => {
846                        let key = id.as_ref().unwrap_or(&function_response.name);
847                        if let Some(count) = pending_calls.get_mut(key) {
848                            *count -= 1;
849                            if *count == 0 {
850                                pending_calls.remove(key);
851                            }
852                        }
853                    }
854                    _ => {}
855                }
856            }
857            projected.push(content);
858            if pending_calls.is_empty() {
859                open_group_start = None;
860                balanced_boundaries.push(projected.len());
861            }
862        }
863
864        // ToolContext execution occurs before the caller's FunctionResponse is
865        // added to its session. Never expose that currently-open call (or any
866        // trailing content after it) as child model history.
867        if let Some(group_start) = open_group_start {
868            projected.truncate(group_start);
869        }
870        let balanced_end = projected.len();
871
872        if let Some(max_events) = max_events {
873            let desired_start = balanced_end.saturating_sub(max_events);
874            let balanced_start = balanced_boundaries
875                .into_iter()
876                .find(|boundary| *boundary >= desired_start)
877                .unwrap_or(balanced_end);
878            projected.drain(..balanced_start);
879        }
880
881        projected
882    }
883}
884
885#[async_trait]
886impl Tool for AgentTool {
887    fn name(&self) -> &str {
888        self.agent.name()
889    }
890
891    fn description(&self) -> &str {
892        self.agent.description()
893    }
894
895    fn parameters_schema(&self) -> Option<Value> {
896        Some(self.config.input_schema.clone().unwrap_or_else(|| self.default_parameters_schema()))
897    }
898
899    fn response_schema(&self) -> Option<Value> {
900        self.config.output_schema.clone()
901    }
902
903    fn is_long_running(&self) -> bool {
904        // Agent execution could take time, but we wait for completion
905        false
906    }
907
908    fn is_agent_delegation(&self) -> bool {
909        true
910    }
911
912    // The delegate reaches its model through the client its builder configured; each of its
913    // own tool calls is checked against the egress policy the delegation carries.
914    fn egress(&self, _args: &Value) -> adk_core::egress::ToolEgress {
915        adk_core::egress::ToolEgress::Configured
916    }
917
918    // The delegation's own timeout replaces the parent's generic tool timeout.
919    fn timeout_override(&self) -> Option<Option<Duration>> {
920        Some(self.config.timeout)
921    }
922
923    #[adk_telemetry::instrument(
924        skip(self, ctx, args),
925        fields(
926            agent_tool.name = %self.agent.name(),
927            agent_tool.description = %self.agent.description(),
928            function_call.id = %ctx.function_call_id()
929        )
930    )]
931    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
932        adk_telemetry::debug!("Executing agent tool: {}", self.agent.name());
933
934        let parent_run_config = ctx.run_config().cloned().unwrap_or_default();
935        // A decision the caller gave this call by its ID was given for the request this call
936        // surfaced when its delegate held a call; it is handed to that call below.
937        let call_decision =
938            parent_run_config.tool_confirmation_decisions.get(ctx.function_call_id()).copied().map(
939                |decision| {
940                    let bound = parent_run_config
941                        .tool_confirmation_fingerprints
942                        .get(ctx.function_call_id())
943                        .cloned();
944                    (decision, bound)
945                },
946            );
947        let mut child_run_config = delegated_run_config(parent_run_config);
948        self.agent.configure_run(self.agent.name(), &mut child_run_config);
949        if let Some(targets) = self.agent.transfer_targets_for(self.agent.name()) {
950            child_run_config.transfer_targets = targets;
951        }
952        let caller = ctx.acting_context();
953        let delegate = self.runtime.principal.clone().unwrap_or_else(|| {
954            let mut derived = adk_core::AgentPrincipal::derived(ctx.app_name(), self.agent.name());
955            derived.tenant = caller.agent.tenant.clone();
956            derived
957        });
958        // The delegate acts for the caller's subject, with the caller appended to the chain;
959        // the subject was admitted when the caller's run started.
960        let delegated = caller.delegate(delegate);
961        child_run_config.acting.principals.insert(self.agent.name().to_string(), delegated.agent);
962        child_run_config.acting.on_behalf_of = delegated.on_behalf_of;
963        child_run_config.acting.delegation_chain = delegated.delegation_chain;
964        let child_depth = ctx.delegation_depth().saturating_add(1);
965        let max_depth = self.runtime.max_delegation_depth.or(ctx.max_delegation_depth());
966        if max_depth.is_some_and(|max| child_depth > max) {
967            return self.failure(format!(
968                "agent delegation depth {child_depth} exceeds the configured maximum of {}",
969                max_depth.unwrap_or_default()
970            ));
971        }
972        if ctx.is_cancelled() {
973            return self.failure("agent delegation was cancelled before execution".to_string());
974        }
975
976        // Extract the request from args
977        let request_text = self.extract_request(&args);
978        let parent_state_baseline =
979            ctx.session().map(|session| session.state().all()).unwrap_or_default();
980        let user_content = Content::new("user").with_text(&request_text);
981
982        // A delegation that held a call in an earlier run resumes from where it stopped, so the
983        // held call runs as the same call once it has a decision.
984        let held_key = format!(
985            "{HELD_DELEGATION_STATE_PREFIX}{}",
986            adk_core::json_digest(&json!([ctx.agent_name(), self.name(), ctx.function_call_id()]))
987        );
988        let call_fingerprint = adk_core::tool_call_fingerprint(self.name(), &args);
989        let resumed = ctx
990            .session()
991            .and_then(|session| session.state().get(&held_key))
992            .and_then(|value| serde_json::from_value::<HeldDelegation>(value).ok())
993            .filter(|held| held.call == call_fingerprint)
994            .and_then(|held| {
995                let agent = if held.agent == self.agent.name() {
996                    Some(self.agent.clone())
997                } else {
998                    self.runtime.handoff_agents.get(&held.agent).cloned()
999                };
1000                agent.map(|agent| (agent, held))
1001            });
1002
1003        let resumed_holder = resumed.as_ref().map(|(_, held)| held.agent.clone());
1004        let (start_agent, session, child_user_content, origin_user_content) = match resumed {
1005            Some((agent, held)) => {
1006                // Whatever this run ends with replaces the record.
1007                let mut actions = ctx.actions();
1008                actions.state_delta.insert(held_key.clone(), Value::Null);
1009                ctx.set_actions(actions);
1010                // With several held requests under this one call, a call-ID decision reaches
1011                // only the request its fingerprint binding names.
1012                if let Some((decision, bound)) = call_decision {
1013                    let single = held.more.is_empty();
1014                    for request in std::iter::once(&held.request).chain(&held.more) {
1015                        let Some(held_call_id) = request.function_call_id.clone() else {
1016                            continue;
1017                        };
1018                        let fingerprint = request.fingerprint();
1019                        let applies = match &bound {
1020                            Some(bound) => *bound == fingerprint,
1021                            None => single,
1022                        };
1023                        if applies {
1024                            child_run_config
1025                                .tool_confirmation_decisions
1026                                .insert(held_call_id.clone(), decision);
1027                            child_run_config
1028                                .tool_confirmation_fingerprints
1029                                .insert(held_call_id, fingerprint);
1030                        }
1031                    }
1032                }
1033                tracing::info!(
1034                    agent_tool.name = %self.agent.name(),
1035                    agent.name = %held.agent,
1036                    tool.name = %held.request.tool_name,
1037                    "resuming a delegation that held a call for confirmation"
1038                );
1039                let session = AgentToolSession::resume(
1040                    ctx.session_id().to_string(),
1041                    ctx.app_name().to_string(),
1042                    ctx.user_id().to_string(),
1043                    &held,
1044                );
1045                // A run that resumes held calls carries no new user input.
1046                (agent, session, Content::new("user"), held.user_content)
1047            }
1048            None => {
1049                let (mut state, history) = match (self.runtime.session_snapshot, ctx.session()) {
1050                    (AgentToolSessionSnapshot::Parent, Some(session)) => {
1051                        (session.state().all(), session.conversation_history())
1052                    }
1053                    _ => (HashMap::new(), Vec::new()),
1054                };
1055                state.retain(|key, _| {
1056                    !key.starts_with(HELD_DELEGATION_STATE_PREFIX)
1057                        && self.runtime.state_keys.as_ref().is_none_or(|keys| keys.contains(key))
1058                });
1059                let session = AgentToolSession::new(
1060                    ctx.session_id().to_string(),
1061                    ctx.app_name().to_string(),
1062                    ctx.user_id().to_string(),
1063                    state,
1064                    AgentTool::project_parent_history(history, self.runtime.history_max_events),
1065                );
1066                (self.agent.clone(), session, user_content.clone(), user_content)
1067            }
1068        };
1069
1070        // Create an isolated context for the sub-agent
1071        let sub_ctx = Arc::new(AgentToolInvocationContext::new(
1072            ctx.clone(),
1073            self.agent.clone(),
1074            child_user_content,
1075            AgentToolChildConfig {
1076                forward_artifacts: self.config.forward_artifacts,
1077                artifact_prefixes: self.runtime.artifact_prefixes.clone(),
1078                forward_memory: self.runtime.forward_memory,
1079                forward_shared_state: self.runtime.forward_shared_state,
1080                session: Arc::new(session),
1081                run_config: child_run_config,
1082                delegation_depth: child_depth,
1083                max_delegation_depth: max_depth,
1084                orchestration_root_invocation_id: ctx
1085                    .orchestration_root_invocation_id()
1086                    .to_string(),
1087                orchestration_edge_id: ctx.orchestration_edge_id().map_or_else(
1088                    || ctx.function_call_id().to_string(),
1089                    |parent| format!("{parent}/{}", ctx.function_call_id()),
1090                ),
1091            },
1092        ));
1093
1094        // Execute the sub-agent
1095        let execution = async {
1096            // A delegation held by one of its handoff targets resumes in that target.
1097            let mut active_ctx = if Arc::ptr_eq(&start_agent, &self.agent) {
1098                sub_ctx.clone()
1099            } else {
1100                Arc::new(sub_ctx.for_agent(start_agent.clone()))
1101            };
1102            let mut active_agent = start_agent;
1103            let mut transfer_depth = 0_u32;
1104            let mut events = Vec::new();
1105            let mut state_delta = HashMap::new();
1106            let mut artifact_delta = HashMap::new();
1107            // The agent whose run ended on the latest hold; the delegation resumes in it.
1108            let mut holder = None;
1109
1110            loop {
1111                let mut event_stream = active_agent.run(active_ctx.clone()).await?;
1112                let mut transfer = None;
1113                while let Some(result) = event_stream.next().await {
1114                    match result {
1115                        Ok(event) => {
1116                            if let Some(target) = &event.actions.transfer_to_agent {
1117                                if self.runtime.reject_child_handoffs {
1118                                    return Err(adk_core::AdkError::tool(format!(
1119                                        "agent '{}' requested handoff to '{target}', but AgentTool cannot execute child handoffs in this configuration",
1120                                        active_agent.name()
1121                                    )));
1122                                }
1123                                if self.runtime.execute_child_handoffs {
1124                                    transfer = Some(target.clone());
1125                                }
1126                            }
1127                            if event.actions.tool_confirmation.is_some() {
1128                                holder = Some(active_agent.name().to_string());
1129                            }
1130                            // A delegation's own resume records are not the caller's state.
1131                            state_delta.extend(
1132                                event
1133                                    .actions
1134                                    .state_delta
1135                                    .iter()
1136                                    .filter(|(key, _)| {
1137                                        !key.starts_with(HELD_DELEGATION_STATE_PREFIX)
1138                                    })
1139                                    .map(|(key, value)| (key.clone(), value.clone())),
1140                            );
1141                            artifact_delta.extend(event.actions.artifact_delta.clone());
1142                            sub_ctx.session.apply_event(&event);
1143                            if self.runtime.forward_events {
1144                                let mut forwarded = event.clone();
1145                                if self.runtime.execute_child_handoffs && transfer.is_some() {
1146                                    // The AgentTool consumes this control-flow edge internally.
1147                                    // Do not let the parent Runner execute the same handoff again.
1148                                    forwarded.actions.transfer_to_agent = None;
1149                                }
1150                                // The caller surfaces the delegate's hold as its own call's.
1151                                forwarded.actions.tool_confirmation = None;
1152                                // On the tool's own branch the caller's history leaves the
1153                                // delegate's turns out; its model gets the tool's response.
1154                                let tool_branch = adk_core::history::tool_branch(
1155                                    ctx.branch(),
1156                                    self.name(),
1157                                    ctx.function_call_id(),
1158                                );
1159                                forwarded.branch = if forwarded.branch.is_empty() {
1160                                    tool_branch
1161                                } else {
1162                                    format!("{tool_branch}.{}", forwarded.branch)
1163                                };
1164                                ctx.emit_event(forwarded).await;
1165                            }
1166                            events.push(event);
1167                            if transfer.is_some() {
1168                                break;
1169                            }
1170                        }
1171                        Err(error) => {
1172                            // The message can quote credentials or upstream bodies.
1173                            adk_telemetry::error!(
1174                                error = %error.diagnostics(),
1175                                "sub-agent execution failed"
1176                            );
1177                            return Err(error);
1178                        }
1179                    }
1180                }
1181
1182                let Some(target_name) = transfer else {
1183                    break;
1184                };
1185                transfer_depth = transfer_depth.saturating_add(1);
1186                let max_transfer_depth = active_ctx.run_config.max_transfer_depth.unwrap_or(10);
1187                if transfer_depth > max_transfer_depth {
1188                    return Err(adk_core::AdkError::tool(format!(
1189                        "nested handoff depth {transfer_depth} exceeds the configured maximum of {max_transfer_depth}"
1190                    )));
1191                }
1192                let target = self
1193                    .runtime
1194                    .handoff_agents
1195                    .get(&target_name)
1196                    .cloned()
1197                    .ok_or_else(|| {
1198                        adk_core::AdkError::tool(format!(
1199                            "agent '{}' requested nested handoff to unregistered target '{target_name}'",
1200                            active_agent.name()
1201                        ))
1202                    })?;
1203                active_ctx = Arc::new(active_ctx.for_agent(target.clone()));
1204                active_agent = target;
1205            }
1206
1207            Ok((events, state_delta, artifact_delta, holder))
1208        };
1209
1210        // A delegation that runs out of time is a failed call, so retries, error hooks, the
1211        // circuit breaker and the action ledger all see it as one. A caller that enforces the
1212        // limit itself through `timeout_override` reaches it first and reports its own timeout,
1213        // which treats a delegation cut mid-flight as one whose effects are unknown.
1214        let result = if let Some(timeout_duration) = self.config.timeout {
1215            match tokio::time::timeout(timeout_duration + CALLER_TIMEOUT_GRACE, execution).await {
1216                Ok(r) => r,
1217                Err(_) => {
1218                    return Err(adk_core::AdkError::new(
1219                        adk_core::ErrorComponent::Tool,
1220                        adk_core::ErrorCategory::Timeout,
1221                        "tool.agent.timeout",
1222                        format!(
1223                            "agent '{}' execution timed out after {timeout_duration:?}",
1224                            self.agent.name()
1225                        ),
1226                    ));
1227                }
1228            }
1229        } else {
1230            execution.await
1231        };
1232
1233        match result {
1234            Ok((events, mut state_delta, artifact_delta, holder)) => {
1235                // Every call the delegate still holds, including one an earlier run held
1236                // that this run's decisions did not reach, keeps the delegation held.
1237                let held_requests = delegate_held_requests(&sub_ctx.session.events());
1238                let hold = (!held_requests.is_empty()).then(|| {
1239                    let agent =
1240                        holder.or(resumed_holder).unwrap_or_else(|| self.agent.name().to_string());
1241                    (agent, held_requests)
1242                });
1243                if let Some(allowed) = &self.runtime.output_state_keys {
1244                    if let Some(key) = state_delta.keys().find(|key| !allowed.contains(*key)) {
1245                        return self.state_policy_failure(format!(
1246                            "agent '{}' attempted unauthorized state write to '{key}'",
1247                            self.agent.name()
1248                        ));
1249                    }
1250                    state_delta.retain(|key, _| allowed.contains(key));
1251                }
1252                if self.runtime.state_merge_policy == AgentToolStateMergePolicy::RejectConflicts
1253                    && let Some(parent_session) = ctx.session()
1254                    && let Some(key) = state_delta.keys().find(|key| {
1255                        !self.runtime.state_merge_exempt_keys.contains(*key)
1256                            && parent_session.state().get(key)
1257                                != parent_state_baseline.get(*key).cloned()
1258                    })
1259                {
1260                    return self.state_policy_failure(format!(
1261                        "agent '{}' state write to '{key}' conflicts with a concurrent parent update",
1262                        self.agent.name()
1263                    ));
1264                }
1265                if let Some(prefixes) = &self.runtime.artifact_prefixes
1266                    && let Some(name) = artifact_delta
1267                        .keys()
1268                        .find(|name| !prefixes.iter().any(|prefix| name.starts_with(prefix)))
1269                {
1270                    return self.state_policy_failure(format!(
1271                        "agent '{}' attempted unauthorized artifact write to '{name}'",
1272                        self.agent.name()
1273                    ));
1274                }
1275                // A held delegation has no output yet, so it does not end the caller's turn.
1276                let skip_summarization = self.config.skip_summarization && hold.is_none();
1277                // Forward state_delta and artifact_delta to parent context
1278                if !state_delta.is_empty() || !artifact_delta.is_empty() || skip_summarization {
1279                    let mut parent_actions = ctx.actions();
1280                    parent_actions.state_delta.extend(state_delta);
1281                    parent_actions.artifact_delta.extend(artifact_delta);
1282                    parent_actions.skip_summarization |= skip_summarization;
1283                    ctx.set_actions(parent_actions);
1284                }
1285
1286                // The delegate held calls for confirmation: this call is held with them, under
1287                // each of the delegate's requests, and the delegation is recorded so it resumes.
1288                if let Some((agent, mut requests)) = hold {
1289                    let request = requests.remove(0);
1290                    let more = requests;
1291                    let rekeyed = |request: &ToolConfirmationRequest| ToolConfirmationRequest {
1292                        function_call_id: Some(ctx.function_call_id().to_string()),
1293                        ..request.clone()
1294                    };
1295                    let reason = match more.len() {
1296                        0 => format!(
1297                            "agent '{agent}' is waiting for a decision on tool '{}'",
1298                            request.tool_name
1299                        ),
1300                        others => format!(
1301                            "agent '{agent}' is waiting for decisions on {} tool calls",
1302                            others + 1
1303                        ),
1304                    };
1305                    // The caller ends its run on the last request; the others are surfaced
1306                    // before it, in the order the delegate held them (spec 3.1 §10 F4).
1307                    let mut surfaced: Vec<ToolConfirmationRequest> =
1308                        std::iter::once(&request).chain(&more).map(rekeyed).collect();
1309                    let last = surfaced.pop().expect("the delegate holds at least one call");
1310                    for request in surfaced {
1311                        ctx.emit_event(surfaced_confirmation_event(ctx.as_ref(), request)).await;
1312                    }
1313                    let record = HeldDelegation {
1314                        call: call_fingerprint,
1315                        agent,
1316                        request,
1317                        more,
1318                        state: sub_ctx.session.initial_state.clone(),
1319                        history: sub_ctx.session.initial_history.clone(),
1320                        user_content: origin_user_content,
1321                        events: sub_ctx.session.events(),
1322                    };
1323                    let record = serde_json::to_value(record).map_err(|error| {
1324                        adk_core::AdkError::new(
1325                            adk_core::ErrorComponent::Tool,
1326                            adk_core::ErrorCategory::Internal,
1327                            "tool.agent.hold_not_recorded",
1328                            format!("the held delegation could not be recorded: {error}"),
1329                        )
1330                    })?;
1331                    let mut parent_actions = ctx.actions();
1332                    parent_actions.state_delta.insert(held_key, record);
1333                    parent_actions.tool_confirmation = Some(last);
1334                    ctx.set_actions(parent_actions);
1335                    tracing::info!(
1336                        agent_tool.name = %self.agent.name(),
1337                        confirmation.reason = %reason,
1338                        "delegated agent held a call for confirmation"
1339                    );
1340                    return Ok(adk_core::confirmation_pending_response(reason));
1341                }
1342
1343                // Extract and return the response
1344                let response = Self::extract_response(&events);
1345
1346                adk_telemetry::debug!(
1347                    "Agent tool {} completed with {} events",
1348                    self.agent.name(),
1349                    events.len()
1350                );
1351
1352                Ok(response)
1353            }
1354            Err(error) => match self.runtime.failure_mode {
1355                // The result goes to the caller's model provider and session, so the delegate's
1356                // message stays out of it unless exposed, as `LlmAgent` treats tool errors.
1357                AgentToolFailureMode::ReturnErrorObject => {
1358                    let failure = if self.runtime.expose_error_messages
1359                        || error.code == adk_core::TOOL_INVALID_ARGUMENTS_CODE
1360                    {
1361                        error.to_string()
1362                    } else {
1363                        error.redacted()
1364                    };
1365                    Ok(json!({
1366                        "error": format!("agent execution failed: {failure}"),
1367                        "agent": self.agent.name()
1368                    }))
1369                }
1370                // The delegate's error keeps its category and code, so the caller can tell a
1371                // timeout or rate limit from an internal failure.
1372                AgentToolFailureMode::Propagate => {
1373                    let mut error = error;
1374                    error.message = format!(
1375                        "agent '{}' execution failed: {}",
1376                        self.agent.name(),
1377                        error.message
1378                    );
1379                    Err(error)
1380                }
1381            },
1382        }
1383    }
1384}
1385
1386// Internal context for sub-agent execution
1387struct AgentToolInvocationContext {
1388    parent_ctx: Arc<dyn ToolContext>,
1389    agent: Arc<dyn Agent>,
1390    user_content: Content,
1391    invocation_id: String,
1392    ended: Arc<AtomicBool>,
1393    forward_artifacts: bool,
1394    artifact_prefixes: Option<Arc<Vec<String>>>,
1395    forward_memory: bool,
1396    forward_shared_state: bool,
1397    session: Arc<AgentToolSession>,
1398    run_config: RunConfig,
1399    delegation_depth: u32,
1400    max_delegation_depth: Option<u32>,
1401    orchestration_root_invocation_id: String,
1402    orchestration_edge_id: String,
1403}
1404
1405impl AgentToolInvocationContext {
1406    fn new(
1407        parent_ctx: Arc<dyn ToolContext>,
1408        agent: Arc<dyn Agent>,
1409        user_content: Content,
1410        child_config: AgentToolChildConfig,
1411    ) -> Self {
1412        let AgentToolChildConfig {
1413            forward_artifacts,
1414            artifact_prefixes,
1415            forward_memory,
1416            forward_shared_state,
1417            session,
1418            run_config,
1419            delegation_depth,
1420            max_delegation_depth,
1421            orchestration_root_invocation_id,
1422            orchestration_edge_id,
1423        } = child_config;
1424        Self {
1425            session,
1426            parent_ctx,
1427            agent,
1428            user_content,
1429            invocation_id: format!("agent-tool-{}", uuid::Uuid::new_v4()),
1430            ended: Arc::new(AtomicBool::new(false)),
1431            forward_artifacts,
1432            artifact_prefixes,
1433            forward_memory,
1434            forward_shared_state,
1435            run_config,
1436            delegation_depth,
1437            max_delegation_depth,
1438            orchestration_root_invocation_id,
1439            orchestration_edge_id,
1440        }
1441    }
1442
1443    fn for_agent(&self, agent: Arc<dyn Agent>) -> Self {
1444        let mut run_config = self.run_config.clone();
1445        run_config.transfer_targets = Vec::new();
1446        run_config.parent_agent = None;
1447        agent.configure_run(agent.name(), &mut run_config);
1448        if let Some(targets) = agent.transfer_targets_for(agent.name()) {
1449            run_config.transfer_targets = targets;
1450        }
1451        Self {
1452            parent_ctx: self.parent_ctx.clone(),
1453            agent,
1454            user_content: self.user_content.clone(),
1455            invocation_id: self.invocation_id.clone(),
1456            ended: self.ended.clone(),
1457            forward_artifacts: self.forward_artifacts,
1458            artifact_prefixes: self.artifact_prefixes.clone(),
1459            forward_memory: self.forward_memory,
1460            forward_shared_state: self.forward_shared_state,
1461            session: self.session.clone(),
1462            run_config,
1463            delegation_depth: self.delegation_depth,
1464            max_delegation_depth: self.max_delegation_depth,
1465            orchestration_root_invocation_id: self.orchestration_root_invocation_id.clone(),
1466            orchestration_edge_id: self.orchestration_edge_id.clone(),
1467        }
1468    }
1469}
1470
1471#[async_trait]
1472impl ReadonlyContext for AgentToolInvocationContext {
1473    fn invocation_id(&self) -> &str {
1474        &self.invocation_id
1475    }
1476
1477    fn agent_name(&self) -> &str {
1478        self.agent.name()
1479    }
1480
1481    fn user_id(&self) -> &str {
1482        self.parent_ctx.user_id()
1483    }
1484
1485    fn app_name(&self) -> &str {
1486        self.parent_ctx.app_name()
1487    }
1488
1489    // The delegate runs inside the caller's session: its history and state are its own, but
1490    // its approvals, policy requests and audit records belong to the caller's session.
1491    fn session_id(&self) -> &str {
1492        self.session.id()
1493    }
1494
1495    fn branch(&self) -> &str {
1496        ""
1497    }
1498
1499    fn user_content(&self) -> &Content {
1500        &self.user_content
1501    }
1502
1503    fn acting_context(&self) -> adk_core::ActingContext {
1504        self.run_config.acting_context_for(self.app_name(), self.agent_name(), self.user_id())
1505    }
1506
1507    fn is_authenticated(&self) -> bool {
1508        self.parent_ctx.is_authenticated()
1509    }
1510}
1511
1512#[async_trait]
1513impl CallbackContext for AgentToolInvocationContext {
1514    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
1515        if !self.forward_artifacts {
1516            return None;
1517        }
1518        let artifacts = self.parent_ctx.artifacts()?;
1519        self.artifact_prefixes.as_ref().map_or(Some(artifacts.clone()), |prefixes| {
1520            Some(Arc::new(AgentToolArtifacts {
1521                inner: artifacts,
1522                allowed_write_prefixes: prefixes.clone(),
1523            }) as Arc<dyn Artifacts>)
1524        })
1525    }
1526
1527    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
1528        self.forward_shared_state.then(|| self.parent_ctx.shared_state()).flatten()
1529    }
1530}
1531
1532struct AgentToolArtifacts {
1533    inner: Arc<dyn Artifacts>,
1534    allowed_write_prefixes: Arc<Vec<String>>,
1535}
1536
1537#[async_trait]
1538impl Artifacts for AgentToolArtifacts {
1539    async fn save(&self, name: &str, data: &Part) -> Result<i64> {
1540        if !self.allowed_write_prefixes.iter().any(|prefix| name.starts_with(prefix)) {
1541            return Err(adk_core::AdkError::new(
1542                adk_core::ErrorComponent::Artifact,
1543                adk_core::ErrorCategory::Forbidden,
1544                "artifact.agent_tool.write_denied",
1545                format!("delegated artifact write to '{name}' is outside the allowed prefixes"),
1546            ));
1547        }
1548        self.inner.save(name, data).await
1549    }
1550
1551    async fn load(&self, name: &str) -> Result<Part> {
1552        self.inner.load(name).await
1553    }
1554
1555    async fn list(&self) -> Result<Vec<String>> {
1556        self.inner.list().await
1557    }
1558}
1559
1560#[async_trait]
1561impl InvocationContext for AgentToolInvocationContext {
1562    fn agent(&self) -> Arc<dyn Agent> {
1563        self.agent.clone()
1564    }
1565
1566    fn memory(&self) -> Option<Arc<dyn Memory>> {
1567        self.forward_memory.then(|| self.parent_ctx.memory()).flatten()
1568    }
1569
1570    fn session(&self) -> &dyn Session {
1571        self.session.as_ref()
1572    }
1573
1574    fn run_config(&self) -> &RunConfig {
1575        &self.run_config
1576    }
1577
1578    fn end_invocation(&self) {
1579        self.ended.store(true, std::sync::atomic::Ordering::SeqCst);
1580    }
1581
1582    fn ended(&self) -> bool {
1583        self.ended.load(std::sync::atomic::Ordering::SeqCst)
1584    }
1585
1586    fn is_cancelled(&self) -> bool {
1587        self.parent_ctx.is_cancelled()
1588    }
1589
1590    /// Authenticated scopes are forwarded so a scope-guarded tool used by the
1591    /// wrapped agent sees the caller's grants rather than an empty set.
1592    fn user_scopes(&self) -> Vec<String> {
1593        self.parent_ctx.user_scopes()
1594    }
1595
1596    fn request_metadata(&self) -> HashMap<String, Value> {
1597        self.parent_ctx.request_metadata()
1598    }
1599
1600    fn delegation_depth(&self) -> u32 {
1601        self.delegation_depth
1602    }
1603
1604    fn max_delegation_depth(&self) -> Option<u32> {
1605        self.max_delegation_depth
1606    }
1607
1608    fn orchestration_root_invocation_id(&self) -> &str {
1609        &self.orchestration_root_invocation_id
1610    }
1611
1612    fn orchestration_edge_id(&self) -> Option<&str> {
1613        Some(&self.orchestration_edge_id)
1614    }
1615
1616    /// Secret access is forwarded so the wrapped agent's tools can resolve
1617    /// secrets through the same provider as the calling agent.
1618    async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
1619        self.parent_ctx.get_secret(name).await
1620    }
1621
1622    async fn get_secret_for(
1623        &self,
1624        request: &adk_core::SecretRequest,
1625    ) -> adk_core::Result<Option<String>> {
1626        // The parent here is a `ToolContext`, which carries no identity of its own, so
1627        // only the stated purpose survives the hop. An agent invoked as a tool
1628        // therefore presents that agent's identity rather than the inner tool's.
1629        match &request.purpose {
1630            Some(purpose) => self.parent_ctx.get_secret_for_purpose(&request.name, purpose).await,
1631            None => self.parent_ctx.get_secret(&request.name).await,
1632        }
1633    }
1634
1635    // Cancellation and request metadata are forwarded above through the
1636    // backward-compatible ToolContext capability methods.
1637}
1638
1639// Minimal session for sub-agent execution
1640struct AgentToolSession {
1641    id: String,
1642    app_name: String,
1643    user_id: String,
1644    state: std::sync::RwLock<HashMap<String, Value>>,
1645    history: std::sync::RwLock<Vec<Content>>,
1646    /// The state and history the delegation started with, kept so a held delegation can be
1647    /// rebuilt.
1648    initial_state: HashMap<String, Value>,
1649    initial_history: Vec<Content>,
1650    /// The delegated agents' complete events, which their held calls are read from.
1651    events: std::sync::RwLock<Vec<Event>>,
1652}
1653
1654impl AgentToolSession {
1655    fn new(
1656        id: String,
1657        app_name: String,
1658        user_id: String,
1659        state: HashMap<String, Value>,
1660        history: Vec<Content>,
1661    ) -> Self {
1662        Self {
1663            id,
1664            app_name,
1665            user_id,
1666            state: std::sync::RwLock::new(state.clone()),
1667            history: std::sync::RwLock::new(history.clone()),
1668            initial_state: state,
1669            initial_history: history,
1670            events: std::sync::RwLock::new(Vec::new()),
1671        }
1672    }
1673
1674    /// Rebuilds the session of a delegation that held a call.
1675    ///
1676    /// The history is the one the delegate's model saw, ending on an empty user turn, as a
1677    /// session does when a run resumes held calls.
1678    fn resume(id: String, app_name: String, user_id: String, held: &HeldDelegation) -> Self {
1679        let mut history = held.history.clone();
1680        // The delegate was given the request as its current user turn.
1681        match history.iter().rposition(|content| content.role == "user") {
1682            Some(index) => history[index] = held.user_content.clone(),
1683            None => history.push(held.user_content.clone()),
1684        }
1685        let session = Self {
1686            id,
1687            app_name,
1688            user_id,
1689            state: std::sync::RwLock::new(held.state.clone()),
1690            history: std::sync::RwLock::new(history),
1691            initial_state: held.state.clone(),
1692            initial_history: held.history.clone(),
1693            events: std::sync::RwLock::new(Vec::new()),
1694        };
1695        for event in &held.events {
1696            session.apply_event(event);
1697        }
1698        if let Ok(mut history) = session.history.write() {
1699            history.push(Content::new("user"));
1700        }
1701        session
1702    }
1703
1704    fn apply_event(&self, event: &Event) {
1705        if !event.actions.state_delta.is_empty()
1706            && let Ok(mut state) = self.state.write()
1707        {
1708            for (key, value) in &event.actions.state_delta {
1709                if adk_core::validate_state_key(key).is_ok() {
1710                    state.insert(key.clone(), value.clone());
1711                }
1712            }
1713        }
1714        // A resumed call's response takes its pending response's place.
1715        if let Some(content) = &event.llm_response.content
1716            && let Ok(mut history) = self.history.write()
1717            && let Some(rest) = adk_core::supersede_pending_responses(&mut history, content.clone())
1718        {
1719            history.push(rest);
1720        }
1721        if !event.llm_response.partial
1722            && let Ok(mut events) = self.events.write()
1723        {
1724            // Provider debug copies are not needed to resume, and would be stored again.
1725            let mut kept = event.clone();
1726            kept.provider_metadata.clear();
1727            kept.llm_request = None;
1728            events.push(kept);
1729        }
1730    }
1731
1732    fn events(&self) -> Vec<Event> {
1733        self.events.read().map(|events| events.clone()).unwrap_or_default()
1734    }
1735}
1736
1737impl Session for AgentToolSession {
1738    fn id(&self) -> &str {
1739        &self.id
1740    }
1741
1742    fn app_name(&self) -> &str {
1743        &self.app_name
1744    }
1745
1746    fn user_id(&self) -> &str {
1747        &self.user_id
1748    }
1749
1750    fn state(&self) -> &dyn State {
1751        self
1752    }
1753
1754    fn conversation_history(&self) -> Vec<Content> {
1755        self.history.read().map(|history| history.clone()).unwrap_or_default()
1756    }
1757
1758    fn held_tool_calls(&self, agent_name: &str, branch: &str) -> Vec<adk_core::HeldToolCall> {
1759        self.events
1760            .read()
1761            .map(|events| adk_core::held_tool_calls(&events, agent_name, branch))
1762            .unwrap_or_default()
1763    }
1764
1765    fn workflow_resume_positions(
1766        &self,
1767        workflow: &str,
1768        branch: &str,
1769    ) -> Vec<adk_core::WorkflowPosition> {
1770        self.events
1771            .read()
1772            .map(|events| adk_core::workflow_resume_positions(&events, workflow, branch))
1773            .unwrap_or_default()
1774    }
1775}
1776
1777impl State for AgentToolSession {
1778    fn get(&self, key: &str) -> Option<Value> {
1779        self.state.read().ok()?.get(key).cloned()
1780    }
1781
1782    fn set(&mut self, key: String, value: Value) {
1783        if let Err(msg) = adk_core::validate_state_key(&key) {
1784            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1785            return;
1786        }
1787        if let Ok(mut state) = self.state.write() {
1788            state.insert(key, value);
1789        }
1790    }
1791
1792    fn all(&self) -> HashMap<String, Value> {
1793        self.state.read().ok().map(|s| s.clone()).unwrap_or_default()
1794    }
1795}
1796
1797#[cfg(test)]
1798mod tests {
1799    use super::*;
1800    use adk_core::{EventActions, MemoryEntry, StreamingMode};
1801    use std::sync::Mutex;
1802
1803    struct MockAgent {
1804        name: String,
1805        description: String,
1806    }
1807
1808    #[async_trait]
1809    impl Agent for MockAgent {
1810        fn name(&self) -> &str {
1811            &self.name
1812        }
1813
1814        fn description(&self) -> &str {
1815            &self.description
1816        }
1817
1818        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1819            &[]
1820        }
1821
1822        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
1823            use async_stream::stream;
1824
1825            let name = self.name.clone();
1826            let s = stream! {
1827                let mut event = Event::new("mock-inv");
1828                event.author = name;
1829                event.llm_response.content = Some(Content::new("model").with_text("Mock response"));
1830                yield Ok(event);
1831            };
1832
1833            Ok(Box::pin(s))
1834        }
1835    }
1836
1837    #[test]
1838    fn test_agent_tool_creation() {
1839        let agent = Arc::new(MockAgent {
1840            name: "test_agent".to_string(),
1841            description: "A test agent".to_string(),
1842        });
1843
1844        let tool = AgentTool::new(agent);
1845        assert_eq!(tool.name(), "test_agent");
1846        assert_eq!(tool.description(), "A test agent");
1847    }
1848
1849    #[test]
1850    fn test_agent_tool_config() {
1851        let agent =
1852            Arc::new(MockAgent { name: "test".to_string(), description: "test".to_string() });
1853
1854        let tool = AgentTool::new(agent)
1855            .skip_summarization(true)
1856            .forward_artifacts(false)
1857            .timeout(Duration::from_secs(30));
1858
1859        assert!(tool.config.skip_summarization);
1860        assert!(!tool.config.forward_artifacts);
1861        assert_eq!(tool.config.timeout, Some(Duration::from_secs(30)));
1862    }
1863
1864    #[test]
1865    fn test_parameters_schema() {
1866        let agent = Arc::new(MockAgent {
1867            name: "calculator".to_string(),
1868            description: "Performs calculations".to_string(),
1869        });
1870
1871        let tool = AgentTool::new(agent);
1872        let schema = tool.parameters_schema().unwrap();
1873
1874        assert_eq!(schema["type"], "object");
1875        assert!(schema["properties"]["request"].is_object());
1876    }
1877
1878    #[test]
1879    fn test_extract_request() {
1880        let agent =
1881            Arc::new(MockAgent { name: "test".to_string(), description: "test".to_string() });
1882
1883        let tool = AgentTool::new(agent);
1884
1885        // Test with request field
1886        let args = json!({"request": "solve 2+2"});
1887        assert_eq!(tool.extract_request(&args), "solve 2+2");
1888
1889        // Test with string value
1890        let args = json!("direct request");
1891        assert_eq!(tool.extract_request(&args), "direct request");
1892    }
1893
1894    #[test]
1895    fn test_extract_response() {
1896        let mut event = Event::new("inv-123");
1897        event.llm_response.content = Some(Content {
1898            role: "model".to_string(),
1899            parts: vec![
1900                Part::Text { text: "The answer ".to_string() },
1901                Part::Text { text: "is 4".to_string() },
1902            ],
1903        });
1904
1905        let events = vec![event];
1906        let response = AgentTool::extract_response(&events);
1907
1908        assert_eq!(response["response"], "The answer is 4");
1909    }
1910
1911    #[test]
1912    fn parent_history_projection_keeps_only_complete_tool_exchanges() {
1913        let history = vec![
1914            Content::new("user").with_text("first request"),
1915            Content {
1916                role: "model".to_string(),
1917                parts: vec![Part::FunctionCall {
1918                    name: "completed_tool".to_string(),
1919                    args: json!({}),
1920                    id: Some("call-complete".to_string()),
1921                    thought_signature: None,
1922                }],
1923            },
1924            Content::new("model").with_text("forwarded child progress"),
1925            Content {
1926                role: "function".to_string(),
1927                parts: vec![Part::FunctionResponse {
1928                    function_response: adk_core::FunctionResponseData::new(
1929                        "completed_tool",
1930                        json!({"ok": true}),
1931                    ),
1932                    id: Some("call-complete".to_string()),
1933                    annotations: None,
1934                }],
1935            },
1936            Content::new("model").with_text("completed result"),
1937            Content {
1938                role: "model".to_string(),
1939                parts: vec![Part::FunctionCall {
1940                    name: "delegated_agent".to_string(),
1941                    args: json!({"request": "current request"}),
1942                    id: Some("call-open".to_string()),
1943                    thought_signature: None,
1944                }],
1945            },
1946        ];
1947
1948        let projected = AgentTool::project_parent_history(history.clone(), None);
1949        assert_eq!(projected.len(), 4);
1950        assert_eq!(projected.last().expect("projected history").role, "model");
1951        assert!(projected.iter().all(|content| {
1952            content.parts.iter().all(
1953                |part| !matches!(part, Part::Text { text } if text == "forwarded child progress"),
1954            )
1955        }));
1956
1957        let bounded = AgentTool::project_parent_history(history, Some(2));
1958        assert_eq!(bounded.len(), 1);
1959        assert_eq!(bounded[0].parts, vec![Part::Text { text: "completed result".to_string() }]);
1960    }
1961
1962    struct TestSession {
1963        state: std::sync::RwLock<HashMap<String, Value>>,
1964        history: Vec<Content>,
1965    }
1966
1967    impl State for TestSession {
1968        fn get(&self, key: &str) -> Option<Value> {
1969            self.state.read().ok()?.get(key).cloned()
1970        }
1971
1972        fn set(&mut self, key: String, value: Value) {
1973            self.state.get_mut().expect("state lock").insert(key, value);
1974        }
1975
1976        fn all(&self) -> HashMap<String, Value> {
1977            self.state.read().expect("state lock").clone()
1978        }
1979    }
1980
1981    impl Session for TestSession {
1982        fn id(&self) -> &str {
1983            "parent-session"
1984        }
1985
1986        fn app_name(&self) -> &str {
1987            "parent-app"
1988        }
1989
1990        fn user_id(&self) -> &str {
1991            "parent-user"
1992        }
1993
1994        fn state(&self) -> &dyn State {
1995            self
1996        }
1997
1998        fn conversation_history(&self) -> Vec<Content> {
1999            self.history.clone()
2000        }
2001    }
2002
2003    struct TestMemory;
2004
2005    #[async_trait]
2006    impl Memory for TestMemory {
2007        async fn search(&self, _query: &str) -> Result<Vec<MemoryEntry>> {
2008            Ok(Vec::new())
2009        }
2010    }
2011
2012    struct TestToolContext {
2013        actions: Mutex<EventActions>,
2014        session: TestSession,
2015        memory: Arc<dyn Memory>,
2016        run_config: RunConfig,
2017        cancelled: bool,
2018        shared_state: Arc<adk_core::SharedState>,
2019        emitted_events: Mutex<Vec<Event>>,
2020        delegation_depth: u32,
2021        max_delegation_depth: Option<u32>,
2022        authenticated: bool,
2023    }
2024
2025    impl TestToolContext {
2026        fn new() -> Self {
2027            Self {
2028                actions: Mutex::new(EventActions::default()),
2029                session: TestSession {
2030                    state: std::sync::RwLock::new(HashMap::from([(
2031                        "parent-key".to_string(),
2032                        json!("parent-value"),
2033                    )])),
2034                    history: vec![Content::new("user").with_text("parent history")],
2035                },
2036                memory: Arc::new(TestMemory),
2037                run_config: RunConfig::default(),
2038                cancelled: false,
2039                shared_state: Arc::new(adk_core::SharedState::new()),
2040                emitted_events: Mutex::new(Vec::new()),
2041                delegation_depth: 0,
2042                max_delegation_depth: None,
2043                authenticated: false,
2044            }
2045        }
2046    }
2047
2048    #[async_trait]
2049    impl ReadonlyContext for TestToolContext {
2050        fn invocation_id(&self) -> &str {
2051            "parent-invocation"
2052        }
2053        fn agent_name(&self) -> &str {
2054            "parent-agent"
2055        }
2056        fn user_id(&self) -> &str {
2057            "parent-user"
2058        }
2059        fn app_name(&self) -> &str {
2060            "parent-app"
2061        }
2062        fn session_id(&self) -> &str {
2063            "parent-session"
2064        }
2065        fn branch(&self) -> &str {
2066            ""
2067        }
2068        fn user_content(&self) -> &Content {
2069            &self.session.history[0]
2070        }
2071        fn is_authenticated(&self) -> bool {
2072            self.authenticated
2073        }
2074    }
2075
2076    #[async_trait]
2077    impl CallbackContext for TestToolContext {
2078        fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
2079            None
2080        }
2081
2082        fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2083            Some(self.shared_state.clone())
2084        }
2085    }
2086
2087    #[async_trait]
2088    impl ToolContext for TestToolContext {
2089        fn function_call_id(&self) -> &str {
2090            "call-1"
2091        }
2092        fn actions(&self) -> EventActions {
2093            self.actions.lock().expect("actions lock").clone()
2094        }
2095        fn set_actions(&self, actions: EventActions) {
2096            *self.actions.lock().expect("actions lock") = actions;
2097        }
2098        async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>> {
2099            self.memory.search(query).await
2100        }
2101        fn memory(&self) -> Option<Arc<dyn Memory>> {
2102            Some(self.memory.clone())
2103        }
2104        fn session(&self) -> Option<&dyn Session> {
2105            Some(&self.session)
2106        }
2107        fn run_config(&self) -> Option<&RunConfig> {
2108            Some(&self.run_config)
2109        }
2110        fn is_cancelled(&self) -> bool {
2111            self.cancelled
2112        }
2113        fn request_metadata(&self) -> HashMap<String, Value> {
2114            HashMap::from([("request-id".to_string(), json!("req-1"))])
2115        }
2116        fn delegation_depth(&self) -> u32 {
2117            self.delegation_depth
2118        }
2119        fn max_delegation_depth(&self) -> Option<u32> {
2120            self.max_delegation_depth
2121        }
2122        async fn emit_event(&self, event: Event) {
2123            self.emitted_events.lock().expect("event lock").push(event);
2124        }
2125    }
2126
2127    struct ContextProbeAgent;
2128
2129    #[async_trait]
2130    impl Agent for ContextProbeAgent {
2131        fn name(&self) -> &str {
2132            "probe"
2133        }
2134
2135        fn description(&self) -> &str {
2136            "records delegated context behavior"
2137        }
2138
2139        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2140            &[]
2141        }
2142
2143        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2144            use async_stream::stream;
2145            let stream = stream! {
2146                assert_eq!(ctx.session_id(), ctx.session().id());
2147                assert_eq!(ctx.app_name(), ctx.session().app_name());
2148                assert_eq!(ctx.user_id(), ctx.session().user_id());
2149                assert_eq!(ctx.session().state().get("parent-key"), Some(json!("parent-value")));
2150                assert_eq!(ctx.session().conversation_history().len(), 1);
2151                assert!(ctx.memory().is_some());
2152                assert!(ctx.shared_state().is_some());
2153                assert!(!ctx.is_cancelled());
2154                assert_eq!(ctx.request_metadata().get("request-id"), Some(&json!("req-1")));
2155                assert_eq!(ctx.run_config().streaming_mode, StreamingMode::None);
2156                assert_eq!(ctx.delegation_depth(), 3);
2157                assert_eq!(ctx.max_delegation_depth(), Some(4));
2158
2159                let mut first = Event::new(ctx.invocation_id());
2160                first.author = "probe".to_string();
2161                first.actions.state_delta.insert("child-key".to_string(), json!(42));
2162                first.actions.artifact_delta.insert("report.txt".to_string(), 2);
2163                first.llm_response.content = Some(Content::new("model").with_text("first"));
2164                yield Ok(first);
2165
2166                assert_eq!(ctx.session().state().get("child-key"), Some(json!(42)));
2167                assert_eq!(ctx.session().conversation_history().len(), 2);
2168                let mut final_event = Event::new(ctx.invocation_id());
2169                final_event.author = "probe".to_string();
2170                final_event.llm_response.content = Some(Content::new("model").with_text("done"));
2171                yield Ok(final_event);
2172            };
2173            Ok(Box::pin(stream))
2174        }
2175    }
2176
2177    #[tokio::test]
2178    async fn forwards_snapshot_runtime_context_and_applies_child_events_immediately() {
2179        let mut parent = TestToolContext::new();
2180        parent.delegation_depth = 2;
2181        parent.max_delegation_depth = Some(4);
2182        let parent = Arc::new(parent);
2183        let tool = AgentTool::new(Arc::new(ContextProbeAgent))
2184            .session_snapshot(AgentToolSessionSnapshot::Parent)
2185            .forward_memory(true)
2186            .forward_events(true)
2187            .skip_summarization(true);
2188
2189        let response = tool.execute(parent.clone(), json!({"request": "inspect"})).await.unwrap();
2190
2191        assert_eq!(response["response"], "done");
2192        let actions = parent.actions();
2193        assert_eq!(actions.state_delta.get("child-key"), Some(&json!(42)));
2194        assert_eq!(actions.artifact_delta.get("report.txt"), Some(&2));
2195        assert!(actions.skip_summarization);
2196        assert_eq!(parent.session.state().get("child-key"), None);
2197        assert_eq!(parent.emitted_events.lock().expect("event lock").len(), 2);
2198    }
2199
2200    /// Records whether the delegate's context reports an authenticated identity.
2201    struct AuthenticationProbe {
2202        seen: Arc<Mutex<Option<bool>>>,
2203    }
2204
2205    #[async_trait]
2206    impl Agent for AuthenticationProbe {
2207        fn name(&self) -> &str {
2208            "auth_probe"
2209        }
2210
2211        fn description(&self) -> &str {
2212            "records whether its caller was authenticated"
2213        }
2214
2215        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2216            &[]
2217        }
2218
2219        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2220            *self.seen.lock().expect("seen lock") = Some(ctx.is_authenticated());
2221            let mut event = Event::new(ctx.invocation_id());
2222            event.author = "auth_probe".to_string();
2223            event.llm_response.content = Some(Content::new("model").with_text("done"));
2224            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
2225        }
2226    }
2227
2228    #[tokio::test]
2229    async fn a_delegate_sees_whether_its_caller_was_authenticated() {
2230        for authenticated in [true, false] {
2231            let seen = Arc::new(Mutex::new(None));
2232            let mut parent = TestToolContext::new();
2233            parent.authenticated = authenticated;
2234            let tool = AgentTool::new(Arc::new(AuthenticationProbe { seen: seen.clone() }));
2235            tool.execute(Arc::new(parent), json!({"request": "go"})).await.unwrap();
2236            assert_eq!(*seen.lock().expect("seen lock"), Some(authenticated));
2237        }
2238    }
2239
2240    struct WritePolicyAgent;
2241
2242    #[async_trait]
2243    impl Agent for WritePolicyAgent {
2244        fn name(&self) -> &str {
2245            "write_policy"
2246        }
2247
2248        fn description(&self) -> &str {
2249            "emits state and artifact writes"
2250        }
2251
2252        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2253            &[]
2254        }
2255
2256        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2257            let mut event = Event::new(ctx.invocation_id());
2258            event.actions.state_delta.insert("child-key".to_string(), json!(42));
2259            event.actions.artifact_delta.insert("report.txt".to_string(), 2);
2260            event.llm_response.content = Some(Content::new("model").with_text("done"));
2261            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
2262        }
2263    }
2264
2265    #[tokio::test]
2266    async fn enforces_delegated_state_and_artifact_write_allowlists() {
2267        let state_tool = AgentTool::new(Arc::new(WritePolicyAgent))
2268            .session_snapshot(AgentToolSessionSnapshot::Parent)
2269            .output_state_keys(["allowed-key"])
2270            .propagate_failures(true);
2271        let error = state_tool
2272            .execute(Arc::new(TestToolContext::new()), json!({"request": "inspect"}))
2273            .await
2274            .unwrap_err();
2275        assert!(error.to_string().contains("unauthorized state write to 'child-key'"));
2276
2277        let artifact_tool = AgentTool::new(Arc::new(WritePolicyAgent))
2278            .session_snapshot(AgentToolSessionSnapshot::Parent)
2279            .output_state_keys(["child-key"])
2280            .artifact_prefixes(["team/"])
2281            .propagate_failures(true);
2282        let error = artifact_tool
2283            .execute(Arc::new(TestToolContext::new()), json!({"request": "inspect"}))
2284            .await
2285            .unwrap_err();
2286        assert!(error.to_string().contains("unauthorized artifact write to 'report.txt'"));
2287    }
2288
2289    struct ConflictingStateAgent {
2290        parent: Arc<TestToolContext>,
2291    }
2292
2293    #[async_trait]
2294    impl Agent for ConflictingStateAgent {
2295        fn name(&self) -> &str {
2296            "conflicting_state"
2297        }
2298
2299        fn description(&self) -> &str {
2300            "changes parent state while returning a child write"
2301        }
2302
2303        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2304            &[]
2305        }
2306
2307        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2308            self.parent
2309                .session
2310                .state
2311                .write()
2312                .expect("parent state lock")
2313                .insert("parent-key".to_string(), json!("concurrent-update"));
2314            let mut event = Event::new(ctx.invocation_id());
2315            event.actions.state_delta.insert("parent-key".to_string(), json!("child-update"));
2316            event.llm_response.content = Some(Content::new("model").with_text("done"));
2317            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
2318        }
2319    }
2320
2321    #[tokio::test]
2322    async fn rejects_delegated_state_merge_conflicts_transactionally() {
2323        let parent = Arc::new(TestToolContext::new());
2324        let tool = AgentTool::new(Arc::new(ConflictingStateAgent { parent: parent.clone() }))
2325            .session_snapshot(AgentToolSessionSnapshot::Parent)
2326            .state_merge_policy(AgentToolStateMergePolicy::RejectConflicts)
2327            .propagate_failures(true);
2328        let error = tool.execute(parent.clone(), json!({"request": "write"})).await.unwrap_err();
2329        assert!(error.to_string().contains("conflicts with a concurrent parent update"));
2330        assert!(parent.actions().state_delta.is_empty());
2331    }
2332
2333    #[tokio::test]
2334    async fn permits_explicit_framework_state_merge_exemptions() {
2335        let parent = Arc::new(TestToolContext::new());
2336        let tool = AgentTool::new(Arc::new(ConflictingStateAgent { parent: parent.clone() }))
2337            .session_snapshot(AgentToolSessionSnapshot::Parent)
2338            .state_merge_policy(AgentToolStateMergePolicy::RejectConflicts)
2339            .state_merge_exempt_keys(["parent-key"])
2340            .propagate_failures(true);
2341
2342        tool.execute(parent.clone(), json!({"request": "write"})).await.unwrap();
2343        assert_eq!(parent.actions().state_delta.get("parent-key"), Some(&json!("child-update")));
2344    }
2345
2346    struct TestArtifacts;
2347
2348    #[async_trait]
2349    impl Artifacts for TestArtifacts {
2350        async fn save(&self, _name: &str, _data: &Part) -> Result<i64> {
2351            Ok(1)
2352        }
2353
2354        async fn load(&self, _name: &str) -> Result<Part> {
2355            Ok(Part::Text { text: "artifact".to_string() })
2356        }
2357
2358        async fn list(&self) -> Result<Vec<String>> {
2359            Ok(Vec::new())
2360        }
2361    }
2362
2363    #[tokio::test]
2364    async fn rejects_artifact_writes_at_the_storage_boundary() {
2365        let artifacts = AgentToolArtifacts {
2366            inner: Arc::new(TestArtifacts),
2367            allowed_write_prefixes: Arc::new(vec!["research/".to_string()]),
2368        };
2369        let data = Part::Text { text: "data".to_string() };
2370        let error = artifacts.save("private/report.txt", &data).await.unwrap_err();
2371        assert_eq!(error.code, "artifact.agent_tool.write_denied");
2372        assert_eq!(artifacts.save("research/report.txt", &data).await.unwrap(), 1);
2373    }
2374
2375    struct FailingAgent;
2376
2377    #[async_trait]
2378    impl Agent for FailingAgent {
2379        fn name(&self) -> &str {
2380            "failing"
2381        }
2382        fn description(&self) -> &str {
2383            "always fails"
2384        }
2385        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2386            &[]
2387        }
2388        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2389            Err(adk_core::AdkError::agent("planned failure"))
2390        }
2391    }
2392
2393    #[tokio::test]
2394    async fn preserves_legacy_failure_object_and_supports_propagation() {
2395        let legacy = AgentTool::new(Arc::new(FailingAgent));
2396        let value = legacy
2397            .execute(Arc::new(TestToolContext::new()), json!({"request": "fail"}))
2398            .await
2399            .unwrap();
2400        assert_eq!(
2401            value,
2402            json!({
2403                "error": format!(
2404                    "agent execution failed: {}",
2405                    adk_core::AdkError::agent("planned failure").redacted()
2406                ),
2407                "agent": "failing",
2408            })
2409        );
2410
2411        let exposed = AgentTool::new(Arc::new(FailingAgent)).expose_error_messages(true);
2412        let value = exposed
2413            .execute(Arc::new(TestToolContext::new()), json!({"request": "fail"}))
2414            .await
2415            .unwrap();
2416        assert!(value["error"].as_str().unwrap().contains("planned failure"));
2417
2418        let strict = AgentTool::new(Arc::new(FailingAgent)).propagate_failures(true);
2419        let error = strict
2420            .execute(Arc::new(TestToolContext::new()), json!({"request": "fail"}))
2421            .await
2422            .unwrap_err();
2423        assert!(error.to_string().contains("planned failure"));
2424    }
2425
2426    #[tokio::test]
2427    async fn enforces_inherited_and_tool_specific_delegation_depth() {
2428        let mut inherited_ctx = TestToolContext::new();
2429        inherited_ctx.delegation_depth = 2;
2430        inherited_ctx.max_delegation_depth = Some(2);
2431        let tool = AgentTool::new(Arc::new(MockAgent {
2432            name: "child".to_string(),
2433            description: "child".to_string(),
2434        }))
2435        .propagate_failures(true);
2436        let error = tool
2437            .execute(Arc::new(inherited_ctx), json!({"request": "too deep"}))
2438            .await
2439            .unwrap_err();
2440        assert!(error.to_string().contains("depth 3"));
2441
2442        let local_limit = AgentTool::new(Arc::new(MockAgent {
2443            name: "child".to_string(),
2444            description: "child".to_string(),
2445        }))
2446        .max_delegation_depth(0)
2447        .propagate_failures(true);
2448        assert!(
2449            local_limit
2450                .execute(Arc::new(TestToolContext::new()), json!({"request": "too deep"}))
2451                .await
2452                .is_err()
2453        );
2454    }
2455
2456    struct HandoffAgent;
2457
2458    #[async_trait]
2459    impl Agent for HandoffAgent {
2460        fn name(&self) -> &str {
2461            "handoff"
2462        }
2463        fn description(&self) -> &str {
2464            "requests a handoff"
2465        }
2466        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2467            &[]
2468        }
2469        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2470            let mut event = Event::new(ctx.invocation_id());
2471            event.actions.transfer_to_agent = Some("other".to_string());
2472            Ok(Box::pin(futures::stream::iter([Ok(event)])))
2473        }
2474    }
2475
2476    #[tokio::test]
2477    async fn strict_mode_rejects_unconsumed_child_handoff() {
2478        let tool = AgentTool::new(Arc::new(HandoffAgent))
2479            .reject_child_handoffs(true)
2480            .propagate_failures(true);
2481        let error = tool
2482            .execute(Arc::new(TestToolContext::new()), json!({"request": "handoff"}))
2483            .await
2484            .unwrap_err();
2485        assert!(error.to_string().contains("cannot execute child handoffs"));
2486    }
2487
2488    #[tokio::test]
2489    async fn executes_registered_child_handoff_and_returns_final_result() {
2490        let target = Arc::new(MockAgent {
2491            name: "other".to_string(),
2492            description: "handoff target".to_string(),
2493        }) as Arc<dyn Agent>;
2494        let tool = AgentTool::new(Arc::new(HandoffAgent))
2495            .execute_child_handoffs([target])
2496            .forward_events(true)
2497            .propagate_failures(true);
2498        let parent = Arc::new(TestToolContext::new());
2499        let response = tool.execute(parent.clone(), json!({"request": "handoff"})).await.unwrap();
2500        assert_eq!(response["response"], "Mock response");
2501        let forwarded = parent.emitted_events.lock().expect("event lock");
2502        assert_eq!(forwarded.len(), 2);
2503        assert!(forwarded[0].actions.transfer_to_agent.is_none());
2504        assert_eq!(forwarded[1].author, "other");
2505    }
2506
2507    #[tokio::test]
2508    async fn cancellation_is_observed_before_child_execution() {
2509        let mut ctx = TestToolContext::new();
2510        ctx.cancelled = true;
2511        let tool = AgentTool::new(Arc::new(MockAgent {
2512            name: "child".to_string(),
2513            description: "child".to_string(),
2514        }))
2515        .propagate_failures(true);
2516        let error = tool.execute(Arc::new(ctx), json!({"request": "go"})).await.unwrap_err();
2517        assert!(error.to_string().contains("cancelled"));
2518    }
2519
2520    struct IsolatedProbeAgent;
2521
2522    #[async_trait]
2523    impl Agent for IsolatedProbeAgent {
2524        fn name(&self) -> &str {
2525            "isolated"
2526        }
2527        fn description(&self) -> &str {
2528            "checks legacy isolation defaults"
2529        }
2530        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2531            &[]
2532        }
2533        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2534            assert_eq!(ctx.session_id(), ctx.session().id());
2535            assert_eq!(ctx.app_name(), ctx.session().app_name());
2536            assert_eq!(ctx.user_id(), ctx.session().user_id());
2537            assert!(ctx.session().state().all().is_empty());
2538            assert!(ctx.session().conversation_history().is_empty());
2539            assert!(ctx.memory().is_none());
2540            let mut event = Event::new(ctx.invocation_id());
2541            event.llm_response.content = Some(Content::new("model").with_text("isolated"));
2542            Ok(Box::pin(futures::stream::iter([Ok(event)])))
2543        }
2544    }
2545
2546    #[tokio::test]
2547    async fn default_keeps_each_child_session_isolated() {
2548        let tool = AgentTool::new(Arc::new(IsolatedProbeAgent));
2549        let parent = Arc::new(TestToolContext::new());
2550        let response = tool.execute(parent.clone(), json!({"request": "inspect"})).await.unwrap();
2551        assert_eq!(response["response"], "isolated");
2552        assert!(parent.emitted_events.lock().expect("event lock").is_empty());
2553    }
2554
2555    struct ProjectionProbeAgent;
2556
2557    #[async_trait]
2558    impl Agent for ProjectionProbeAgent {
2559        fn name(&self) -> &str {
2560            "projection"
2561        }
2562
2563        fn description(&self) -> &str {
2564            "checks explicit history and state projections"
2565        }
2566
2567        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2568            &[]
2569        }
2570
2571        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2572            assert!(ctx.session().conversation_history().is_empty());
2573            assert!(ctx.session().state().all().is_empty());
2574            let mut event = Event::new(ctx.invocation_id());
2575            event.llm_response.content = Some(Content::new("model").with_text("projected"));
2576            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
2577        }
2578    }
2579
2580    #[tokio::test]
2581    async fn applies_exact_history_and_state_projection() {
2582        let tool = AgentTool::new(Arc::new(ProjectionProbeAgent))
2583            .session_snapshot(AgentToolSessionSnapshot::Parent)
2584            .history_max_events(0)
2585            .state_keys(["not-present"])
2586            .propagate_failures(true);
2587        let response = tool
2588            .execute(Arc::new(TestToolContext::new()), json!({"request": "inspect"}))
2589            .await
2590            .unwrap();
2591        assert_eq!(response["response"], "projected");
2592    }
2593
2594    struct StateWithoutHistoryProbe;
2595
2596    #[async_trait]
2597    impl Agent for StateWithoutHistoryProbe {
2598        fn name(&self) -> &str {
2599            "state_without_history"
2600        }
2601
2602        fn description(&self) -> &str {
2603            "checks independent state and history projections"
2604        }
2605
2606        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2607            &[]
2608        }
2609
2610        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2611            assert!(ctx.session().conversation_history().is_empty());
2612            assert_eq!(ctx.session().state().get("parent-key"), Some(json!("parent-value")));
2613            let mut event = Event::new(ctx.invocation_id());
2614            event.llm_response.content = Some(Content::new("model").with_text("independent"));
2615            Ok(Box::pin(futures::stream::once(async { Ok(event) })))
2616        }
2617    }
2618
2619    #[tokio::test]
2620    async fn projects_state_independently_from_history() {
2621        let tool = AgentTool::new(Arc::new(StateWithoutHistoryProbe))
2622            .session_snapshot(AgentToolSessionSnapshot::Parent)
2623            .history_max_events(0)
2624            .state_keys(["parent-key"])
2625            .propagate_failures(true);
2626        let response = tool
2627            .execute(Arc::new(TestToolContext::new()), json!({"request": "inspect"}))
2628            .await
2629            .unwrap();
2630        assert_eq!(response["response"], "independent");
2631    }
2632
2633    struct PendingAgent;
2634
2635    #[async_trait]
2636    impl Agent for PendingAgent {
2637        fn name(&self) -> &str {
2638            "pending"
2639        }
2640        fn description(&self) -> &str {
2641            "never completes"
2642        }
2643        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2644            &[]
2645        }
2646        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2647            Ok(Box::pin(futures::stream::pending()))
2648        }
2649    }
2650
2651    #[tokio::test]
2652    async fn a_timeout_is_a_timeout_error_in_every_failure_mode() {
2653        for propagate in [false, true] {
2654            let tool = AgentTool::new(Arc::new(PendingAgent))
2655                .timeout(Duration::from_millis(1))
2656                .propagate_failures(propagate);
2657            let error = tool
2658                .execute(Arc::new(TestToolContext::new()), json!({"request": "wait"}))
2659                .await
2660                .unwrap_err();
2661            assert_eq!(error.category, adk_core::ErrorCategory::Timeout);
2662            assert_eq!(error.code, "tool.agent.timeout");
2663            assert!(error.message.contains("timed out after 1ms"), "{}", error.message);
2664        }
2665    }
2666
2667    struct RateLimitedAgent;
2668
2669    #[async_trait]
2670    impl Agent for RateLimitedAgent {
2671        fn name(&self) -> &str {
2672            "rate_limited"
2673        }
2674        fn description(&self) -> &str {
2675            "fails with a rate limit"
2676        }
2677        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2678            &[]
2679        }
2680        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2681            Err(adk_core::AdkError::new(
2682                adk_core::ErrorComponent::Model,
2683                adk_core::ErrorCategory::RateLimited,
2684                "model.test.rate_limited",
2685                "slow down",
2686            ))
2687        }
2688    }
2689
2690    #[tokio::test]
2691    async fn propagated_failures_keep_the_delegates_category_and_code() {
2692        let error = AgentTool::new(Arc::new(RateLimitedAgent))
2693            .propagate_failures(true)
2694            .execute(Arc::new(TestToolContext::new()), json!({"request": "go"}))
2695            .await
2696            .unwrap_err();
2697        assert_eq!(error.category, adk_core::ErrorCategory::RateLimited);
2698        assert_eq!(error.code, "model.test.rate_limited");
2699        assert_eq!(error.message, "agent 'rate_limited' execution failed: slow down");
2700    }
2701
2702    fn function_response_event(responses: &[(&str, Value)], skip: bool) -> Event {
2703        let mut event = Event::new("inv");
2704        event.actions.skip_summarization = skip;
2705        event.llm_response.content = Some(Content {
2706            role: "function".to_string(),
2707            parts: responses
2708                .iter()
2709                .map(|(name, response)| Part::FunctionResponse {
2710                    function_response: adk_core::FunctionResponseData::new(*name, response.clone()),
2711                    id: Some(format!("{name}-id")),
2712                    annotations: None,
2713                })
2714                .collect(),
2715        });
2716        event
2717    }
2718
2719    #[test]
2720    fn the_answer_is_read_past_a_trailing_state_only_event() {
2721        let mut answer = Event::new("inv");
2722        answer.llm_response.content = Some(Content::new("model").with_text("Nairobi"));
2723        // The `output_key` write `LlmAgent` emits after its answer.
2724        let mut state = Event::new("inv");
2725        state.actions.state_delta.insert("capital".to_string(), json!("Nairobi"));
2726
2727        assert_eq!(
2728            AgentTool::extract_response(&[answer.clone(), state.clone()]),
2729            json!({ "response": "Nairobi" })
2730        );
2731
2732        let mut partial = answer;
2733        partial.llm_response.partial = true;
2734        assert_eq!(
2735            AgentTool::extract_response(&[partial, state]),
2736            json!({ "response": "Nairobi" })
2737        );
2738    }
2739
2740    #[test]
2741    fn code_execution_results_are_part_of_the_delegations_output() {
2742        let result = json!({"codeExecutionResult": {"outcome": "OUTCOME_OK", "output": "5117\n"}});
2743        let mut answer = Event::new("inv");
2744        answer.llm_response.content = Some(Content {
2745            role: "model".to_string(),
2746            parts: vec![
2747                Part::ServerToolCall {
2748                    server_tool_call: json!({"executableCode": {"language": "PYTHON", "code": "print(5117)"}}),
2749                },
2750                Part::ServerToolResponse { server_tool_response: result.clone() },
2751                Part::Text { text: "The sum is 5117.".to_string() },
2752            ],
2753        });
2754        let mut streamed = answer.clone();
2755        streamed.llm_response.partial = true;
2756
2757        assert_eq!(
2758            AgentTool::extract_response(&[streamed.clone(), answer]),
2759            json!({"response": "The sum is 5117.", "server_tool_responses": [result.clone()]})
2760        );
2761
2762        // Only the code ran; no final text followed.
2763        let mut code_only = Event::new("inv");
2764        code_only.llm_response.content = Some(Content {
2765            role: "model".to_string(),
2766            parts: vec![Part::ServerToolResponse { server_tool_response: result.clone() }],
2767        });
2768        assert_eq!(
2769            AgentTool::extract_response(&[code_only]),
2770            json!({"response": "", "server_tool_responses": [result]})
2771        );
2772    }
2773
2774    #[test]
2775    fn a_replay_only_copy_never_reaches_the_parent() {
2776        let mut answer = Event::new("inv");
2777        answer.llm_response.content = Some(Content {
2778            role: "model".to_string(),
2779            parts: vec![
2780                Part::ServerToolResponse {
2781                    server_tool_response: json!({
2782                        "type": "anthropic_message",
2783                        "adk_replay_only": true,
2784                        "content": [{"type": "thinking", "thinking": "private", "signature": "s"}],
2785                    }),
2786                },
2787                Part::Text { text: "Done.".to_string() },
2788            ],
2789        });
2790        assert_eq!(AgentTool::extract_response(&[answer]), json!({"response": "Done."}));
2791    }
2792
2793    #[test]
2794    fn a_delegate_that_ends_on_a_tool_result_hands_back_its_payload() {
2795        let single = function_response_event(&[("compute", json!({"answer": 42}))], true);
2796        assert_eq!(AgentTool::extract_response(&[single]), json!({"answer": 42}));
2797
2798        let several = function_response_event(
2799            &[("first", json!({"a": 1})), ("second", json!({"b": 2}))],
2800            true,
2801        );
2802        assert_eq!(
2803            AgentTool::extract_response(&[several]),
2804            json!({"responses": [
2805                {"name": "first", "response": {"a": 1}},
2806                {"name": "second", "response": {"b": 2}},
2807            ]})
2808        );
2809
2810        // A delegate ending on an escalating tool result is not a final response; its
2811        // result is still the delegation's output.
2812        let escalated = function_response_event(&[("stop", json!({"done": true}))], false);
2813        assert_eq!(AgentTool::extract_response(&[escalated]), json!({"done": true}));
2814
2815        let mut empty_text = Event::new("inv");
2816        empty_text.llm_response.content = Some(Content::new("model").with_text(""));
2817        assert_eq!(AgentTool::extract_response(&[empty_text]), json!({"response": ""}));
2818        assert_eq!(AgentTool::extract_response(&[]), json!({"response": "No response from agent"}));
2819    }
2820
2821    struct RunConfigProbe {
2822        seen: Arc<Mutex<Option<(RunConfig, String)>>>,
2823    }
2824
2825    #[async_trait]
2826    impl Agent for RunConfigProbe {
2827        fn name(&self) -> &str {
2828            "probe"
2829        }
2830        fn description(&self) -> &str {
2831            "records the delegated run config"
2832        }
2833        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2834            &[]
2835        }
2836        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2837            *self.seen.lock().unwrap() =
2838                Some((ctx.run_config().clone(), ctx.session_id().to_string()));
2839            let mut event = Event::new(ctx.invocation_id());
2840            event.llm_response.content = Some(Content::new("model").with_text("done"));
2841            Ok(Box::pin(futures::stream::iter([Ok(event)])))
2842        }
2843    }
2844
2845    #[tokio::test]
2846    async fn a_delegate_gets_the_shared_run_config_without_its_callers_agent_scoped_fields() {
2847        let tracker = Arc::new(adk_core::BudgetTracker::new(adk_core::RunBudget::default()));
2848        let mut parent = TestToolContext::new();
2849        parent.run_config = RunConfig {
2850            transfer_targets: vec!["coordinator".to_string(), "peer".to_string()],
2851            parent_agent: Some("coordinator".to_string()),
2852            cached_content: Some("cachedContents/coordinator".to_string()),
2853            runtime_toolsets: vec![adk_core::RuntimeToolset::new(Arc::new(
2854                crate::BasicToolset::new("client", Vec::new()),
2855            ))],
2856            tool_confirmation_decisions: HashMap::from([(
2857                "call-1".to_string(),
2858                adk_core::ToolConfirmationDecision::Approve,
2859            )]),
2860            tool_confirmation_fingerprints: HashMap::from([(
2861                "call-1".to_string(),
2862                "fingerprint".to_string(),
2863            )]),
2864            tool_approvals: HashMap::from([(
2865                "fingerprint".to_string(),
2866                adk_core::ToolApproval::approve(),
2867            )]),
2868            budget_tracker: Some(tracker.clone()),
2869            durable_run_id: Some("run-1".to_string()),
2870            max_transfer_depth: Some(3),
2871            record_payloads: true,
2872            ..RunConfig::default()
2873        };
2874        let seen = Arc::new(Mutex::new(None));
2875        AgentTool::new(Arc::new(RunConfigProbe { seen: seen.clone() }))
2876            .execute(Arc::new(parent), json!({"request": "inspect"}))
2877            .await
2878            .unwrap();
2879
2880        let (config, session_id) = seen.lock().unwrap().take().expect("the delegate ran");
2881        assert!(config.transfer_targets.is_empty());
2882        assert_eq!(config.parent_agent, None);
2883        assert_eq!(config.cached_content, None);
2884        assert!(config.runtime_toolsets.is_empty());
2885        assert!(config.tool_confirmation_decisions.is_empty());
2886        assert!(config.tool_confirmation_fingerprints.is_empty());
2887        assert_eq!(config.streaming_mode, StreamingMode::None);
2888        assert!(config.tool_approvals.contains_key("fingerprint"));
2889        assert!(config.budget_tracker.is_some_and(|shared| Arc::ptr_eq(&shared, &tracker)));
2890        assert_eq!(config.durable_run_id.as_deref(), Some("run-1"));
2891        assert_eq!(config.max_transfer_depth, Some(3));
2892        assert!(config.record_payloads);
2893        // Approvals, policy requests and audit records of the delegate belong to the
2894        // caller's session.
2895        assert_eq!(session_id, "parent-session");
2896    }
2897
2898    /// What a resumed delegate saw: its held calls, its user turn, and its run config.
2899    type Resumed = (Vec<adk_core::HeldToolCall>, Content, RunConfig);
2900
2901    /// Holds a call on its first run; on the run that resumes, reports what it resumed.
2902    struct HoldingAgent {
2903        resumed: Arc<Mutex<Option<Resumed>>>,
2904    }
2905
2906    #[async_trait]
2907    impl Agent for HoldingAgent {
2908        fn name(&self) -> &str {
2909            "holder"
2910        }
2911        fn description(&self) -> &str {
2912            "holds a call for confirmation"
2913        }
2914        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2915            &[]
2916        }
2917        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
2918            let held = ctx.session().held_tool_calls("holder", ctx.branch());
2919            if !held.is_empty() {
2920                *self.resumed.lock().unwrap() =
2921                    Some((held, ctx.user_content().clone(), ctx.run_config().clone()));
2922                // The resumed call is answered, as `LlmAgent` answers it.
2923                let mut answered = Event::new(ctx.invocation_id());
2924                answered.author = "holder".to_string();
2925                answered.llm_response.content = Some(Content {
2926                    role: "function".to_string(),
2927                    parts: vec![Part::FunctionResponse {
2928                        function_response: adk_core::FunctionResponseData::new(
2929                            "delete_file",
2930                            json!({"deleted": true}),
2931                        ),
2932                        id: Some("inner-1".to_string()),
2933                        annotations: None,
2934                    }],
2935                });
2936                let mut done = Event::new(ctx.invocation_id());
2937                done.author = "holder".to_string();
2938                done.llm_response.content = Some(Content::new("model").with_text("deleted"));
2939                return Ok(Box::pin(futures::stream::iter([Ok(answered), Ok(done)])));
2940            }
2941            let args = json!({"path": "a.txt"});
2942            let mut issued = Event::new(ctx.invocation_id());
2943            issued.author = "holder".to_string();
2944            issued.llm_response.content = Some(Content {
2945                role: "model".to_string(),
2946                parts: vec![Part::FunctionCall {
2947                    name: "delete_file".to_string(),
2948                    args: args.clone(),
2949                    id: Some("inner-1".to_string()),
2950                    thought_signature: None,
2951                }],
2952            });
2953            let mut pending = Event::new(ctx.invocation_id());
2954            pending.author = "holder".to_string();
2955            pending.llm_response.content = Some(Content {
2956                role: "function".to_string(),
2957                parts: vec![Part::FunctionResponse {
2958                    function_response: adk_core::FunctionResponseData::new(
2959                        "delete_file",
2960                        adk_core::confirmation_pending_response("held"),
2961                    ),
2962                    id: Some("inner-1".to_string()),
2963                    annotations: None,
2964                }],
2965            });
2966            let mut hold = Event::new(ctx.invocation_id());
2967            hold.author = "holder".to_string();
2968            hold.llm_response.content =
2969                Some(Content::new("model").with_text("confirmation required"));
2970            hold.actions.tool_confirmation = Some(
2971                ToolConfirmationRequest::new("delete_file", args)
2972                    .with_function_call_id("inner-1")
2973                    .with_acting_context(ctx.acting_context()),
2974            );
2975            Ok(Box::pin(futures::stream::iter([Ok(issued), Ok(pending), Ok(hold)])))
2976        }
2977    }
2978
2979    #[tokio::test]
2980    async fn a_delegates_hold_holds_the_call_and_resumes_where_it_stopped() {
2981        let resumed = Arc::new(Mutex::new(None));
2982        let tool = AgentTool::new(Arc::new(HoldingAgent { resumed: resumed.clone() }))
2983            .forward_events(true)
2984            .skip_summarization(true);
2985        let args = json!({"request": "delete a.txt"});
2986
2987        let first = Arc::new(TestToolContext::new());
2988        let response = tool.execute(first.clone(), args.clone()).await.unwrap();
2989        assert!(adk_core::is_confirmation_pending(&response), "{response}");
2990        let actions = first.actions();
2991        assert!(!actions.skip_summarization, "a held delegation does not end the turn");
2992        let surfaced = actions.tool_confirmation.expect("the call is held with the delegate");
2993        assert_eq!(surfaced.tool_name, "delete_file");
2994        assert_eq!(surfaced.args, json!({"path": "a.txt"}));
2995        assert_eq!(surfaced.function_call_id.as_deref(), Some("call-1"));
2996        assert_eq!(
2997            surfaced.acting.as_ref().map(|acting| acting.agent.id.as_str()),
2998            Some("urn:adk:agent:parent-app/holder")
2999        );
3000        let (key, record) = actions
3001            .state_delta
3002            .iter()
3003            .find(|(key, _)| key.starts_with(HELD_DELEGATION_STATE_PREFIX))
3004            .expect("the held delegation is recorded");
3005        assert!(
3006            first
3007                .emitted_events
3008                .lock()
3009                .unwrap()
3010                .iter()
3011                .all(|event| event.actions.tool_confirmation.is_none()),
3012            "the delegate's own request is not forwarded"
3013        );
3014
3015        // The next run carries the record in session state and a decision for the call.
3016        let mut second = TestToolContext::new();
3017        second.session.state.write().unwrap().insert(key.clone(), record.clone());
3018        second.run_config.tool_confirmation_decisions =
3019            HashMap::from([("call-1".to_string(), adk_core::ToolConfirmationDecision::Approve)]);
3020        second.run_config.tool_confirmation_fingerprints =
3021            HashMap::from([("call-1".to_string(), surfaced.fingerprint())]);
3022        let second = Arc::new(second);
3023        let response = tool.execute(second.clone(), args).await.unwrap();
3024        assert_eq!(response, json!({"response": "deleted"}));
3025        assert_eq!(second.actions().state_delta.get(key), Some(&Value::Null));
3026        assert!(second.actions().skip_summarization);
3027
3028        let (held, user_content, config) = resumed.lock().unwrap().take().expect("it resumed");
3029        assert_eq!(held.len(), 1);
3030        assert_eq!(held[0].id.as_deref(), Some("inner-1"));
3031        assert_eq!(held[0].name, "delete_file");
3032        assert!(user_content.parts.is_empty(), "a resuming run carries no new input");
3033        // The caller's decision for its own call reaches the call it was surfaced for.
3034        assert_eq!(
3035            config.tool_confirmation_decisions.get("inner-1"),
3036            Some(&adk_core::ToolConfirmationDecision::Approve)
3037        );
3038        assert_eq!(
3039            config.tool_confirmation_fingerprints.get("inner-1"),
3040            Some(&surfaced.fingerprint())
3041        );
3042    }
3043
3044    /// Holds two calls in one turn, as a model that issues both at once does.
3045    struct DoubleHoldingAgent;
3046
3047    #[async_trait]
3048    impl Agent for DoubleHoldingAgent {
3049        fn name(&self) -> &str {
3050            "holder"
3051        }
3052        fn description(&self) -> &str {
3053            "holds two calls for confirmation"
3054        }
3055        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
3056            &[]
3057        }
3058        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
3059            let event = |content: Content| {
3060                let mut event = Event::new(ctx.invocation_id());
3061                event.author = "holder".to_string();
3062                event.llm_response.content = Some(content);
3063                event
3064            };
3065            let files = [("inner-1", "a.txt"), ("inner-2", "b.txt")];
3066            let issued = event(Content {
3067                role: "model".to_string(),
3068                parts: files
3069                    .iter()
3070                    .map(|(id, file)| Part::FunctionCall {
3071                        name: "delete_file".to_string(),
3072                        args: json!({ "path": file }),
3073                        id: Some((*id).to_string()),
3074                        thought_signature: None,
3075                    })
3076                    .collect(),
3077            });
3078            let pending = event(Content {
3079                role: "function".to_string(),
3080                parts: files
3081                    .iter()
3082                    .map(|(id, _)| Part::FunctionResponse {
3083                        function_response: adk_core::FunctionResponseData::new(
3084                            "delete_file",
3085                            adk_core::confirmation_pending_response("held"),
3086                        ),
3087                        id: Some((*id).to_string()),
3088                        annotations: None,
3089                    })
3090                    .collect(),
3091            });
3092            let mut events = vec![Ok(issued), Ok(pending)];
3093            for (id, file) in files {
3094                let mut hold = event(Content::new("model").with_text("confirmation required"));
3095                hold.actions.tool_confirmation = Some(
3096                    ToolConfirmationRequest::new("delete_file", json!({ "path": file }))
3097                        .with_function_call_id(id)
3098                        .with_acting_context(ctx.acting_context()),
3099                );
3100                events.push(Ok(hold));
3101            }
3102            Ok(Box::pin(futures::stream::iter(events)))
3103        }
3104    }
3105
3106    #[tokio::test]
3107    async fn every_call_a_delegate_holds_is_surfaced_under_the_callers_call() {
3108        let tool = AgentTool::new(Arc::new(DoubleHoldingAgent));
3109        let ctx = Arc::new(TestToolContext::new());
3110
3111        let response = tool.execute(ctx.clone(), json!({"request": "delete both"})).await.unwrap();
3112
3113        assert!(adk_core::is_confirmation_pending(&response), "{response}");
3114        let emitted = ctx.emitted_events.lock().unwrap().clone();
3115        assert_eq!(emitted.len(), 1, "the earlier request is surfaced before the last");
3116        assert_eq!(emitted[0].author, "parent-agent");
3117        assert_eq!(emitted[0].invocation_id, "parent-invocation");
3118        let mut surfaced: Vec<ToolConfirmationRequest> =
3119            emitted.iter().filter_map(|event| event.actions.tool_confirmation.clone()).collect();
3120        surfaced.extend(ctx.actions().tool_confirmation);
3121        let shown: Vec<_> = surfaced
3122            .iter()
3123            .map(|request| (request.args.clone(), request.function_call_id.as_deref()))
3124            .collect();
3125        assert_eq!(
3126            shown,
3127            vec![
3128                (json!({"path": "a.txt"}), Some("call-1")),
3129                (json!({"path": "b.txt"}), Some("call-1")),
3130            ]
3131        );
3132        let record = ctx
3133            .actions()
3134            .state_delta
3135            .into_iter()
3136            .find(|(key, _)| key.starts_with(HELD_DELEGATION_STATE_PREFIX))
3137            .map(|(_, record)| serde_json::from_value::<HeldDelegation>(record).unwrap())
3138            .expect("the held delegation is recorded");
3139        assert_eq!(record.request.function_call_id.as_deref(), Some("inner-1"));
3140        assert_eq!(record.more.len(), 1);
3141        assert_eq!(record.more[0].function_call_id.as_deref(), Some("inner-2"));
3142    }
3143
3144    #[test]
3145    fn a_record_without_further_requests_still_reads() {
3146        let request = ToolConfirmationRequest::new("delete_file", json!({"path": "a.txt"}))
3147            .with_function_call_id("inner-1");
3148        let written = json!({
3149            "call": "fingerprint",
3150            "agent": "holder",
3151            "request": request,
3152            "state": {},
3153            "history": [],
3154            "userContent": Content::new("user").with_text("delete a.txt"),
3155            "events": [],
3156        });
3157        let record: HeldDelegation = serde_json::from_value(written).unwrap();
3158        assert!(record.more.is_empty());
3159    }
3160}