Skip to main content

adk_agent/
llm_agent.rs

1use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
2use adk_core::{
3    AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull, Agent,
4    BeforeAgentCallback, BeforeModelCallback, BeforeModelResult, BeforeToolCallback,
5    CallbackContext, Content, Event, EventActions, FunctionResponseData, GlobalInstructionProvider,
6    GovernedCall, InstructionProvider, InvocationContext, Llm, LlmRequest, LlmResponse,
7    MemoryEntry, OnToolErrorCallback, Part, ReadonlyContext, Result, RetryBudget, Tool,
8    ToolAuthorization, ToolCallbackContext, ToolConfirmationPolicy, ToolConfirmationRequest,
9    ToolContext, ToolEffect, ToolExecutionStrategy, ToolGate, ToolOutcome, ToolResultStatus,
10    Toolset, authorize_tool_call,
11};
12use async_stream::stream;
13use async_trait::async_trait;
14use std::{
15    collections::{HashMap, HashSet},
16    sync::{Arc, Mutex},
17};
18use tracing::Instrument;
19
20#[cfg(feature = "enhanced-plugins")]
21use adk_plugin::{
22    BeforeModelCallResult, BeforeToolCallResult, EnhancedPlugin, EnhancedPluginManager,
23};
24
25#[cfg(feature = "skills")]
26use crate::skill_shim::load_skill_index;
27use crate::{
28    grounding::answer_citations,
29    guardrails::{
30        Grounding, GuardrailScreen, GuardrailSet, Phase, Screened, ToolGuardrailSet, Warnings,
31        enforce_guardrails, screen_model_output, screen_tool_result,
32    },
33    invocation_hooks::HookCallbacks,
34    skill_shim::{SelectionPolicy, SkillIndex, apply_skill_injection},
35    tool_call_markup::normalize_option_content,
36    workflow::with_user_content_override,
37};
38
39/// Default maximum number of LLM round-trips (iterations) before the agent stops.
40pub const DEFAULT_MAX_ITERATIONS: u32 = 100;
41
42/// Default tool execution timeout (5 minutes).
43pub const DEFAULT_TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
44
45/// Recorded in place of a request, response, or tool payload when
46/// [`RunConfig::record_payloads`](adk_core::RunConfig::record_payloads) is off.
47const PAYLOAD_OMITTED: &str = "[omitted: set RunConfig::record_payloads to record payloads]";
48
49/// Renders a payload for a span field or debug log.
50///
51/// Payloads carry user text and tool data, so nothing of them is recorded unless
52/// `record_payloads` is set: in full with the `record-payloads` feature, otherwise
53/// truncated to `max_bytes`.
54fn trace_json_payload<T: serde::Serialize>(
55    value: &T,
56    record_payloads: bool,
57    max_bytes: usize,
58) -> String {
59    if !record_payloads {
60        return PAYLOAD_OMITTED.to_string();
61    }
62    let json = serde_json::to_string(value).unwrap_or_default();
63    if cfg!(feature = "record-payloads") {
64        return json;
65    }
66
67    let max_bytes = max_bytes.max(32);
68    if json.len() <= max_bytes {
69        return json;
70    }
71
72    let mut end = max_bytes;
73    while !json.is_char_boundary(end) {
74        end -= 1;
75    }
76    format!("{}...[truncated {} bytes]", &json[..end], json.len() - end)
77}
78
79/// The text logged for an error message or a denial reason: the text when the run records
80/// payloads, else a placeholder.
81///
82/// Provider errors can echo prompts, and tool errors and guardrail reasons can quote
83/// arguments and credentials, so their text follows the same rule as payloads. Log the content-free part
84/// with [`AdkError::diagnostics`](adk_core::AdkError::diagnostics) beside it.
85fn traced_message(run_config: &adk_core::RunConfig, message: &str) -> String {
86    trace_json_payload(&message, run_config.record_payloads, run_config.trace_payload_max_bytes)
87}
88
89/// The audit action of a tool call a hook, callback, or plugin answered before the governed
90/// path saw it (spec 3.1 §10, F1).
91const SHORT_CIRCUIT_ACTION: &str = "tool.short_circuit";
92/// `answeredBy` of an enhanced plugin's `ShortCircuit`.
93#[cfg(feature = "enhanced-plugins")]
94const SHORT_CIRCUIT_BY_ENHANCED_PLUGIN: &str = "enhanced_plugin";
95/// `answeredBy` of a run-wide `InvocationHooks::before_tool` answer.
96const SHORT_CIRCUIT_BY_INVOCATION_HOOK: &str = "invocation_hook";
97/// `answeredBy` of the agent's own `BeforeToolCallback` answer.
98const SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK: &str = "before_tool_callback";
99
100#[derive(Debug, Clone)]
101struct PendingToolCall {
102    index: usize,
103    name: String,
104    args: serde_json::Value,
105    id: Option<String>,
106    function_call_id: String,
107    /// The held request this call resumes, when it is the call that request describes.
108    resumes: Option<ToolConfirmationRequest>,
109}
110
111fn build_generation_config(
112    base: Option<&adk_core::GenerateContentConfig>,
113    output_schema: Option<&serde_json::Value>,
114    cached_content: Option<&str>,
115) -> Option<adk_core::GenerateContentConfig> {
116    let mut config = base.cloned().unwrap_or_default();
117    if let Some(schema) = output_schema {
118        config.response_schema = Some(schema.clone());
119    }
120    if config.cached_content.is_none()
121        && let Some(cached_content) = cached_content
122    {
123        config.cached_content = Some(cached_content.to_string());
124    }
125
126    if base.is_some() || output_schema.is_some() || cached_content.is_some() {
127        Some(config)
128    } else {
129        None
130    }
131}
132
133/// Appends streamed parts, joining a delta onto the part it continues.
134///
135/// Consecutive text deltas form one text part. A thinking delta joins the previous
136/// thinking part until that part is signed, since a signature closes its block.
137fn append_streamed_parts(parts: &mut Vec<Part>, incoming: Vec<Part>) {
138    for part in incoming {
139        match (parts.last_mut(), part) {
140            (Some(Part::Text { text }), Part::Text { text: delta }) => text.push_str(&delta),
141            (
142                Some(Part::Thinking { thinking, signature: signature @ None }),
143                Part::Thinking { thinking: delta, signature: delta_signature },
144            ) => {
145                thinking.push_str(&delta);
146                *signature = delta_signature;
147            }
148            (_, part) => parts.push(part),
149        }
150    }
151}
152
153fn collect_function_calls(content: &Content, invocation_id: &str) -> Vec<PendingToolCall> {
154    content
155        .parts
156        .iter()
157        .filter_map(|part| {
158            if let Part::FunctionCall { name, args, id, .. } = part {
159                Some((name, args, id))
160            } else {
161                None
162            }
163        })
164        .enumerate()
165        .map(|(index, (name, args, id))| PendingToolCall {
166            index,
167            name: name.clone(),
168            args: args.clone(),
169            id: id.clone(),
170            function_call_id: id
171                .clone()
172                .unwrap_or_else(|| format!("{invocation_id}_{name}_{index}")),
173            resumes: None,
174        })
175        .collect()
176}
177
178/// The calls in `content` to long-running tools, by call id, as adk-python and adk-go list
179/// them; a call without an id is listed by its tool's name.
180fn collect_long_running_tool_ids(
181    tool_map: &HashMap<String, Arc<dyn Tool>>,
182    content: &Content,
183) -> Vec<String> {
184    content
185        .parts
186        .iter()
187        .filter_map(|part| {
188            if let Part::FunctionCall { name, id, .. } = part
189                && tool_map.get(name).is_some_and(|tool| tool.is_long_running())
190            {
191                return Some(id.clone().unwrap_or_else(|| name.clone()));
192            }
193            None
194        })
195        .collect()
196}
197
198/// Builds one streamed model event.
199///
200/// `request_debug` is the bounded request copy from [`trace_json_payload`]: the
201/// full request carries the whole conversation, so embedding it in every
202/// terminal event would make stored history grow quadratically.
203fn build_partial_llm_event(
204    event_id: &str,
205    invocation_id: &str,
206    agent_name: &str,
207    request_debug: &str,
208    chunk: &LlmResponse,
209    long_running_tool_ids: Vec<String>,
210) -> Event {
211    let mut event = Event::with_id(event_id, invocation_id);
212    event.author = agent_name.to_string();
213    // Payload snapshots go on the terminal chunk only; repeating them on every
214    // incremental chunk turns streaming into O(request_size * chunk_count) work.
215    if !chunk.partial {
216        event.llm_request = Some(request_debug.to_string());
217        event.provider_metadata.insert(
218            "gcp.vertex.agent.llm_response".to_string(),
219            serde_json::to_string(chunk).unwrap_or_default(),
220        );
221    }
222    event.llm_response.partial = chunk.partial;
223    event.llm_response.turn_complete = chunk.turn_complete;
224    event.llm_response.finish_reason = chunk.finish_reason;
225    event.llm_response.usage_metadata = chunk.usage_metadata.clone();
226    event.llm_response.citation_metadata = chunk.citation_metadata.clone();
227    event.llm_response.content = chunk.content.clone();
228    event.llm_response.provider_metadata = chunk.provider_metadata.clone();
229    event.llm_response.interaction_id = chunk.interaction_id.clone();
230    // Provider failures delivered as `Ok(LlmResponse { error_code, .. })` must
231    // remain observable on the streamed event.
232    event.llm_response.interrupted = chunk.interrupted;
233    event.llm_response.error_code = chunk.error_code.clone();
234    event.llm_response.error_message = chunk.error_message.clone();
235    event.llm_response.model = chunk.model.clone();
236    event.llm_response.provider = chunk.provider.clone();
237    event.long_running_tool_ids = long_running_tool_ids;
238    event
239}
240
241/// Builds the single model event of a non-streaming turn; see
242/// [`build_partial_llm_event`] for `request_debug`.
243fn build_final_llm_event(
244    event_id: &str,
245    invocation_id: &str,
246    agent_name: &str,
247    request_debug: &str,
248    content: Option<&Content>,
249    last_chunk: Option<&LlmResponse>,
250    long_running_tool_ids: Vec<String>,
251) -> Event {
252    let mut event = Event::with_id(event_id, invocation_id);
253    event.author = agent_name.to_string();
254    event.llm_request = Some(request_debug.to_string());
255    event.llm_response.content = content.cloned();
256    event.llm_response.partial = false;
257    event.llm_response.turn_complete = true;
258
259    if let Some(last_chunk) = last_chunk {
260        event.llm_response.turn_complete = last_chunk.turn_complete;
261        event.llm_response.finish_reason = last_chunk.finish_reason;
262        event.llm_response.usage_metadata = last_chunk.usage_metadata.clone();
263        event.llm_response.citation_metadata = last_chunk.citation_metadata.clone();
264        event.llm_response.provider_metadata = last_chunk.provider_metadata.clone();
265        event.llm_response.interaction_id = last_chunk.interaction_id.clone();
266        event.llm_response.interrupted = last_chunk.interrupted;
267        event.llm_response.error_code = last_chunk.error_code.clone();
268        event.llm_response.error_message = last_chunk.error_message.clone();
269        event.llm_response.model = last_chunk.model.clone();
270        event.llm_response.provider = last_chunk.provider.clone();
271        event.provider_metadata.insert(
272            "gcp.vertex.agent.llm_response".to_string(),
273            serde_json::to_string(last_chunk).unwrap_or_default(),
274        );
275    }
276
277    event.long_running_tool_ids = long_running_tool_ids;
278    event
279}
280
281/// The event that ends a run on a call held for confirmation.
282pub(crate) fn confirmation_event(
283    invocation_id: &str,
284    agent_name: &str,
285    request: ToolConfirmationRequest,
286) -> Event {
287    let mut event = Event::new(invocation_id);
288    event.author = agent_name.to_string();
289    event.llm_response.interrupted = true;
290    event.llm_response.turn_complete = true;
291    event.llm_response.content = Some(Content::new("model").with_text(format!(
292        "Tool confirmation required for '{}'. Provide approve/deny decision to continue.",
293        request.tool_name
294    )));
295    event.actions.tool_confirmation = Some(request);
296    event
297}
298
299/// An LLM-powered agent that orchestrates tool calls and sub-agent delegation.
300///
301/// `LlmAgent` is the primary agent type in ADK. It sends requests to an LLM,
302/// executes tool calls from the response, and iterates until the model produces
303/// a final text response or the iteration limit is reached.
304///
305/// Use [`LlmAgentBuilder::new`] to construct instances.
306pub struct LlmAgent {
307    name: String,
308    description: String,
309    model: Arc<dyn Llm>,
310    instruction: Option<String>,
311    instruction_provider: Option<Arc<InstructionProvider>>,
312    static_instruction: Option<String>,
313    global_instruction: Option<String>,
314    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
315    skills_index: Option<Arc<SkillIndex>>,
316    skill_policy: SelectionPolicy,
317    max_skill_chars: usize,
318    #[allow(dead_code)] // Part of public API via builder
319    input_schema: Option<serde_json::Value>,
320    output_schema: Option<serde_json::Value>,
321    /// Maximum retry attempts for output schema validation (default: 3).
322    output_max_retries: usize,
323    disallow_transfer_to_parent: bool,
324    disallow_transfer_to_peers: bool,
325    include_contents: adk_core::IncludeContents,
326    tools: Vec<Arc<dyn Tool>>,
327    toolsets: Vec<Arc<dyn Toolset>>,
328    /// Whether a toolset that fails to resolve its tools fails the turn.
329    strict_toolsets: bool,
330    sub_agents: Vec<Arc<dyn Agent>>,
331    output_key: Option<String>,
332    /// Default generation config (temperature, top_p, etc.) applied to every LLM request.
333    generate_content_config: Option<adk_core::GenerateContentConfig>,
334    /// Maximum number of LLM round-trips before stopping
335    max_iterations: u32,
336    /// Timeout for individual tool executions
337    tool_timeout: std::time::Duration,
338    /// Whether tool and callback error messages reach the model.
339    expose_tool_error_messages: bool,
340    before_callbacks: Arc<Vec<BeforeAgentCallback>>,
341    after_callbacks: Arc<Vec<AfterAgentCallback>>,
342    history_processors: Arc<Vec<adk_core::HistoryProcessor>>,
343    before_model_callbacks: Arc<Vec<BeforeModelCallback>>,
344    after_model_callbacks: Arc<Vec<AfterModelCallback>>,
345    before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
346    after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
347    on_tool_error_callbacks: Arc<Vec<OnToolErrorCallback>>,
348    /// Rich after-tool callbacks that receive tool, args, and response.
349    after_tool_callbacks_full: Arc<Vec<AfterToolCallbackFull>>,
350    /// Default retry budget applied to all tools without a per-tool override.
351    default_retry_budget: Option<RetryBudget>,
352    /// Per-tool retry budget overrides, keyed by tool name.
353    tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
354    /// Circuit breaker failure threshold. When set, tools are temporarily disabled
355    /// after this many consecutive failures within a single invocation.
356    circuit_breaker_threshold: Option<u32>,
357    tool_confirmation_policy: ToolConfirmationPolicy,
358    /// Per-agent tool execution strategy override. When `Some`, overrides the
359    /// `RunConfig` strategy for this agent's dispatch loop.
360    tool_execution_strategy: Option<ToolExecutionStrategy>,
361    /// Whether consecutive agent-delegation calls may execute concurrently.
362    parallelize_agent_delegations: bool,
363    input_guardrails: Arc<GuardrailSet>,
364    output_guardrails: Arc<GuardrailSet>,
365    tool_guardrails: Arc<ToolGuardrailSet>,
366    /// Enhanced plugin manager for fine-grained tool/model call interception.
367    /// Only created when enhanced plugins are registered (zero overhead otherwise).
368    #[cfg(feature = "enhanced-plugins")]
369    enhanced_plugin_manager: Option<Arc<EnhancedPluginManager>>,
370    /// Optional sandbox configuration for workspace lifecycle management.
371    /// When present, the SandboxRunner uses this to provision and bind tools.
372    /// The config does NOT add tools directly — that is SandboxRunner's responsibility.
373    #[cfg(feature = "sandbox")]
374    sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
375}
376
377struct PromptConfig {
378    instruction: Option<String>,
379    instruction_provider: Option<Arc<InstructionProvider>>,
380    static_instruction: Option<String>,
381    global_instruction: Option<String>,
382    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
383    skills_index: Option<Arc<SkillIndex>>,
384    skill_policy: SelectionPolicy,
385    max_skill_chars: usize,
386    output_schema: Option<serde_json::Value>,
387    include_contents: adk_core::IncludeContents,
388}
389
390impl PromptConfig {
391    fn from_agent(agent: &LlmAgent) -> Self {
392        Self {
393            instruction: agent.instruction.clone(),
394            instruction_provider: agent.instruction_provider.clone(),
395            static_instruction: agent.static_instruction.clone(),
396            global_instruction: agent.global_instruction.clone(),
397            global_instruction_provider: agent.global_instruction_provider.clone(),
398            skills_index: agent.skills_index.clone(),
399            skill_policy: agent.skill_policy.clone(),
400            max_skill_chars: agent.max_skill_chars,
401            output_schema: agent.output_schema.clone(),
402            include_contents: agent.include_contents,
403        }
404    }
405
406    async fn prepare_conversation(
407        &self,
408        ctx: &Arc<dyn InvocationContext>,
409        agent_name: &str,
410    ) -> Result<Vec<Content>> {
411        // Instructions travel as `system` contents so providers place them in their
412        // native system prompt instead of guessing from leading user turns.
413        let mut preamble = Vec::new();
414
415        // Sent first and never templated, so a provider can cache it across sessions.
416        if let Some(text) = self.static_instruction.as_ref().filter(|text| !text.is_empty()) {
417            preamble.push(Content::new("system").with_text(text.clone()));
418        }
419
420        if let Some(provider) = &self.global_instruction_provider {
421            let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
422            if !instruction.is_empty() {
423                preamble.push(Content::new("system").with_text(instruction));
424            }
425        } else if let Some(template) = &self.global_instruction {
426            let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
427            if !instruction.is_empty() {
428                preamble.push(Content::new("system").with_text(instruction));
429            }
430        }
431
432        if let Some(provider) = &self.instruction_provider {
433            let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
434            if !instruction.is_empty() {
435                preamble.push(Content::new("system").with_text(instruction));
436            }
437        } else if let Some(template) = &self.instruction {
438            let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
439            if !instruction.is_empty() {
440                preamble.push(Content::new("system").with_text(instruction));
441            }
442        }
443
444        if let Some(schema) = &self.output_schema {
445            preamble.push(Content::new("system").with_text(format!(
446                "You MUST respond with valid JSON conforming to this schema: {schema}. Do not include any text outside the JSON object."
447            )));
448        }
449
450        // An agent that received control by transfer sees only the user's turns and its own.
451        // Otherwise, as in a workflow, other agents' turns reach it as user-role context, so
452        // it never replays an earlier agent's answer as its own.
453        let mut session_history = if ctx.authoritative_transfer_targets()
454            || !ctx.run_config().transfer_targets.is_empty()
455        {
456            ctx.session().conversation_history_scoped(Some(agent_name), ctx.branch())
457        } else {
458            ctx.session().conversation_history_with_context(agent_name, ctx.branch())
459        };
460        let mut current_user_content = ctx.user_content().clone();
461        if let Some(index) = &self.skills_index {
462            apply_skill_injection(
463                &mut current_user_content,
464                index.as_ref(),
465                &self.skill_policy,
466                self.max_skill_chars,
467            );
468        }
469        // A run that resumes held calls carries an empty user turn: no parts, or only blank
470        // text. A turn without parts never reaches the projected history, so the last user
471        // turn there is the person's message, which an empty turn must not stand in for.
472        let empty_turn = current_user_content
473            .parts
474            .iter()
475            .all(|part| matches!(part, Part::Text { text } if text.trim().is_empty()));
476        // A turn of function responses alone answers calls, as a caller resuming a
477        // long-running call sends. The session history already holds those responses after
478        // their calls, so the turn never stands in for the person's message.
479        let answers_only = !current_user_content.parts.is_empty()
480            && current_user_content
481                .parts
482                .iter()
483                .all(|part| matches!(part, Part::FunctionResponse { .. }));
484        if !empty_turn {
485            // The run's own message, never a steering message a run-mate took after it.
486            let own = session_history.iter().rposition(|content| content == ctx.user_content());
487            let last_message = || {
488                session_history.iter().rposition(|content| {
489                    content.role == "user"
490                        && !adk_core::history::is_other_agent_context(content)
491                        && !adk_core::history::is_system_notice(content)
492                })
493            };
494            match own {
495                Some(index) => session_history[index] = current_user_content.clone(),
496                None if answers_only => {}
497                None => match last_message() {
498                    Some(index) => session_history[index] = current_user_content.clone(),
499                    None => session_history.push(current_user_content.clone()),
500                },
501            }
502        }
503        // An empty user turn adds nothing to the conversation, and providers such as
504        // Anthropic reject empty text blocks.
505        session_history.retain(|content| {
506            content.role != "user"
507                || content
508                    .parts
509                    .iter()
510                    .any(|part| !matches!(part, Part::Text { text } if text.trim().is_empty()))
511        });
512        // An agent limited to its current turn sees the latest user input and what followed.
513        // A run that resumes held calls begins that turn at the message that led to the
514        // earliest one, so each resumed result answers a call the model can see; an empty
515        // turn that resumes none begins it at the person's last message. Any other run sends
516        // the current user turn alone, also while a call waits for a decision (spec 3.3 §7.3).
517        let turn_start = match self.include_contents {
518            adk_core::IncludeContents::Default => None,
519            adk_core::IncludeContents::None => {
520                // The held calls this run resumes: those with a decision.
521                let gate = ToolGate::for_context(ctx.as_ref());
522                let mut held = Vec::<String>::new();
523                for call in ctx.session().held_tool_calls(agent_name, ctx.branch()) {
524                    if let Some(id) = call.id
525                        && adk_core::confirmation_decision_available(&gate, &call.request).await?
526                    {
527                        held.push(id);
528                    }
529                }
530                let earliest_held = session_history.iter().position(|content| {
531                    content.parts.iter().any(|part| {
532                        matches!(part, Part::FunctionCall { id: Some(id), .. } if held.contains(id))
533                    })
534                });
535                let is_message = |content: &Content| {
536                    content.role == "user"
537                        && content.carries_user_input()
538                        && !adk_core::history::is_other_agent_context(content)
539                        && !adk_core::history::is_system_notice(content)
540                };
541                match earliest_held {
542                    Some(call) => {
543                        Some(session_history[..call].iter().rposition(is_message).unwrap_or(0))
544                    }
545                    None if empty_turn => {
546                        Some(session_history.iter().rposition(is_message).unwrap_or(0))
547                    }
548                    None => None,
549                }
550            }
551        };
552        // A history that ends on the model's answer — a resuming run whose model already
553        // answered after the held call, or a loop running this agent again after its own
554        // answer — would be read as a prefill, which models without prefill support
555        // (Anthropic's newer ones) reject. It gets a user turn to answer.
556        if session_history.last().is_some_and(|last| {
557            last.role == "model"
558                && !last.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
559        }) {
560            let note = if empty_turn { RESUMED_TURN_NOTE } else { CONTINUE_TURN_NOTE };
561            session_history.push(Content::new("user").with_text(note));
562        }
563
564        Ok(match (self.include_contents, turn_start) {
565            (adk_core::IncludeContents::None, Some(start)) => {
566                preamble.extend(session_history.drain(start..));
567                preamble
568            }
569            (adk_core::IncludeContents::None, None) => {
570                preamble.push(current_user_content);
571                preamble
572            }
573            (adk_core::IncludeContents::Default, _) => {
574                preamble.extend(session_history);
575                preamble
576            }
577        })
578    }
579}
580
581/// The system text that tells the model when to hand the conversation to another agent:
582/// each agent it can transfer to, with that agent's description, the rule to answer itself
583/// or transfer, and the parent to fall back to. adk-python gives its models the same
584/// guidance; without the descriptions a model chooses a target by its name alone.
585fn transfer_instruction(targets: &[(&str, &str)], parent: Option<&str>) -> String {
586    let mut text = String::from("You can transfer the conversation to these agents:\n");
587    for (name, description) in targets {
588        text.push_str(&format!("\nAgent name: {name}\n"));
589        if !description.trim().is_empty() {
590            text.push_str(&format!("Agent description: {description}\n"));
591        }
592    }
593    text.push_str(
594        "\nIf you are the best agent to answer according to your own description, answer. If \
595         another agent fits the request better according to its description, call \
596         `transfer_to_agent` with its name, and write no text other than the function call.",
597    );
598    if let Some(parent) = parent {
599        text.push_str(&format!(
600            "\n\nYour parent agent is {parent}. If neither you nor the other agents fit the \
601             request, transfer to {parent}."
602        ));
603    }
604    text
605}
606
607/// The user turn a run without user input sends when the conversation would otherwise
608/// end on a model message.
609const RESUMED_TURN_NOTE: &str =
610    "(No new message from the user. Continue from the tool results above.)";
611
612/// The user turn a run sends when its history ends on this agent's own answer.
613const CONTINUE_TURN_NOTE: &str =
614    "(No new message from the user. Continue from the conversation above.)";
615
616struct ToolSetup {
617    tools: Vec<Arc<dyn Tool>>,
618    toolsets: Vec<Arc<dyn Toolset>>,
619    strict_toolsets: bool,
620    sub_agents: Vec<Arc<dyn Agent>>,
621    disallow_transfer_to_parent: bool,
622    disallow_transfer_to_peers: bool,
623}
624
625struct ResolvedTools {
626    map: HashMap<String, Arc<dyn Tool>>,
627    declarations: adk_core::ToolDeclarations,
628    transfer_targets: Vec<String>,
629    /// When to transfer and to whom, for the system instruction; see [`transfer_instruction`].
630    transfer_guidance: Option<String>,
631}
632
633impl ToolSetup {
634    fn from_agent(agent: &LlmAgent) -> Self {
635        Self {
636            tools: agent.tools.clone(),
637            toolsets: agent.toolsets.clone(),
638            strict_toolsets: agent.strict_toolsets,
639            sub_agents: agent.sub_agents.clone(),
640            disallow_transfer_to_parent: agent.disallow_transfer_to_parent,
641            disallow_transfer_to_peers: agent.disallow_transfer_to_peers,
642        }
643    }
644
645    async fn resolve(&self, ctx: &Arc<dyn InvocationContext>) -> Result<ResolvedTools> {
646        let mut tools = self.tools.clone();
647        let static_tool_names: std::collections::HashSet<_> =
648            tools.iter().map(|tool| tool.name().to_string()).collect();
649        let mut toolset_sources = std::collections::HashMap::<String, String>::new();
650        let mut active_toolsets: Vec<&dyn Toolset> =
651            self.toolsets.iter().map(AsRef::as_ref).collect();
652        active_toolsets.extend(
653            ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
654        );
655
656        for toolset in active_toolsets {
657            let provided = match toolset.tools(ctx.clone() as Arc<dyn ReadonlyContext>).await {
658                Ok(provided) => provided,
659                // One unreachable server costs the model that server's tools, not the turn.
660                Err(error) if !self.strict_toolsets => {
661                    tracing::warn!(
662                        agent.name = %ctx.agent_name(),
663                        toolset.name = %toolset.name(),
664                        error = %error.diagnostics(),
665                        error.message = %traced_message(ctx.run_config(), &error.message),
666                        "toolset failed to resolve its tools; continuing without them"
667                    );
668                    continue;
669                }
670                Err(error) => return Err(error),
671            };
672            for tool in provided {
673                let name = tool.name().to_string();
674                if static_tool_names.contains(&name) {
675                    return Err(adk_core::AdkError::agent(format!(
676                        "Duplicate tool name '{name}': conflict between static tool and toolset '{}'",
677                        toolset.name()
678                    )));
679                }
680                if let Some(other_toolset) = toolset_sources.get(&name) {
681                    return Err(adk_core::AdkError::agent(format!(
682                        "Duplicate tool name '{name}': conflict between toolset '{other_toolset}' and toolset '{}'",
683                        toolset.name()
684                    )));
685                }
686                toolset_sources.insert(name, toolset.name().to_string());
687                tools.push(tool);
688            }
689        }
690
691        let map = tools.iter().map(|tool| (tool.name().to_string(), tool.clone())).collect();
692        let mut declarations = tools
693            .iter()
694            .map(|tool| (tool.name().to_string(), tool.declaration()))
695            .collect::<adk_core::ToolDeclarations>();
696        let mut transfer_targets: Vec<String> = if ctx.authoritative_transfer_targets() {
697            Vec::new()
698        } else {
699            self.sub_agents.iter().map(|agent| agent.name().to_string()).collect()
700        };
701        let child_names: std::collections::HashSet<_> =
702            self.sub_agents.iter().map(|agent| agent.name()).collect();
703        let parent_name = ctx.run_config().parent_agent.as_deref();
704
705        for target in &ctx.run_config().transfer_targets {
706            if child_names.contains(target.as_str()) {
707                continue;
708            }
709            let is_parent = parent_name == Some(target.as_str());
710            if (is_parent && self.disallow_transfer_to_parent)
711                || (!is_parent && self.disallow_transfer_to_peers)
712            {
713                continue;
714            }
715            transfer_targets.push(target.clone());
716        }
717
718        if !transfer_targets.is_empty() {
719            declarations.insert(
720                "transfer_to_agent".to_string(),
721                serde_json::json!({
722                    "name": "transfer_to_agent",
723                    "description": format!(
724                        "Transfer execution to another agent. Valid targets: {}",
725                        transfer_targets.join(", ")
726                    ),
727                    "parameters": {
728                        "type": "object",
729                        "properties": {
730                            "agent_name": {
731                                "type": "string",
732                                "description": "The name of the agent to transfer to.",
733                                "enum": transfer_targets
734                            }
735                        },
736                        "required": ["agent_name"]
737                    }
738                }),
739            );
740        }
741
742        let transfer_guidance = (!transfer_targets.is_empty()).then(|| {
743            let descriptions = &ctx.run_config().transfer_target_descriptions;
744            let described: Vec<(&str, &str)> = transfer_targets
745                .iter()
746                .map(|name| {
747                    let description = self
748                        .sub_agents
749                        .iter()
750                        .find(|agent| agent.name() == name)
751                        .map(|agent| agent.description())
752                        .or_else(|| descriptions.get(name).map(String::as_str))
753                        .unwrap_or("");
754                    (name.as_str(), description)
755                })
756                .collect();
757            let parent = parent_name.filter(|parent| transfer_targets.iter().any(|t| t == parent));
758            transfer_instruction(&described, parent)
759        });
760
761        Ok(ResolvedTools { map, declarations, transfer_targets, transfer_guidance })
762    }
763
764    /// Lets static and invocation-scoped toolsets enrich each LLM request.
765    async fn process_llm_request(
766        &self,
767        ctx: &Arc<dyn InvocationContext>,
768        request: &mut LlmRequest,
769    ) -> Result<()> {
770        for toolset in self.toolsets.iter().map(AsRef::as_ref).chain(
771            ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
772        ) {
773            toolset.process_llm_request(ctx.clone() as Arc<dyn ReadonlyContext>, request).await?;
774        }
775        Ok(())
776    }
777}
778
779impl std::fmt::Debug for LlmAgent {
780    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
781        f.debug_struct("LlmAgent")
782            .field("name", &self.name)
783            .field("description", &self.description)
784            .field("model", &self.model.name())
785            .field("instruction", &self.instruction)
786            .field("tools_count", &self.tools.len())
787            .field("sub_agents_count", &self.sub_agents.len())
788            .finish()
789    }
790}
791
792impl LlmAgent {
793    /// Returns the sandbox configuration attached to this agent, if any.
794    ///
795    /// The `SandboxRunner` uses this to provision a workspace and bind tools.
796    /// Returns `None` when no sandbox config was set on the builder.
797    ///
798    /// Requires the `sandbox` feature.
799    #[cfg(feature = "sandbox")]
800    pub fn sandbox_config(&self) -> Option<&adk_sandbox::workspace::SandboxConfig> {
801        self.sandbox_config.as_ref()
802    }
803
804    async fn apply_input_guardrails(
805        ctx: Arc<dyn InvocationContext>,
806        input_guardrails: Arc<GuardrailSet>,
807    ) -> Result<Arc<dyn InvocationContext>> {
808        let content =
809            enforce_guardrails(input_guardrails.as_ref(), ctx.user_content(), Phase::Input)
810                .await?
811                .content;
812        if content.role != ctx.user_content().role || content.parts != ctx.user_content().parts {
813            Ok(with_user_content_override(ctx, content))
814        } else {
815            Ok(ctx)
816        }
817    }
818
819    fn history_parts_from_provider_metadata(
820        provider_metadata: Option<&serde_json::Value>,
821    ) -> Vec<Part> {
822        let Some(provider_metadata) = provider_metadata else {
823            return Vec::new();
824        };
825
826        let history_parts = provider_metadata
827            .get("conversation_history_parts")
828            .or_else(|| {
829                provider_metadata
830                    .get("openai")
831                    .and_then(|openai| openai.get("conversation_history_parts"))
832            })
833            .and_then(serde_json::Value::as_array);
834
835        history_parts
836            .into_iter()
837            .flatten()
838            .filter_map(|value| serde_json::from_value::<Part>(value.clone()).ok())
839            .collect()
840    }
841
842    fn continues_turn(metadata: Option<&serde_json::Value>) -> bool {
843        metadata
844            .and_then(|metadata| metadata.get("continue_turn"))
845            .and_then(serde_json::Value::as_bool)
846            == Some(true)
847    }
848
849    fn augment_content_for_history(
850        content: &Content,
851        provider_metadata: Option<&serde_json::Value>,
852    ) -> Content {
853        let mut augmented = content.clone();
854        augmented.parts.extend(Self::history_parts_from_provider_metadata(provider_metadata));
855        // The next request of this loop may go to another provider (a fallback or router
856        // model); the turn's native items stay with the origin that produced them.
857        adk_core::history::mark_origin(
858            &mut augmented,
859            adk_core::history::ProviderOrigin::of_response(provider_metadata).as_ref(),
860        );
861        augmented
862    }
863}
864
865/// Validate a JSON string against an output schema.
866///
867/// Returns `Ok(valid_json)` if the text parses as valid JSON and passes schema
868/// validation. Returns `Err(error_message)` describing the validation failure.
869fn validate_output_against_schema(
870    text: &str,
871    schema: &serde_json::Value,
872) -> std::result::Result<serde_json::Value, String> {
873    let parsed: serde_json::Value = serde_json::from_str(strip_json_code_fence(text))
874        .map_err(|e| format!("Response is not valid JSON: {e}"))?;
875
876    let validator =
877        jsonschema::validator_for(schema).map_err(|e| format!("Invalid schema: {e}"))?;
878
879    let errors: Vec<String> = validator.iter_errors(&parsed).map(|e| e.to_string()).collect();
880
881    if errors.is_empty() { Ok(parsed) } else { Err(errors.join("; ")) }
882}
883
884/// The JSON inside one Markdown code fence wrapping all of `text`, or `text` unchanged.
885///
886/// A model asked for structured output sometimes wraps it in a ```` ```json ```` fence,
887/// most often when tools are configured and the schema constraint is best-effort. JSON
888/// never starts with a fence, so valid output is unchanged.
889fn strip_json_code_fence(text: &str) -> &str {
890    let trimmed = text.trim();
891    let Some(rest) = trimmed.strip_prefix("```") else {
892        return text;
893    };
894    let Some(body) = rest.strip_suffix("```") else {
895        return text;
896    };
897    // The info string (`json`, `JSON`, ...) runs to the end of the opening line.
898    let body = match body.find('\n') {
899        Some(newline) if body[..newline].chars().all(|c| c.is_ascii_alphanumeric()) => {
900            &body[newline + 1..]
901        }
902        _ => body.trim_start_matches(|c: char| c.is_ascii_alphanumeric()),
903    };
904    if body.contains("```") {
905        return text;
906    }
907    body.trim()
908}
909
910/// Rebuilds the chunk an after-model callback replaced.
911///
912/// The replacement's content and metadata win. The chunk's place in the stream and what the
913/// call used stay with the original: `partial` and `turn_complete` stay set when the
914/// original had them, and `finish_reason` and `usage_metadata` carry over unless the
915/// replacement sets them. A callback that returns `LlmResponse { content, ..Default::default() }`
916/// for a streamed delta therefore still produces one persisted event per response, with usage.
917fn replace_chunk(original: &LlmResponse, mut replacement: LlmResponse) -> LlmResponse {
918    replacement.partial |= original.partial;
919    replacement.turn_complete |= original.turn_complete;
920    if replacement.finish_reason.is_none() {
921        replacement.finish_reason = original.finish_reason;
922    }
923    if replacement.usage_metadata.is_none() {
924        replacement.usage_metadata = original.usage_metadata.clone();
925    }
926    replacement
927}
928
929/// Whether a final model turn carries an answer: text that is not only whitespace, data, a
930/// file, a resource, or a provider tool part. Thinking alone is not an answer.
931fn has_answer_content(content: &Content) -> bool {
932    content.parts.iter().any(|part| match part {
933        Part::Text { text } => !text.trim().is_empty(),
934        Part::Thinking { .. } => false,
935        Part::InlineData { .. }
936        | Part::FileData { .. }
937        | Part::FunctionCall { .. }
938        | Part::FunctionResponse { .. }
939        | Part::ServerToolCall { .. }
940        | Part::ServerToolResponse { .. }
941        | Part::EmbeddedResource { .. } => true,
942    })
943}
944
945/// The error for a model turn that ended without an answer.
946fn empty_response_error(finish_reason: Option<adk_core::FinishReason>) -> adk_core::AdkError {
947    let mut details = adk_core::ErrorDetails::default();
948    if let Some(reason) = finish_reason {
949        details
950            .metadata
951            .insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
952    }
953    let reason = finish_reason.map_or_else(|| "none".to_string(), |reason| format!("{reason:?}"));
954    let message = match finish_reason {
955        // Retrying spends the same limit the same way, so the guidance names the two fixes.
956        Some(adk_core::FinishReason::MaxTokens) => "the model reached its output-token limit \
957             before it answered: the whole limit went to thinking (finish reason: MaxTokens); \
958             raise the model's maximum output tokens or lower its reasoning effort"
959            .to_string(),
960        _ => format!(
961            "the model ended its turn without an answer: no text, data or tool call, only \
962             thinking or whitespace (finish reason: {reason}); retry the run, or check the \
963             model's output limit and safety settings"
964        ),
965    };
966    adk_core::AdkError::new(
967        adk_core::ErrorComponent::Model,
968        adk_core::ErrorCategory::Internal,
969        "model.empty_response",
970        message,
971    )
972    .with_details(details)
973}
974
975/// The error that ends a run whose model turn finished with [`FinishReason::Refusal`] or
976/// [`FinishReason::MalformedToolCall`], or `None` for any other finish.
977///
978/// A refusal's text is the model declining, not an answer, and a malformed tool call names
979/// no call that can run, so neither may read as a finished turn. `description` is the
980/// provider's own message when it sent one, otherwise the turn's text; `provider_code` is the
981/// provider's `error_code`, kept in `details.metadata["provider_error_code"]`.
982///
983/// [`FinishReason::Refusal`]: adk_core::FinishReason::Refusal
984/// [`FinishReason::MalformedToolCall`]: adk_core::FinishReason::MalformedToolCall
985pub(crate) fn finish_error(
986    finish_reason: Option<adk_core::FinishReason>,
987    description: Option<&str>,
988    provider_code: Option<&str>,
989) -> Option<adk_core::AdkError> {
990    let reason = finish_reason?;
991    let description = description
992        .map(|text| adk_core::upstream_excerpt(text).trim_end_matches('.'))
993        .filter(|text| !text.is_empty())
994        .map(|text| format!(": {text}"))
995        .unwrap_or_default();
996    let (category, code, message) = match reason {
997        adk_core::FinishReason::Refusal => (
998            adk_core::ErrorCategory::Forbidden,
999            "model.refusal",
1000            format!(
1001                "the model declined the request{description}. Rephrase the request, or retry \
1002                 it on another model"
1003            ),
1004        ),
1005        adk_core::FinishReason::MalformedToolCall => (
1006            adk_core::ErrorCategory::Internal,
1007            "model.malformed_tool_call",
1008            format!(
1009                "the model produced a tool call the provider reports as invalid{description}. \
1010                 Retry the run; if it recurs, simplify the tool's parameter schema or offer \
1011                 fewer tools"
1012            ),
1013        ),
1014        _ => return None,
1015    };
1016    let mut details = adk_core::ErrorDetails::default();
1017    details.metadata.insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
1018    if let Some(provider_code) = provider_code {
1019        details
1020            .metadata
1021            .insert("provider_error_code".to_string(), serde_json::json!(provider_code));
1022    }
1023    Some(
1024        adk_core::AdkError::new(adk_core::ErrorComponent::Model, category, code, message)
1025            .with_details(details),
1026    )
1027}
1028
1029/// Extract the text content from a series of events.
1030///
1031/// Scans events in reverse order for the last non-empty text content
1032/// produced by the agent. Used internally for output schema validation.
1033fn extract_text_from_events(events: &[Event]) -> Option<String> {
1034    for event in events.iter().rev() {
1035        if let Some(ref content) = event.llm_response.content {
1036            let text: String =
1037                content
1038                    .parts
1039                    .iter()
1040                    .filter_map(|p| {
1041                        if let Part::Text { text } = p { Some(text.as_str()) } else { None }
1042                    })
1043                    .collect::<Vec<_>>()
1044                    .join("");
1045            if !text.is_empty() {
1046                return Some(text);
1047            }
1048        }
1049    }
1050    None
1051}
1052
1053/// Extract a typed value from agent events.
1054///
1055/// Scans events for the last text content and deserializes it into `T`.
1056/// This is useful after running an agent with `output_schema` set to
1057/// extract the structured result. One Markdown code fence wrapping the whole
1058/// text is removed first.
1059///
1060/// # Example
1061///
1062/// ```rust,ignore
1063/// use serde::Deserialize;
1064/// use adk_agent::extract_typed;
1065///
1066/// #[derive(Deserialize)]
1067/// struct Weather {
1068///     temperature: f64,
1069///     condition: String,
1070/// }
1071///
1072/// let events: Vec<Event> = collect_events_from_stream(stream).await?;
1073/// let weather: Weather = extract_typed(&events)?;
1074/// ```
1075pub fn extract_typed<T: serde::de::DeserializeOwned>(events: &[Event]) -> Result<T> {
1076    let text = extract_text_from_events(events).ok_or_else(|| {
1077        adk_core::AdkError::agent("no text content found in events for typed extraction")
1078    })?;
1079
1080    serde_json::from_str(strip_json_code_fence(&text))
1081        .map_err(|e| adk_core::AdkError::agent(format!("output deserialization failed: {e}")))
1082}
1083
1084/// Builder for constructing an [`LlmAgent`] with all configuration options.
1085pub struct LlmAgentBuilder {
1086    name: String,
1087    description: Option<String>,
1088    model: Option<Arc<dyn Llm>>,
1089    instruction: Option<String>,
1090    instruction_provider: Option<Arc<InstructionProvider>>,
1091    static_instruction: Option<String>,
1092    global_instruction: Option<String>,
1093    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
1094    skills_index: Option<Arc<SkillIndex>>,
1095    skill_policy: SelectionPolicy,
1096    max_skill_chars: usize,
1097    input_schema: Option<serde_json::Value>,
1098    output_schema: Option<serde_json::Value>,
1099    output_max_retries: usize,
1100    disallow_transfer_to_parent: bool,
1101    disallow_transfer_to_peers: bool,
1102    include_contents: adk_core::IncludeContents,
1103    tools: Vec<Arc<dyn Tool>>,
1104    toolsets: Vec<Arc<dyn Toolset>>,
1105    strict_toolsets: bool,
1106    sub_agents: Vec<Arc<dyn Agent>>,
1107    output_key: Option<String>,
1108    generate_content_config: Option<adk_core::GenerateContentConfig>,
1109    max_iterations: u32,
1110    tool_timeout: std::time::Duration,
1111    expose_tool_error_messages: bool,
1112    before_callbacks: Vec<BeforeAgentCallback>,
1113    after_callbacks: Vec<AfterAgentCallback>,
1114    history_processors: Vec<adk_core::HistoryProcessor>,
1115    before_model_callbacks: Vec<BeforeModelCallback>,
1116    after_model_callbacks: Vec<AfterModelCallback>,
1117    before_tool_callbacks: Vec<BeforeToolCallback>,
1118    after_tool_callbacks: Vec<AfterToolCallback>,
1119    on_tool_error_callbacks: Vec<OnToolErrorCallback>,
1120    after_tool_callbacks_full: Vec<AfterToolCallbackFull>,
1121    default_retry_budget: Option<RetryBudget>,
1122    tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
1123    circuit_breaker_threshold: Option<u32>,
1124    tool_confirmation_policy: ToolConfirmationPolicy,
1125    tool_execution_strategy: Option<ToolExecutionStrategy>,
1126    parallelize_agent_delegations: bool,
1127    input_guardrails: GuardrailSet,
1128    output_guardrails: GuardrailSet,
1129    tool_guardrails: ToolGuardrailSet,
1130    /// Enhanced plugins to register on the built agent.
1131    #[cfg(feature = "enhanced-plugins")]
1132    enhanced_plugins: Vec<Arc<dyn EnhancedPlugin>>,
1133    /// Optional sandbox configuration for workspace lifecycle management.
1134    #[cfg(feature = "sandbox")]
1135    sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
1136}
1137
1138impl LlmAgentBuilder {
1139    /// Create a new builder with the given agent name.
1140    pub fn new(name: impl Into<String>) -> Self {
1141        Self {
1142            name: name.into(),
1143            description: None,
1144            model: None,
1145            instruction: None,
1146            instruction_provider: None,
1147            static_instruction: None,
1148            global_instruction: None,
1149            global_instruction_provider: None,
1150            skills_index: None,
1151            skill_policy: SelectionPolicy::default(),
1152            max_skill_chars: 2000,
1153            input_schema: None,
1154            output_schema: None,
1155            output_max_retries: 3,
1156            disallow_transfer_to_parent: false,
1157            disallow_transfer_to_peers: false,
1158            include_contents: adk_core::IncludeContents::Default,
1159            tools: Vec::new(),
1160            toolsets: Vec::new(),
1161            strict_toolsets: false,
1162            sub_agents: Vec::new(),
1163            output_key: None,
1164            generate_content_config: None,
1165            max_iterations: DEFAULT_MAX_ITERATIONS,
1166            tool_timeout: DEFAULT_TOOL_TIMEOUT,
1167            expose_tool_error_messages: false,
1168            before_callbacks: Vec::new(),
1169            after_callbacks: Vec::new(),
1170            history_processors: Vec::new(),
1171            before_model_callbacks: Vec::new(),
1172            after_model_callbacks: Vec::new(),
1173            before_tool_callbacks: Vec::new(),
1174            after_tool_callbacks: Vec::new(),
1175            on_tool_error_callbacks: Vec::new(),
1176            after_tool_callbacks_full: Vec::new(),
1177            default_retry_budget: None,
1178            tool_retry_budgets: std::collections::HashMap::new(),
1179            circuit_breaker_threshold: None,
1180            tool_confirmation_policy: ToolConfirmationPolicy::Never,
1181            tool_execution_strategy: None,
1182            parallelize_agent_delegations: false,
1183            input_guardrails: GuardrailSet::new(),
1184            output_guardrails: GuardrailSet::new(),
1185            tool_guardrails: ToolGuardrailSet::new(),
1186            #[cfg(feature = "enhanced-plugins")]
1187            enhanced_plugins: Vec::new(),
1188            #[cfg(feature = "sandbox")]
1189            sandbox_config: None,
1190        }
1191    }
1192
1193    /// Set the agent description.
1194    pub fn description(mut self, desc: impl Into<String>) -> Self {
1195        self.description = Some(desc.into());
1196        self
1197    }
1198
1199    /// Set the LLM model for this agent.
1200    pub fn model(mut self, model: Arc<dyn Llm>) -> Self {
1201        self.model = Some(model);
1202        self
1203    }
1204
1205    /// Set the system instruction for this agent.
1206    ///
1207    /// `{key}` is replaced with the session state value under `key` (an error when it is
1208    /// missing), `{key?}` with the value or nothing, `{app:key}`, `{user:key}`, and
1209    /// `{temp:key}` with prefixed state, and `{artifact.name}` with the artifact's text. See
1210    /// [`adk_core::inject_session_state`]. Text whose braces are not placeholders, such as a
1211    /// skill file quoting `set_target {window_id}`, belongs in
1212    /// [`static_instruction`](Self::static_instruction), which sends it as written.
1213    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
1214        self.instruction = Some(instruction.into());
1215        self
1216    }
1217
1218    /// Set a dynamic instruction provider evaluated per invocation.
1219    ///
1220    /// Takes precedence over [`instruction`](Self::instruction). Its result is sent as
1221    /// written, without `{key}` templating.
1222    ///
1223    /// # Example
1224    ///
1225    /// ```
1226    /// use adk_agent::LlmAgentBuilder;
1227    ///
1228    /// let skill = "Call set_target {window_id} before the first click.";
1229    /// let builder = LlmAgentBuilder::new("trainer").instruction_provider(Box::new(move |_ctx| {
1230    ///     Box::pin(async move { Ok(skill.to_string()) })
1231    /// }));
1232    /// ```
1233    pub fn instruction_provider(mut self, provider: InstructionProvider) -> Self {
1234        self.instruction_provider = Some(Arc::new(provider));
1235        self
1236    }
1237
1238    /// Set an instruction sent exactly as written, before the global instruction and
1239    /// [`instruction`](Self::instruction).
1240    ///
1241    /// No `{key}` placeholder is read, so text you do not control — a skill file, a tool's
1242    /// documentation — keeps its braces. The text is the same in every request, which keeps
1243    /// it cacheable; combine it with `instruction` for the parts that read session state.
1244    ///
1245    /// # Example
1246    ///
1247    /// ```
1248    /// use adk_agent::LlmAgentBuilder;
1249    ///
1250    /// let builder = LlmAgentBuilder::new("trainer")
1251    ///     .static_instruction("Call set_target {window_id} before the first click.")
1252    ///     .instruction("The learner is {learner_name}.");
1253    /// ```
1254    pub fn static_instruction(mut self, instruction: impl Into<String>) -> Self {
1255        self.static_instruction = Some(instruction.into());
1256        self
1257    }
1258
1259    /// Set a global instruction prepended to all requests.
1260    pub fn global_instruction(mut self, instruction: impl Into<String>) -> Self {
1261        self.global_instruction = Some(instruction.into());
1262        self
1263    }
1264
1265    /// Set a dynamic global instruction provider evaluated per invocation.
1266    pub fn global_instruction_provider(mut self, provider: GlobalInstructionProvider) -> Self {
1267        self.global_instruction_provider = Some(Arc::new(provider));
1268        self
1269    }
1270
1271    /// Set a preloaded skills index for this agent.
1272    ///
1273    /// The best matching skill is injected into the current user turn so stable
1274    /// instructions and conversation history remain available for prompt caching.
1275    #[cfg(feature = "skills")]
1276    pub fn with_skills(mut self, index: SkillIndex) -> Self {
1277        self.skills_index = Some(Arc::new(index));
1278        self
1279    }
1280
1281    /// Auto-load skills from `.skills/` in the current working directory.
1282    #[cfg(feature = "skills")]
1283    pub fn with_auto_skills(self) -> Result<Self> {
1284        self.with_skills_from_root(".")
1285    }
1286
1287    /// Auto-load skills from `.skills/` under a custom root directory.
1288    #[cfg(feature = "skills")]
1289    pub fn with_skills_from_root(mut self, root: impl AsRef<std::path::Path>) -> Result<Self> {
1290        let index = load_skill_index(root).map_err(|e| adk_core::AdkError::agent(e.to_string()))?;
1291        self.skills_index = Some(Arc::new(index));
1292        Ok(self)
1293    }
1294
1295    /// Customize skill selection behavior.
1296    #[cfg(feature = "skills")]
1297    pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
1298        self.skill_policy = policy;
1299        self
1300    }
1301
1302    /// Limit injected skill content length.
1303    #[cfg(feature = "skills")]
1304    pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
1305        self.max_skill_chars = max_chars;
1306        self
1307    }
1308
1309    /// Records a JSON Schema describing the input this agent expects.
1310    ///
1311    /// The schema is descriptive: `LlmAgent` does not check user messages against it. To
1312    /// give a model a schema for calling this agent as a tool, set it on the `AgentTool`
1313    /// that wraps the agent (`adk_tool::AgentTool::input_schema`), which declares it as
1314    /// the tool's parameters.
1315    ///
1316    /// # Example
1317    ///
1318    /// ```rust,ignore
1319    /// let agent = LlmAgentBuilder::new("lookup")
1320    ///     .model(model)
1321    ///     .input_schema(serde_json::json!({
1322    ///         "type": "object",
1323    ///         "properties": { "order_id": { "type": "string" } },
1324    ///         "required": ["order_id"]
1325    ///     }))
1326    ///     .build()?;
1327    /// ```
1328    pub fn input_schema(mut self, schema: serde_json::Value) -> Self {
1329        self.input_schema = Some(schema);
1330        self
1331    }
1332
1333    /// Set a JSON schema for structured output from the LLM.
1334    pub fn output_schema(mut self, schema: serde_json::Value) -> Self {
1335        self.output_schema = Some(schema);
1336        self
1337    }
1338
1339    /// Derive the output schema from a Rust type using `schemars`.
1340    ///
1341    /// This is a convenience method that generates a JSON Schema from `T`'s
1342    /// `JsonSchema` implementation and sets it as the output schema.
1343    ///
1344    /// # Example
1345    ///
1346    /// ```rust,ignore
1347    /// use schemars::JsonSchema;
1348    /// use serde::Deserialize;
1349    ///
1350    /// #[derive(JsonSchema, Deserialize)]
1351    /// struct MyOutput {
1352    ///     name: String,
1353    ///     score: f64,
1354    /// }
1355    ///
1356    /// let agent = LlmAgentBuilder::new("my-agent")
1357    ///     .model(model)
1358    ///     .output_type::<MyOutput>()
1359    ///     .build()?;
1360    /// ```
1361    pub fn output_type<T: schemars::JsonSchema>(mut self) -> Self {
1362        let schema = schemars::schema_for!(T);
1363        self.output_schema =
1364            Some(serde_json::to_value(schema).expect("schema serialization cannot fail"));
1365        self
1366    }
1367
1368    /// Set the maximum number of retry attempts for output schema validation.
1369    ///
1370    /// When the LLM produces output that fails schema validation, the agent
1371    /// will retry up to this many times with a correction prompt. Default is 3.
1372    pub fn output_max_retries(mut self, n: usize) -> Self {
1373        self.output_max_retries = n;
1374        self
1375    }
1376
1377    /// Prevent this agent from transferring control back to its parent.
1378    ///
1379    /// The model is not offered the parent as a target, and the runner refuses a transfer to
1380    /// the parent that a tool of this agent requests.
1381    pub fn disallow_transfer_to_parent(mut self, disallow: bool) -> Self {
1382        self.disallow_transfer_to_parent = disallow;
1383        self
1384    }
1385
1386    /// Prevent this agent from transferring control to peer agents.
1387    ///
1388    /// The model is not offered its parent's other sub-agents as targets, and the runner
1389    /// refuses a transfer to one of them that a tool of this agent requests.
1390    pub fn disallow_transfer_to_peers(mut self, disallow: bool) -> Self {
1391        self.disallow_transfer_to_peers = disallow;
1392        self
1393    }
1394
1395    /// Control which conversation history contents are included in LLM requests.
1396    pub fn include_contents(mut self, include: adk_core::IncludeContents) -> Self {
1397        self.include_contents = include;
1398        self
1399    }
1400
1401    /// Set a state key where the agent's final output will be stored.
1402    ///
1403    /// The value is the concatenated text of the final model response: the last turn, the
1404    /// one without tool calls. Text the model wrote beside a tool call in an earlier turn is
1405    /// not included, and each run replaces the value. When a before-agent callback answers
1406    /// for the agent, its content is stored instead. When an `output_schema` is set, it is
1407    /// written only after the response passes schema validation; a response that exhausts
1408    /// `output_max_retries` leaves the key unset.
1409    pub fn output_key(mut self, key: impl Into<String>) -> Self {
1410        self.output_key = Some(key.into());
1411        self
1412    }
1413
1414    /// Set default generation parameters (temperature, top_p, top_k, max_output_tokens)
1415    /// applied to every LLM request made by this agent.
1416    ///
1417    /// These defaults are merged with any per-request config. If `output_schema` is also
1418    /// set, the schema is preserved alongside these generation parameters.
1419    ///
1420    /// # Example
1421    ///
1422    /// ```rust,ignore
1423    /// use adk_core::GenerateContentConfig;
1424    ///
1425    /// let agent = LlmAgentBuilder::new("my-agent")
1426    ///     .model(model)
1427    ///     .generate_content_config(GenerateContentConfig {
1428    ///         temperature: Some(0.7),
1429    ///         max_output_tokens: Some(2048),
1430    ///         ..Default::default()
1431    ///     })
1432    ///     .build()?;
1433    /// ```
1434    pub fn generate_content_config(mut self, config: adk_core::GenerateContentConfig) -> Self {
1435        self.generate_content_config = Some(config);
1436        self
1437    }
1438
1439    /// Set the default temperature for LLM requests.
1440    /// Shorthand for setting just temperature without a full `GenerateContentConfig`.
1441    pub fn temperature(mut self, temperature: f32) -> Self {
1442        self.generate_content_config
1443            .get_or_insert(adk_core::GenerateContentConfig::default())
1444            .temperature = Some(temperature);
1445        self
1446    }
1447
1448    /// Set the default top_p for LLM requests.
1449    pub fn top_p(mut self, top_p: f32) -> Self {
1450        self.generate_content_config
1451            .get_or_insert(adk_core::GenerateContentConfig::default())
1452            .top_p = Some(top_p);
1453        self
1454    }
1455
1456    /// Set the default top_k for LLM requests.
1457    pub fn top_k(mut self, top_k: i32) -> Self {
1458        self.generate_content_config
1459            .get_or_insert(adk_core::GenerateContentConfig::default())
1460            .top_k = Some(top_k);
1461        self
1462    }
1463
1464    /// Set the default max output tokens for LLM requests.
1465    pub fn max_output_tokens(mut self, max_tokens: i32) -> Self {
1466        self.generate_content_config
1467            .get_or_insert(adk_core::GenerateContentConfig::default())
1468            .max_output_tokens = Some(max_tokens);
1469        self
1470    }
1471
1472    /// Set the maximum number of LLM round-trips (iterations) before the agent stops.
1473    /// Default is 100.
1474    pub fn max_iterations(mut self, max: u32) -> Self {
1475        self.max_iterations = max;
1476        self
1477    }
1478
1479    /// Set the timeout for individual tool executions.
1480    /// Default is 5 minutes. Tools that exceed this timeout will return an error.
1481    ///
1482    /// A tool whose [`Tool::timeout_override`] returns `Some` uses that instead,
1483    /// so an `AgentTool` delegation is bounded by its own timeout. A
1484    /// [`ToolEffect::NonIdempotent`] call that times out is answered with an
1485    /// [`outcome_unknown_response`](adk_core::outcome_unknown_response), because
1486    /// its side effect may already have happened.
1487    pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
1488        self.tool_timeout = timeout;
1489        self
1490    }
1491
1492    /// Sends the full message of a tool or tool-callback error to the model.
1493    ///
1494    /// By default a call that fails with an [`AdkError`](adk_core::AdkError) is answered with
1495    /// its component, category, and code only
1496    /// ([`tool_error_response`](adk_core::tool_error_response)), because the message can quote
1497    /// credentials, internal hosts, or upstream bodies, and the function response is sent to the
1498    /// model provider and stored in the session. The message is logged when
1499    /// [`RunConfig::record_payloads`](adk_core::RunConfig::record_payloads) is set. Errors with
1500    /// code [`TOOL_INVALID_ARGUMENTS_CODE`](adk_core::TOOL_INVALID_ARGUMENTS_CODE) always keep
1501    /// their message, as do timeouts, the agent's own refusals, and a tool's rejections
1502    /// ([`ErrorCategory::is_rejection`](adk_core::ErrorCategory::is_rejection)), cut at
1503    /// [`TOOL_ERROR_MESSAGE_LIMIT`](adk_core::TOOL_ERROR_MESSAGE_LIMIT) characters.
1504    ///
1505    /// Enable this only when every tool's error messages are safe to send to the provider. An
1506    /// [`on_tool_error`](Self::on_tool_error) callback chooses the text for one failure instead.
1507    ///
1508    /// # Example
1509    ///
1510    /// ```rust,ignore
1511    /// let agent = LlmAgentBuilder::new("support")
1512    ///     .model(model)
1513    ///     .tool(lookup_order)
1514    ///     .expose_tool_error_messages(true)
1515    ///     .build()?;
1516    /// ```
1517    pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
1518        self.expose_tool_error_messages = expose;
1519        self
1520    }
1521
1522    /// Add a tool to this agent's toolbox.
1523    ///
1524    /// The model calls tools by name, so each tool added here needs a name of
1525    /// its own: [`build`](Self::build) fails when two share one.
1526    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
1527        self.tools.push(tool);
1528        self
1529    }
1530
1531    /// Register a dynamic toolset for per-invocation tool resolution.
1532    ///
1533    /// Toolsets are resolved at the start of each `run()` call, and again after
1534    /// each round of tool calls, using the invocation's `ReadonlyContext`. This
1535    /// enables context-dependent tools like per-user browser sessions from a
1536    /// pool.
1537    ///
1538    /// A toolset whose `tools()` call fails is skipped for that resolution with
1539    /// a `warn`-level trace naming the toolset and the error, and the turn
1540    /// continues with the remaining tools. Use
1541    /// [`strict_toolsets`](Self::strict_toolsets) to fail the turn instead.
1542    pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
1543        self.toolsets.push(toolset);
1544        self
1545    }
1546
1547    /// Fail the turn when any toolset cannot resolve its tools.
1548    ///
1549    /// Off by default: a failing toolset, such as an MCP server that is down,
1550    /// is skipped and the model runs with the tools that did resolve. Turn this
1551    /// on when the agent must not run without every toolset, for example when
1552    /// a toolset supplies the only tools that can complete its task. It applies
1553    /// to toolsets registered here and to `RunConfig::runtime_toolsets`.
1554    /// Duplicate tool names fail the turn either way.
1555    ///
1556    /// # Example
1557    ///
1558    /// ```rust,ignore
1559    /// let agent = LlmAgentBuilder::new("operator")
1560    ///     .model(model)
1561    ///     .toolset(Arc::new(mcp_toolset))
1562    ///     .strict_toolsets(true)
1563    ///     .build()?;
1564    /// ```
1565    pub fn strict_toolsets(mut self, strict: bool) -> Self {
1566        self.strict_toolsets = strict;
1567        self
1568    }
1569
1570    /// Add a sub-agent that this agent can delegate to.
1571    pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
1572        self.sub_agents.push(agent);
1573        self
1574    }
1575
1576    /// Add a before-agent callback.
1577    pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
1578        self.before_callbacks.push(callback);
1579        self
1580    }
1581
1582    /// Add an after-agent callback.
1583    pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
1584        self.after_callbacks.push(callback);
1585        self
1586    }
1587
1588    /// Add a history processor that rewrites the agent's conversation history before each
1589    /// model request.
1590    ///
1591    /// Processors run before every model call of a turn, the first included, in the order
1592    /// added, each receiving the previous one's output. The result replaces the history the
1593    /// turn continues from: later steps append to it, so a compaction runs once and carries
1594    /// over to the rest of the turn. The session keeps every event, and the next turn builds
1595    /// its history from the session again.
1596    ///
1597    /// A processor receives the agent's own history: its instructions as `system` contents,
1598    /// the conversation, and the turn's calls and responses, including call IDs the agent
1599    /// generated for a provider that sent none. Toolsets, enhanced plugins, invocation hooks
1600    /// and [`before_model_callback`](Self::before_model_callback)s apply afterwards, to each
1601    /// request, and what they add never enters the history. A processor error ends the turn
1602    /// with that error.
1603    ///
1604    /// A before-model callback shapes one request; a history processor changes what the agent
1605    /// works from for the rest of the turn. A cut must keep every function response with its
1606    /// call: [`balanced_content_cut`](adk_core::history::balanced_content_cut) moves a cut
1607    /// back to the nearest point that does.
1608    ///
1609    /// # Example
1610    ///
1611    /// ```rust
1612    /// use adk_agent::LlmAgentBuilder;
1613    /// use adk_core::Content;
1614    /// use adk_core::history::balanced_content_cut;
1615    ///
1616    /// // Past 40 turns, replaces all but about the last 20 with a note. The cut moves earlier
1617    /// // when it would separate a function response from its call.
1618    /// let builder = LlmAgentBuilder::new("assistant").history_processor(Box::new(
1619    ///     |_ctx, history: Vec<Content>| {
1620    ///         Box::pin(async move {
1621    ///             let (system, turns): (Vec<_>, Vec<_>) =
1622    ///                 history.into_iter().partition(|content| content.role == "system");
1623    ///             if turns.len() <= 40 {
1624    ///                 return Ok(system.into_iter().chain(turns).collect());
1625    ///             }
1626    ///             let cut = balanced_content_cut(&turns, turns.len() - 20);
1627    ///             let note = Content::new("user")
1628    ///                 .with_text(format!("({cut} earlier turns were removed.)"));
1629    ///             Ok(system.into_iter().chain([note]).chain(turns.into_iter().skip(cut)).collect())
1630    ///         })
1631    ///     },
1632    /// ));
1633    /// # let _ = builder;
1634    /// ```
1635    pub fn history_processor(mut self, processor: adk_core::HistoryProcessor) -> Self {
1636        self.history_processors.push(processor);
1637        self
1638    }
1639
1640    /// Add a before-model callback invoked before each LLM request.
1641    pub fn before_model_callback(mut self, callback: BeforeModelCallback) -> Self {
1642        self.before_model_callbacks.push(callback);
1643        self
1644    }
1645
1646    /// Add an after-model callback invoked after each LLM response.
1647    pub fn after_model_callback(mut self, callback: AfterModelCallback) -> Self {
1648        self.after_model_callbacks.push(callback);
1649        self
1650    }
1651
1652    /// Add a before-tool callback invoked before each tool execution.
1653    pub fn before_tool_callback(mut self, callback: BeforeToolCallback) -> Self {
1654        self.before_tool_callbacks.push(callback);
1655        self
1656    }
1657
1658    /// Add an after-tool callback invoked after each tool execution.
1659    pub fn after_tool_callback(mut self, callback: AfterToolCallback) -> Self {
1660        self.after_tool_callbacks.push(callback);
1661        self
1662    }
1663
1664    /// Register a rich after-tool callback that receives the tool, arguments,
1665    /// and response value.
1666    ///
1667    /// This is the V2 callback surface aligned with the Python/Go ADK model
1668    /// where `after_tool_callback` receives the full tool execution context.
1669    /// Unlike [`after_tool_callback`](Self::after_tool_callback) (which only
1670    /// receives `CallbackContext`), this callback can inspect and modify tool
1671    /// results directly.
1672    ///
1673    /// Return `Ok(None)` to keep the original response, or `Ok(Some(value))`
1674    /// to replace the function response sent to the LLM.
1675    ///
1676    /// These callbacks run after the legacy `after_tool_callback` chain.
1677    /// `ToolOutcome` is available via `ctx.tool_outcome()`.
1678    pub fn after_tool_callback_full(mut self, callback: AfterToolCallbackFull) -> Self {
1679        self.after_tool_callbacks_full.push(callback);
1680        self
1681    }
1682
1683    /// Register a callback invoked when a tool execution fails
1684    /// (after retries are exhausted).
1685    ///
1686    /// The callback receives the error's full message, and
1687    /// `ctx.tool_outcome()` carries the structured error in
1688    /// [`ToolOutcome::error`](adk_core::ToolOutcome::error).
1689    /// If the callback returns `Ok(Some(value))`, the value is used as a
1690    /// fallback function response to the LLM. If it returns `Ok(None)`,
1691    /// the next callback in the chain is tried. If no callback provides a
1692    /// fallback, the LLM receives
1693    /// [`tool_error_response`](adk_core::tool_error_response), which omits the message unless
1694    /// [`expose_tool_error_messages`](Self::expose_tool_error_messages) is set.
1695    pub fn on_tool_error(mut self, callback: OnToolErrorCallback) -> Self {
1696        self.on_tool_error_callbacks.push(callback);
1697        self
1698    }
1699
1700    /// Set a default retry budget applied to all tools that do not have
1701    /// a per-tool override.
1702    ///
1703    /// When a tool execution fails and a retry budget applies, the agent
1704    /// retries up to `budget.max_retries` times, with the backoff described on
1705    /// [`RetryBudget::backoff_delay`]. Only a tool whose [`Tool::effect`] is
1706    /// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] is retried, and
1707    /// only after a retryable error or a timeout. Each attempt gets a fresh tool
1708    /// context, so a retried attempt's state delta and escalation are discarded.
1709    pub fn default_retry_budget(mut self, budget: RetryBudget) -> Self {
1710        self.default_retry_budget = Some(budget);
1711        self
1712    }
1713
1714    /// Set a per-tool retry budget that overrides the default for the
1715    /// named tool.
1716    ///
1717    /// Per-tool budgets take precedence over the default retry budget.
1718    pub fn tool_retry_budget(mut self, tool_name: impl Into<String>, budget: RetryBudget) -> Self {
1719        self.tool_retry_budgets.insert(tool_name.into(), budget);
1720        self
1721    }
1722
1723    /// Configure a circuit breaker that temporarily disables tools after
1724    /// `threshold` consecutive failures within a single invocation.
1725    ///
1726    /// When a tool's consecutive failure count reaches the threshold, subsequent
1727    /// calls to that tool are short-circuited with an immediate error response
1728    /// until the next invocation (which resets the state).
1729    pub fn circuit_breaker_threshold(mut self, threshold: u32) -> Self {
1730        self.circuit_breaker_threshold = Some(threshold);
1731        self
1732    }
1733
1734    /// Configure tool confirmation requirements for this agent.
1735    ///
1736    /// The effective requirement is the union of this policy and
1737    /// [`InvocationContext::requires_tool_confirmation`], so a runtime-injected requirement
1738    /// (for example a team relationship with required approval) still pauses the call when
1739    /// no decision exists and blocks it when the decision is
1740    /// [`ToolConfirmationDecision::Deny`](adk_core::ToolConfirmationDecision::Deny).
1741    pub fn tool_confirmation_policy(mut self, policy: ToolConfirmationPolicy) -> Self {
1742        self.tool_confirmation_policy = policy;
1743        self
1744    }
1745
1746    /// Require confirmation for a specific tool name.
1747    pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
1748        self.tool_confirmation_policy = self.tool_confirmation_policy.with_tool(tool_name);
1749        self
1750    }
1751
1752    /// Require confirmation for all tool calls.
1753    pub fn require_tool_confirmation_for_all(mut self) -> Self {
1754        self.tool_confirmation_policy = ToolConfirmationPolicy::Always;
1755        self
1756    }
1757
1758    /// Set the tool execution strategy for this agent.
1759    ///
1760    /// Without it, the agent dispatches with [`ToolExecutionStrategy::Sequential`].
1761    /// [`ToolExecutionStrategy::Parallel`] is an explicit override that bypasses
1762    /// tool safety metadata, so the caller owns concurrency safety.
1763    pub fn tool_execution_strategy(mut self, strategy: ToolExecutionStrategy) -> Self {
1764        self.tool_execution_strategy = Some(strategy);
1765        self
1766    }
1767
1768    /// Allow consecutive agent-delegation calls to execute concurrently.
1769    ///
1770    /// Ordinary tools remain sequential and retain their position relative to
1771    /// each delegation batch. This setting takes precedence over the general
1772    /// tool execution strategy for the agent.
1773    pub fn parallelize_agent_delegations(mut self, parallelize: bool) -> Self {
1774        self.parallelize_agent_delegations = parallelize;
1775        self
1776    }
1777
1778    /// Set input guardrails to validate user input before processing.
1779    ///
1780    /// Input guardrails run before the agent processes the request and can:
1781    /// - Block harmful or off-topic content
1782    /// - Redact PII from user input
1783    /// - Enforce input length limits
1784    ///
1785    /// Requires the `guardrails` feature.
1786    pub fn input_guardrails(mut self, guardrails: GuardrailSet) -> Self {
1787        self.input_guardrails = guardrails;
1788        self
1789    }
1790
1791    /// Set output guardrails to validate agent responses.
1792    ///
1793    /// Output guardrails run after the agent generates a response and can:
1794    /// - Enforce JSON schema compliance
1795    /// - Redact PII from responses
1796    /// - Block harmful content in responses
1797    ///
1798    /// They screen every model turn before the client or the session sees it: the final
1799    /// response through `Guardrail::validate`, and the text of a turn that also calls tools, or
1800    /// that the provider paused, through `Guardrail::validate_preamble`, so a transform
1801    /// rewrites that text and keeps the calls. A block ends the run with an `InvalidInput`
1802    /// error coded `guardrail.output_blocked`, and the blocked turn's calls do not run. A
1803    /// tool result that ends the turn is screened too. With output guardrails set, an `SSE`
1804    /// or `Bidi` run delivers each model turn as one event.
1805    ///
1806    /// Requires the `guardrails` feature.
1807    pub fn output_guardrails(mut self, guardrails: GuardrailSet) -> Self {
1808        self.output_guardrails = guardrails;
1809        self
1810    }
1811
1812    /// Set guardrails that screen tool calls before they execute.
1813    ///
1814    /// [`GuardrailSet`] validates `Content` and never sees a tool call, and
1815    /// [`ToolConfirmationPolicy`] decides per tool *name*. Neither can express "this tool may run,
1816    /// but not with these arguments". A [`ToolGuardrailSet`] receives the tool name and the
1817    /// arguments and may allow, deny, or narrow them.
1818    ///
1819    /// Screening runs on the call's final arguments, after plugin and callback rewrites and the
1820    /// run's [`ToolPolicy`](adk_core::ToolPolicy), and before confirmation is resolved, so a
1821    /// denied call neither prompts the user nor consumes a concurrency permit. A denial is
1822    /// reported to the model as the tool's result, letting it correct the call rather than
1823    /// stalling the run.
1824    ///
1825    /// The set also screens each call's result (`ToolGuardrail::validate_result`) after the
1826    /// after-tool callbacks and plugins, before the model, the client, or the session sees it:
1827    /// a revision replaces the result, and a withheld result is answered with
1828    /// [`result_blocked_response`](adk_core::result_blocked_response).
1829    ///
1830    /// Requires the `guardrails` feature.
1831    ///
1832    /// # Example
1833    ///
1834    /// ```rust,ignore
1835    /// use adk_agent::guardrails::{PathAllowList, ToolGuardrailSet};
1836    ///
1837    /// let agent = LlmAgentBuilder::new("ops")
1838    ///     .tool_guardrails(ToolGuardrailSet::new().with(
1839    ///         PathAllowList::new("agents-only", ["path"], ["/Users/me/Library/LaunchAgents"])
1840    ///             .on_tools(["plist_write"]),
1841    ///     ))
1842    ///     .build()?;
1843    /// ```
1844    pub fn tool_guardrails(mut self, guardrails: ToolGuardrailSet) -> Self {
1845        self.tool_guardrails = guardrails;
1846        self
1847    }
1848
1849    /// Register a single enhanced plugin for fine-grained tool/model call interception.
1850    ///
1851    /// Enhanced plugins can inspect and modify tool arguments, tool results,
1852    /// model requests, and model responses. They execute in priority order
1853    /// (lower priority values execute first).
1854    ///
1855    /// Requires the `enhanced-plugins` feature.
1856    ///
1857    /// # Example
1858    ///
1859    /// ```rust,ignore
1860    /// use std::sync::Arc;
1861    /// use adk_plugin::EnhancedPlugin;
1862    ///
1863    /// let agent = LlmAgentBuilder::new("my-agent")
1864    ///     .model(model)
1865    ///     .enhanced_plugin(Arc::new(MyPlugin::new()))
1866    ///     .build()?;
1867    /// ```
1868    #[cfg(feature = "enhanced-plugins")]
1869    pub fn enhanced_plugin(mut self, plugin: Arc<dyn EnhancedPlugin>) -> Self {
1870        self.enhanced_plugins.push(plugin);
1871        self
1872    }
1873
1874    /// Register multiple enhanced plugins at once.
1875    ///
1876    /// Plugins are sorted by priority when the agent is built. Lower priority
1877    /// values execute first. Same-priority plugins execute in registration order.
1878    ///
1879    /// Requires the `enhanced-plugins` feature.
1880    ///
1881    /// # Example
1882    ///
1883    /// ```rust,ignore
1884    /// use std::sync::Arc;
1885    /// use adk_plugin::EnhancedPlugin;
1886    ///
1887    /// let agent = LlmAgentBuilder::new("my-agent")
1888    ///     .model(model)
1889    ///     .enhanced_plugins(vec![
1890    ///         Arc::new(SecurityPlugin::new()),  // priority = 10
1891    ///         Arc::new(LoggingPlugin::new()),   // priority = 100
1892    ///     ])
1893    ///     .build()?;
1894    /// ```
1895    #[cfg(feature = "enhanced-plugins")]
1896    pub fn enhanced_plugins(mut self, plugins: Vec<Arc<dyn EnhancedPlugin>>) -> Self {
1897        self.enhanced_plugins.extend(plugins);
1898        self
1899    }
1900
1901    /// Attach a sandbox configuration for workspace lifecycle management.
1902    ///
1903    /// When a `SandboxConfig` is attached, the `SandboxRunner` will provision
1904    /// a workspace, bind tools based on enabled capabilities, and manage the
1905    /// session lifecycle. The config does NOT add tools directly to the agent —
1906    /// tool binding is the responsibility of the `SandboxRunner`.
1907    ///
1908    /// When no `SandboxConfig` is attached, the agent behaves identically to
1909    /// its behavior before this feature was introduced.
1910    ///
1911    /// Requires the `sandbox` feature.
1912    ///
1913    /// # Example
1914    ///
1915    /// ```rust,ignore
1916    /// use adk_sandbox::workspace::{SandboxConfig, Capability, Manifest};
1917    /// use std::collections::HashSet;
1918    /// use std::sync::Arc;
1919    /// use std::time::Duration;
1920    ///
1921    /// let config = SandboxConfig {
1922    ///     client: Arc::new(my_client),
1923    ///     manifest: Manifest { entries: vec![] },
1924    ///     capabilities: HashSet::from([Capability::Shell, Capability::Filesystem]),
1925    ///     snapshot_on_stop: true,
1926    ///     session_timeout: Duration::from_secs(600),
1927    ///     command_timeout: Duration::from_secs(120),
1928    /// };
1929    ///
1930    /// let agent = LlmAgentBuilder::new("coding-agent")
1931    ///     .model(model)
1932    ///     .sandbox_config(config)
1933    ///     .build()?;
1934    /// ```
1935    #[cfg(feature = "sandbox")]
1936    pub fn sandbox_config(mut self, config: adk_sandbox::workspace::SandboxConfig) -> Self {
1937        self.sandbox_config = Some(config);
1938        self
1939    }
1940
1941    /// Build the [`LlmAgent`].
1942    ///
1943    /// # Errors
1944    ///
1945    /// Returns an error when no model was set, when two sub-agents share a
1946    /// name, or when two tools added with [`tool`](Self::tool) share a name
1947    /// (code `agent.duplicate_tool_name`).
1948    pub fn build(self) -> Result<LlmAgent> {
1949        let model = self.model.ok_or_else(|| adk_core::AdkError::agent("Model is required"))?;
1950
1951        let mut seen_names = std::collections::HashSet::new();
1952        for agent in &self.sub_agents {
1953            if !seen_names.insert(agent.name()) {
1954                return Err(adk_core::AdkError::agent(format!(
1955                    "Duplicate sub-agent name: {}",
1956                    agent.name()
1957                )));
1958            }
1959        }
1960        adk_core::ensure_unique_tool_names(&self.name, &self.tools)?;
1961
1962        // Validate: Gemini Interactions API + client-side sandbox tools conflict.
1963        // These provide competing filesystems and would produce nondeterministic behavior.
1964        #[cfg(feature = "sandbox")]
1965        if let Some(ref sandbox_cfg) = self.sandbox_config {
1966            use adk_sandbox::workspace::Capability;
1967            if model.uses_interactions_api()
1968                && (sandbox_cfg.capabilities.contains(&Capability::Shell)
1969                    || sandbox_cfg.capabilities.contains(&Capability::Filesystem))
1970            {
1971                return Err(adk_core::AdkError::new(
1972                    adk_core::ErrorComponent::Agent,
1973                    adk_core::ErrorCategory::InvalidInput,
1974                    "code.gemini_interactions_conflict",
1975                    "Cannot combine Gemini Interactions API (server-managed environment) \
1976                     with client-side sandbox tools (Shell/Filesystem). These provide \
1977                     competing filesystems and would produce nondeterministic behavior. \
1978                     Either disable use_interactions_api or remove sandbox capabilities.",
1979                ));
1980            }
1981        }
1982
1983        // Construct EnhancedPluginManager only when plugins are registered (zero overhead otherwise)
1984        #[cfg(feature = "enhanced-plugins")]
1985        let enhanced_plugin_manager = if self.enhanced_plugins.is_empty() {
1986            None
1987        } else {
1988            Some(Arc::new(EnhancedPluginManager::new(self.enhanced_plugins)))
1989        };
1990
1991        Ok(LlmAgent {
1992            name: self.name,
1993            description: self.description.unwrap_or_default(),
1994            model,
1995            instruction: self.instruction,
1996            instruction_provider: self.instruction_provider,
1997            static_instruction: self.static_instruction,
1998            global_instruction: self.global_instruction,
1999            global_instruction_provider: self.global_instruction_provider,
2000            skills_index: self.skills_index,
2001            skill_policy: self.skill_policy,
2002            max_skill_chars: self.max_skill_chars,
2003            input_schema: self.input_schema,
2004            output_schema: self.output_schema,
2005            output_max_retries: self.output_max_retries,
2006            disallow_transfer_to_parent: self.disallow_transfer_to_parent,
2007            disallow_transfer_to_peers: self.disallow_transfer_to_peers,
2008            include_contents: self.include_contents,
2009            tools: self.tools,
2010            toolsets: self.toolsets,
2011            strict_toolsets: self.strict_toolsets,
2012            sub_agents: self.sub_agents,
2013            output_key: self.output_key,
2014            generate_content_config: self.generate_content_config,
2015            max_iterations: self.max_iterations,
2016            tool_timeout: self.tool_timeout,
2017            expose_tool_error_messages: self.expose_tool_error_messages,
2018            before_callbacks: Arc::new(self.before_callbacks),
2019            after_callbacks: Arc::new(self.after_callbacks),
2020            history_processors: Arc::new(self.history_processors),
2021            before_model_callbacks: Arc::new(self.before_model_callbacks),
2022            after_model_callbacks: Arc::new(self.after_model_callbacks),
2023            before_tool_callbacks: Arc::new(self.before_tool_callbacks),
2024            after_tool_callbacks: Arc::new(self.after_tool_callbacks),
2025            on_tool_error_callbacks: Arc::new(self.on_tool_error_callbacks),
2026            after_tool_callbacks_full: Arc::new(self.after_tool_callbacks_full),
2027            default_retry_budget: self.default_retry_budget,
2028            tool_retry_budgets: self.tool_retry_budgets,
2029            circuit_breaker_threshold: self.circuit_breaker_threshold,
2030            tool_confirmation_policy: self.tool_confirmation_policy,
2031            tool_execution_strategy: self.tool_execution_strategy,
2032            parallelize_agent_delegations: self.parallelize_agent_delegations,
2033            input_guardrails: Arc::new(self.input_guardrails),
2034            output_guardrails: Arc::new(self.output_guardrails),
2035            tool_guardrails: Arc::new(self.tool_guardrails),
2036            #[cfg(feature = "enhanced-plugins")]
2037            enhanced_plugin_manager,
2038            #[cfg(feature = "sandbox")]
2039            sandbox_config: self.sandbox_config,
2040        })
2041    }
2042}
2043
2044// AgentToolContext wraps the parent InvocationContext and preserves all context
2045// instead of throwing it away like SimpleToolContext did
2046/// Progress events held in flight for one tool batch.
2047///
2048/// The queue exists to decouple a tool that writes progress from a client that
2049/// reads it. It is bounded so a verbose tool cannot grow the queue without limit
2050/// while the consumer is slow.
2051const TOOL_PROGRESS_CAPACITY: usize = 256;
2052
2053/// How long a tool waits for queue space before its chunk is dropped.
2054///
2055/// A short wait applies real backpressure to a tool that outruns its consumer,
2056/// without letting a stalled consumer block the tool indefinitely.
2057const TOOL_PROGRESS_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);
2058
2059/// Largest single progress chunk forwarded, in bytes.
2060const TOOL_PROGRESS_MAX_CHUNK_BYTES: usize = 8 * 1024;
2061
2062/// Total progress bytes forwarded for one tool call.
2063const TOOL_PROGRESS_MAX_TOTAL_BYTES: usize = 1024 * 1024;
2064
2065/// Text appended in place of progress output that was not forwarded.
2066const TOOL_PROGRESS_TRUNCATION_MARKER: &str = "[adk: tool progress truncated]";
2067
2068/// Progress stream that carries the marker for dropped forwarded events.
2069const FORWARDED_EVENTS_STREAM: &str = "events";
2070
2071/// Text emitted once, ahead of the next forwarded event, after a tool's forwarded partial
2072/// events were dropped.
2073const FORWARDED_EVENTS_DROPPED_MARKER: &str = "[adk: forwarded events dropped]";
2074
2075/// Markers that found the progress queue full, delivered by the dispatch loop after the
2076/// queued events.
2077type ProgressOverflow = Arc<std::sync::Mutex<Vec<Event>>>;
2078
2079/// Queues `marker`, keeping it in `overflow` when the queue is full: a marker reports a
2080/// backlog, so the full queue is exactly when it must not be dropped.
2081fn send_marker(tx: &tokio::sync::mpsc::Sender<Event>, overflow: &ProgressOverflow, marker: Event) {
2082    if let Err(tokio::sync::mpsc::error::TrySendError::Full(marker)) = tx.try_send(marker) {
2083        overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(marker);
2084    }
2085}
2086
2087/// Truncates `text` to at most `max_bytes`, never splitting a character.
2088fn truncate_on_char_boundary(text: &str, max_bytes: usize) -> &str {
2089    if text.len() <= max_bytes {
2090        return text;
2091    }
2092    let mut end = max_bytes;
2093    while end > 0 && !text.is_char_boundary(end) {
2094        end -= 1;
2095    }
2096    &text[..end]
2097}
2098
2099struct AgentToolContext {
2100    parent_ctx: Arc<dyn InvocationContext>,
2101    function_call_id: String,
2102    /// The tool this context was built for, recorded by the dispatcher so secret
2103    /// requests carry an identity the tool cannot choose.
2104    tool_name: Option<String>,
2105    /// The key of the held call this context resumes, shared by every run that resumes
2106    /// it; `None` for a call made in this invocation (spec 3.1 §7.12).
2107    idempotency_key: Option<String>,
2108    /// The names of the calling agent's tools, recorded by the dispatcher.
2109    agent_tools: Option<Vec<String>>,
2110    actions: Mutex<EventActions>,
2111    progress_tx: Option<tokio::sync::mpsc::Sender<Event>>,
2112    /// Where a marker goes when the progress queue is full.
2113    progress_overflow: ProgressOverflow,
2114    /// Progress bytes forwarded so far for this call.
2115    progress_bytes: std::sync::atomic::AtomicUsize,
2116    /// Set once the truncation marker has been emitted, so it is emitted once.
2117    progress_truncated: std::sync::atomic::AtomicBool,
2118    /// Forwarded partial events dropped because the consumer did not keep up.
2119    events_dropped: std::sync::atomic::AtomicUsize,
2120    /// Set once the marker for dropped forwarded events has been sent.
2121    events_drop_marked: std::sync::atomic::AtomicBool,
2122}
2123
2124impl Drop for AgentToolContext {
2125    fn drop(&mut self) {
2126        let dropped = *self.events_dropped.get_mut();
2127        if dropped == 0 {
2128            return;
2129        }
2130        tracing::warn!(
2131            function_call.id = %self.function_call_id,
2132            events.dropped = dropped,
2133            "forwarded partial events were dropped for this tool call"
2134        );
2135        if !*self.events_drop_marked.get_mut()
2136            && let Some(tx) = &self.progress_tx
2137        {
2138            send_marker(tx, &self.progress_overflow, self.events_dropped_marker());
2139        }
2140    }
2141}
2142
2143impl AgentToolContext {
2144    fn new(parent_ctx: Arc<dyn InvocationContext>, function_call_id: String) -> Self {
2145        Self {
2146            parent_ctx,
2147            function_call_id,
2148            tool_name: None,
2149            idempotency_key: None,
2150            agent_tools: None,
2151            actions: Mutex::new(EventActions::default()),
2152            progress_tx: None,
2153            progress_overflow: ProgressOverflow::default(),
2154            progress_bytes: std::sync::atomic::AtomicUsize::new(0),
2155            progress_truncated: std::sync::atomic::AtomicBool::new(false),
2156            events_dropped: std::sync::atomic::AtomicUsize::new(0),
2157            events_drop_marked: std::sync::atomic::AtomicBool::new(false),
2158        }
2159    }
2160
2161    /// Record which tool this context serves.
2162    fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
2163        self.tool_name = Some(tool_name.into());
2164        self
2165    }
2166
2167    /// Keys the call by `key` instead of this invocation and its call ID.
2168    fn with_idempotency_key(mut self, key: Option<String>) -> Self {
2169        self.idempotency_key = key;
2170        self
2171    }
2172
2173    /// Record the names of the calling agent's tools.
2174    fn with_agent_tools(mut self, tools: impl IntoIterator<Item = String>) -> Self {
2175        self.agent_tools = Some(tools.into_iter().collect());
2176        self
2177    }
2178
2179    /// Attach a progress sink so [`ToolContext::emit_progress`] forwards chunks
2180    /// as partial [`Event`]s onto the agent's `EventStream`.
2181    fn with_progress(
2182        mut self,
2183        tx: tokio::sync::mpsc::Sender<Event>,
2184        overflow: ProgressOverflow,
2185    ) -> Self {
2186        self.progress_tx = Some(tx);
2187        self.progress_overflow = overflow;
2188        self
2189    }
2190
2191    /// Builds a described secret access from the identity the framework holds.
2192    ///
2193    /// The tool name comes from the dispatch record rather than from anything the tool
2194    /// supplied, so one tool cannot request a secret under another tool's identity.
2195    async fn request_secret(&self, name: &str, purpose: Option<&str>) -> Result<Option<String>> {
2196        let mut request = adk_core::SecretRequest::new(name)
2197            .with_identity(
2198                self.parent_ctx.app_name(),
2199                self.parent_ctx.user_id(),
2200                self.parent_ctx.session_id(),
2201            )
2202            .with_invocation_id(self.parent_ctx.invocation_id());
2203        if let Some(tool_name) = &self.tool_name {
2204            request = request.with_tool_name(tool_name);
2205        }
2206        if let Some(purpose) = purpose {
2207            request = request.with_purpose(purpose);
2208        }
2209        self.parent_ctx.get_secret_for(&request).await
2210    }
2211
2212    /// Forwards one progress chunk under this call's budget.
2213    ///
2214    /// The policy is bounded and lossy by design: memory is capped, and output that
2215    /// does not fit is replaced by a single truncation marker rather than stalling
2216    /// the tool or growing without limit. A tool that outruns its consumer waits
2217    /// briefly, which slows the tool rather than the whole run.
2218    async fn forward_progress(
2219        &self,
2220        tx: &tokio::sync::mpsc::Sender<Event>,
2221        stream: &str,
2222        chunk: &str,
2223    ) {
2224        use std::sync::atomic::Ordering;
2225
2226        if self.progress_truncated.load(Ordering::Relaxed) {
2227            return;
2228        }
2229
2230        // Cap one chunk, then cap the call. Truncation respects char boundaries so
2231        // multi-byte text is never split mid-character.
2232        let payload = truncate_on_char_boundary(chunk, TOOL_PROGRESS_MAX_CHUNK_BYTES);
2233        let forwarded = self.progress_bytes.fetch_add(payload.len(), Ordering::Relaxed);
2234        if forwarded.saturating_add(payload.len()) > TOOL_PROGRESS_MAX_TOTAL_BYTES {
2235            self.mark_progress_truncated(tx, stream).await;
2236            return;
2237        }
2238
2239        let event = Event::tool_progress(
2240            self.parent_ctx.invocation_id(),
2241            self.parent_ctx.agent_name(),
2242            &self.function_call_id,
2243            stream,
2244            payload,
2245        );
2246
2247        match tx.try_send(event) {
2248            Ok(()) => {}
2249            Err(tokio::sync::mpsc::error::TrySendError::Full(event)) => {
2250                // Wait briefly for the consumer to catch up, then give up on this
2251                // chunk so a stalled consumer cannot block the tool.
2252                match tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await {
2253                    Ok(Ok(())) => {}
2254                    Ok(Err(_)) => {}
2255                    Err(_) => self.mark_progress_truncated(tx, stream).await,
2256                }
2257            }
2258            Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {}
2259        }
2260    }
2261
2262    /// The marker that stands in for forwarded partial events this call dropped.
2263    fn events_dropped_marker(&self) -> Event {
2264        Event::tool_progress(
2265            self.parent_ctx.invocation_id(),
2266            self.parent_ctx.agent_name(),
2267            &self.function_call_id,
2268            FORWARDED_EVENTS_STREAM,
2269            FORWARDED_EVENTS_DROPPED_MARKER,
2270        )
2271    }
2272
2273    /// Emits the truncation marker once for this call.
2274    async fn mark_progress_truncated(&self, tx: &tokio::sync::mpsc::Sender<Event>, stream: &str) {
2275        use std::sync::atomic::Ordering;
2276        if self.progress_truncated.swap(true, Ordering::Relaxed) {
2277            return;
2278        }
2279        tracing::warn!(
2280            function_call.id = %self.function_call_id,
2281            progress.stream = %stream,
2282            "tool progress exceeded its budget, remaining output is not forwarded"
2283        );
2284        let marker = Event::tool_progress(
2285            self.parent_ctx.invocation_id(),
2286            self.parent_ctx.agent_name(),
2287            &self.function_call_id,
2288            stream,
2289            TOOL_PROGRESS_TRUNCATION_MARKER,
2290        );
2291        send_marker(tx, &self.progress_overflow, marker);
2292    }
2293
2294    fn actions_guard(&self) -> std::sync::MutexGuard<'_, EventActions> {
2295        self.actions.lock().unwrap_or_else(|e| e.into_inner())
2296    }
2297}
2298
2299#[async_trait]
2300impl ReadonlyContext for AgentToolContext {
2301    fn invocation_id(&self) -> &str {
2302        self.parent_ctx.invocation_id()
2303    }
2304
2305    fn agent_name(&self) -> &str {
2306        self.parent_ctx.agent_name()
2307    }
2308
2309    fn user_id(&self) -> &str {
2310        // ✅ Delegate to parent - now tools get the real user_id!
2311        self.parent_ctx.user_id()
2312    }
2313
2314    fn app_name(&self) -> &str {
2315        // ✅ Delegate to parent - now tools get the real app_name!
2316        self.parent_ctx.app_name()
2317    }
2318
2319    fn session_id(&self) -> &str {
2320        // ✅ Delegate to parent - now tools get the real session_id!
2321        self.parent_ctx.session_id()
2322    }
2323
2324    fn branch(&self) -> &str {
2325        self.parent_ctx.branch()
2326    }
2327
2328    fn user_content(&self) -> &Content {
2329        self.parent_ctx.user_content()
2330    }
2331
2332    fn acting_context(&self) -> adk_core::ActingContext {
2333        self.parent_ctx.acting_context()
2334    }
2335
2336    fn is_authenticated(&self) -> bool {
2337        self.parent_ctx.is_authenticated()
2338    }
2339}
2340
2341#[async_trait]
2342impl CallbackContext for AgentToolContext {
2343    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2344        // ✅ Delegate to parent - tools can now access artifacts!
2345        self.parent_ctx.artifacts()
2346    }
2347
2348    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2349        self.parent_ctx.shared_state()
2350    }
2351}
2352
2353#[async_trait]
2354impl ToolContext for AgentToolContext {
2355    fn function_call_id(&self) -> &str {
2356        &self.function_call_id
2357    }
2358
2359    fn agent_tool_names(&self) -> Option<Vec<String>> {
2360        self.agent_tools.clone()
2361    }
2362
2363    /// A resumed held call keeps the key it was first dispatched under, so a payment or
2364    /// another downstream idempotency key is the same in every run that resumes it
2365    /// (spec 3.1 §7.12). Any other call uses the trait's default form.
2366    fn idempotency_key(&self) -> String {
2367        self.idempotency_key.clone().unwrap_or_else(|| {
2368            format!(
2369                "{}/{}/{}/{}/{}",
2370                self.app_name(),
2371                self.user_id(),
2372                self.session_id(),
2373                self.invocation_id(),
2374                self.function_call_id
2375            )
2376        })
2377    }
2378
2379    fn actions(&self) -> EventActions {
2380        self.actions_guard().clone()
2381    }
2382
2383    fn set_actions(&self, actions: EventActions) {
2384        *self.actions_guard() = actions;
2385    }
2386
2387    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>> {
2388        // ✅ Delegate to parent's memory if available
2389        if let Some(memory) = self.parent_ctx.memory() {
2390            memory.search(query).await
2391        } else {
2392            Ok(vec![])
2393        }
2394    }
2395
2396    fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
2397        self.parent_ctx.memory()
2398    }
2399
2400    fn session(&self) -> Option<&dyn adk_core::Session> {
2401        Some(self.parent_ctx.session())
2402    }
2403
2404    fn run_config(&self) -> Option<&adk_core::RunConfig> {
2405        Some(self.parent_ctx.run_config())
2406    }
2407
2408    fn is_cancelled(&self) -> bool {
2409        self.parent_ctx.is_cancelled()
2410    }
2411
2412    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
2413        self.parent_ctx.request_metadata()
2414    }
2415
2416    fn delegation_depth(&self) -> u32 {
2417        self.parent_ctx.delegation_depth()
2418    }
2419
2420    fn max_delegation_depth(&self) -> Option<u32> {
2421        self.parent_ctx.max_delegation_depth()
2422    }
2423
2424    fn orchestration_root_invocation_id(&self) -> &str {
2425        self.parent_ctx.orchestration_root_invocation_id()
2426    }
2427
2428    fn orchestration_edge_id(&self) -> Option<&str> {
2429        self.parent_ctx.orchestration_edge_id()
2430    }
2431
2432    async fn emit_event(&self, event: Event) {
2433        use std::sync::atomic::Ordering;
2434
2435        let Some(tx) = &self.progress_tx else {
2436            return;
2437        };
2438        if tx.is_closed() {
2439            return;
2440        }
2441        // A complete event becomes session history, so it waits for the consumer as a tool
2442        // result does. Only a partial event, which is never persisted, may be dropped.
2443        if !event.llm_response.partial {
2444            let _ = tx.send(event).await;
2445            return;
2446        }
2447        // A consumer that missed partial events is told so before the next one reaches it.
2448        if self.events_dropped.load(Ordering::Relaxed) > 0
2449            && !self.events_drop_marked.load(Ordering::Relaxed)
2450            && tokio::time::timeout(
2451                TOOL_PROGRESS_SEND_TIMEOUT,
2452                tx.send(self.events_dropped_marker()),
2453            )
2454            .await
2455            .is_ok_and(|sent| sent.is_ok())
2456        {
2457            self.events_drop_marked.store(true, Ordering::Relaxed);
2458        }
2459        if tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await.is_ok() {
2460            return;
2461        }
2462        if self.events_dropped.fetch_add(1, Ordering::Relaxed) == 0 {
2463            tracing::warn!(
2464                function_call.id = %self.function_call_id,
2465                "consumer is not keeping up; forwarded partial events are being dropped"
2466            );
2467        }
2468    }
2469
2470    fn user_scopes(&self) -> Vec<String> {
2471        self.parent_ctx.user_scopes()
2472    }
2473
2474    async fn get_secret(&self, name: &str) -> Result<Option<String>> {
2475        self.request_secret(name, None).await
2476    }
2477
2478    async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
2479        self.request_secret(name, Some(purpose)).await
2480    }
2481
2482    async fn emit_progress(&self, stream: &str, chunk: &str) {
2483        // Primary path: forward as a partial Event on the agent's EventStream so
2484        // UIs consume tool progress through the same channel as everything else.
2485        if let Some(tx) = &self.progress_tx {
2486            // A closed receiver means nobody is listening, so stop building events.
2487            if !tx.is_closed() {
2488                self.forward_progress(tx, stream, chunk).await;
2489            }
2490        }
2491        // Secondary path: structured trace for log-based observability.
2492        tracing::debug!(
2493            target: "adk_agent::tool_progress",
2494            tool_call_id = %self.function_call_id,
2495            stream = %stream,
2496            "{chunk}",
2497        );
2498    }
2499}
2500
2501/// Wrapper that adds ToolOutcome to an existing CallbackContext.
2502/// Used only during after-tool callback invocation so callbacks
2503/// can inspect structured metadata about the completed tool execution.
2504struct ToolOutcomeCallbackContext {
2505    inner: Arc<dyn CallbackContext>,
2506    outcome: ToolOutcome,
2507}
2508
2509#[async_trait]
2510impl ReadonlyContext for ToolOutcomeCallbackContext {
2511    fn invocation_id(&self) -> &str {
2512        self.inner.invocation_id()
2513    }
2514
2515    fn agent_name(&self) -> &str {
2516        self.inner.agent_name()
2517    }
2518
2519    fn user_id(&self) -> &str {
2520        self.inner.user_id()
2521    }
2522
2523    fn app_name(&self) -> &str {
2524        self.inner.app_name()
2525    }
2526
2527    fn session_id(&self) -> &str {
2528        self.inner.session_id()
2529    }
2530
2531    fn branch(&self) -> &str {
2532        self.inner.branch()
2533    }
2534
2535    fn user_content(&self) -> &Content {
2536        self.inner.user_content()
2537    }
2538
2539    fn acting_context(&self) -> adk_core::ActingContext {
2540        self.inner.acting_context()
2541    }
2542
2543    fn is_authenticated(&self) -> bool {
2544        self.inner.is_authenticated()
2545    }
2546}
2547
2548#[async_trait]
2549impl CallbackContext for ToolOutcomeCallbackContext {
2550    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2551        self.inner.artifacts()
2552    }
2553
2554    fn tool_outcome(&self) -> Option<ToolOutcome> {
2555        Some(self.outcome.clone())
2556    }
2557
2558    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2559        self.inner.shared_state()
2560    }
2561}
2562
2563/// Per-invocation circuit breaker state.
2564///
2565/// Tracks consecutive failures per tool name within a single agent
2566/// invocation. When a tool's consecutive failure count reaches the
2567/// configured threshold the breaker "opens" and subsequent calls to
2568/// that tool are short-circuited with an immediate error response.
2569///
2570/// The state is created fresh at the start of each `run()` call so
2571/// it automatically resets between invocations.
2572struct CircuitBreakerState {
2573    threshold: u32,
2574    /// tool_name → consecutive failure count
2575    failures: std::collections::HashMap<String, u32>,
2576}
2577
2578impl CircuitBreakerState {
2579    fn new(threshold: u32) -> Self {
2580        Self { threshold, failures: std::collections::HashMap::new() }
2581    }
2582
2583    /// Returns `true` if the tool is currently tripped (open state).
2584    fn is_open(&self, tool_name: &str) -> bool {
2585        self.failures.get(tool_name).copied().unwrap_or(0) >= self.threshold
2586    }
2587
2588    /// Record a tool outcome. Resets count on success, increments on failure.
2589    fn record(&mut self, outcome: &ToolOutcome) {
2590        if outcome.success {
2591            self.failures.remove(&outcome.tool_name);
2592        } else {
2593            let count = self.failures.entry(outcome.tool_name.clone()).or_insert(0);
2594            *count += 1;
2595        }
2596    }
2597}
2598
2599struct ToolExecutionResult {
2600    index: usize,
2601    content: Content,
2602    actions: EventActions,
2603    escalate_or_skip: bool,
2604    /// Set when the call is held for a confirmation decision that does not exist yet.
2605    pending: Option<ToolConfirmationRequest>,
2606    /// Whether the tool's `execute` was entered in this dispatch.
2607    executed: bool,
2608}
2609
2610/// Runs output guardrails on the function responses of a result that ends the turn.
2611///
2612/// Guardrails read text parts, so each response is screened as its JSON text. A transformed
2613/// text replaces the response, parsed back to JSON when it still parses and wrapped as
2614/// `{"result": text}` when it does not.
2615async fn screen_terminal_tool_output(
2616    guardrails: &GuardrailSet,
2617    mut content: Content,
2618) -> Result<Screened> {
2619    let mut warnings = Warnings::default();
2620    for part in &mut content.parts {
2621        if let Part::FunctionResponse { function_response, .. } = part {
2622            let text = function_response.response.to_string();
2623            let screened = enforce_guardrails(
2624                guardrails,
2625                &Content::new("model").with_text(&text),
2626                Phase::Output,
2627            )
2628            .await?;
2629            let screened_text: String =
2630                screened.content.parts.iter().filter_map(Part::text).collect();
2631            if screened_text != text {
2632                function_response.response = serde_json::from_str(&screened_text)
2633                    .unwrap_or_else(|_| serde_json::json!({ "result": screened_text }));
2634            }
2635            warnings.extend(screened.warnings);
2636        }
2637    }
2638    Ok(Screened { content, warnings })
2639}
2640
2641/// Turns a tool callback's substitute content into the response to the call it replaces.
2642///
2643/// Providers reject a request whose function call has no function response with the same id,
2644/// so a function response part is re-addressed to this call, keeping the annotations the
2645/// callback set, and text-only content is wrapped as one by `wrap_text`, with `text_status`.
2646/// Only the function response is kept, as OpenAI Chat reads the first part of a tool message
2647/// and nothing else.
2648fn callback_tool_response(
2649    content: Content,
2650    name: &str,
2651    id: Option<&String>,
2652    wrap_text: impl FnOnce(String) -> serde_json::Value,
2653    text_status: Option<ToolResultStatus>,
2654) -> Content {
2655    let mut text = String::new();
2656    let mut response = None;
2657    for part in content.parts {
2658        match part {
2659            Part::FunctionResponse { mut function_response, annotations, .. }
2660                if response.is_none() =>
2661            {
2662                function_response.name = name.to_string();
2663                response = Some(Part::FunctionResponse {
2664                    function_response,
2665                    id: id.cloned(),
2666                    annotations,
2667                });
2668            }
2669            other => {
2670                if let Some(chunk) = other.text() {
2671                    text.push_str(chunk);
2672                }
2673            }
2674        }
2675    }
2676    let response = response.unwrap_or_else(|| {
2677        let mut part = Part::FunctionResponse {
2678            function_response: FunctionResponseData::new(name, wrap_text(text)),
2679            id: id.cloned(),
2680            annotations: None,
2681        };
2682        if let Some(status) = text_status {
2683            part.set_tool_result_status(status, None);
2684        }
2685        part
2686    });
2687    Content { role: "function".to_string(), parts: vec![response] }
2688}
2689
2690/// Whether a call ran and returned its result: not held, refused, skipped, failed, of
2691/// unknown outcome, or withheld.
2692fn completed(result: &ToolExecutionResult) -> bool {
2693    result.pending.is_none()
2694        && result.content.parts.iter().all(|part| {
2695            part.tool_result_status()
2696                .is_none_or(|status| matches!(status, ToolResultStatus::Succeeded))
2697        })
2698}
2699
2700#[derive(Clone, Copy)]
2701enum ToolDispatchMode {
2702    Sequential,
2703    Parallel,
2704    ParallelDelegations,
2705    Auto,
2706}
2707
2708impl ToolDispatchMode {
2709    fn resolve(strategy: ToolExecutionStrategy, parallelize_agent_delegations: bool) -> Self {
2710        if parallelize_agent_delegations {
2711            return Self::ParallelDelegations;
2712        }
2713        match strategy {
2714            ToolExecutionStrategy::Sequential => Self::Sequential,
2715            ToolExecutionStrategy::Parallel => Self::Parallel,
2716            ToolExecutionStrategy::Auto => Self::Auto,
2717        }
2718    }
2719}
2720
2721struct ToolExecutor<'a> {
2722    ctx: Arc<dyn InvocationContext>,
2723    /// The agent the results are authored by. Under a workflow parent the context names the
2724    /// parent, but a call's response belongs to the agent that issued it, as its hold does.
2725    agent_name: &'a str,
2726    tool_map: &'a std::collections::HashMap<String, Arc<dyn Tool>>,
2727    tool_retry_budgets: &'a std::collections::HashMap<String, RetryBudget>,
2728    default_retry_budget: &'a Option<RetryBudget>,
2729    before_tool_callbacks: &'a Arc<Vec<BeforeToolCallback>>,
2730    after_tool_callbacks: &'a Arc<Vec<AfterToolCallback>>,
2731    after_tool_callbacks_full: &'a Arc<Vec<AfterToolCallbackFull>>,
2732    on_tool_error_callbacks: &'a Arc<Vec<OnToolErrorCallback>>,
2733    /// The run's invocation hooks, iterated ahead of the agent's own tool callbacks.
2734    hook_callbacks: &'a HookCallbacks,
2735    tool_confirmation_policy: &'a ToolConfirmationPolicy,
2736    tool_guardrails: &'a ToolGuardrailSet,
2737    /// Screens a result that ends the turn, since that result is the final response.
2738    output_guardrails: &'a GuardrailSet,
2739    cb_mutex: &'a std::sync::Mutex<Option<CircuitBreakerState>>,
2740    invocation_id: &'a str,
2741    concurrency_manager: &'a adk_core::ToolConcurrencyManager,
2742    progress_tx: tokio::sync::mpsc::Sender<Event>,
2743    progress_overflow: ProgressOverflow,
2744    tool_timeout: std::time::Duration,
2745    expose_tool_error_messages: bool,
2746    /// Set when an approval fails, so calls still waiting for theirs stop waiting.
2747    approval_failed: tokio::sync::watch::Sender<bool>,
2748    /// The ordered batches ([`Tool::batch_group`]) a call in this dispatch did not complete;
2749    /// their later calls are answered with the halt text instead of running.
2750    halted_batches: std::sync::Mutex<std::collections::HashSet<String>>,
2751    #[cfg(feature = "enhanced-plugins")]
2752    enhanced_plugin_manager: &'a Option<Arc<EnhancedPluginManager>>,
2753}
2754
2755impl ToolExecutor<'_> {
2756    /// Runs one batch of calls under `strategy`, returning results in completion order.
2757    async fn dispatch(
2758        &self,
2759        strategy: ToolDispatchMode,
2760        fc_parts: Vec<PendingToolCall>,
2761    ) -> Result<Vec<ToolExecutionResult>> {
2762        // An ordered batch runs in the model's order, so no strategy may overlap its calls.
2763        let strategy = match strategy {
2764            ToolDispatchMode::Parallel
2765                if fc_parts.iter().any(|call| self.batch_of(&call.name).is_some()) =>
2766            {
2767                ToolDispatchMode::Sequential
2768            }
2769            other => other,
2770        };
2771        let results: Vec<ToolExecutionResult> = match strategy {
2772            ToolDispatchMode::Sequential => {
2773                let mut results = Vec::with_capacity(fc_parts.len());
2774                for call in fc_parts {
2775                    results.push(self.execute(call).await?);
2776                }
2777                results
2778            }
2779            ToolDispatchMode::Parallel => {
2780                use futures::StreamExt as _;
2781                // Parallel is an explicit caller override. Tool
2782                // safety metadata is intentionally not inspected.
2783                // All concurrency enforcement is handled by the
2784                // ToolConcurrencyManager semaphore inside ToolExecutor.
2785                // Use fc_parts.len() as buffer so all futures can start
2786                // and queue on the semaphore for proper per-tool limiting.
2787                let buffer_size = fc_parts.len().max(1);
2788                futures::stream::iter(fc_parts.into_iter().map(|call| self.execute(call)))
2789                    .buffer_unordered(buffer_size)
2790                    // Running tools finish before an approval error ends the turn.
2791                    .collect::<Vec<_>>()
2792                    .await
2793                    .into_iter()
2794                    .collect::<Result<Vec<_>>>()?
2795            }
2796            ToolDispatchMode::ParallelDelegations => {
2797                use futures::StreamExt as _;
2798
2799                let mut all_results = Vec::with_capacity(fc_parts.len());
2800                let mut calls = fc_parts.into_iter().peekable();
2801                while let Some(call) = calls.next() {
2802                    let is_delegation = self
2803                        .tool_map
2804                        .get(&call.name)
2805                        .is_some_and(|tool| tool.is_agent_delegation());
2806                    if !is_delegation {
2807                        all_results.push(self.execute(call).await?);
2808                        continue;
2809                    }
2810
2811                    let mut delegation_batch = vec![call];
2812                    while calls.peek().is_some_and(|next| {
2813                        self.tool_map.get(&next.name).is_some_and(|tool| tool.is_agent_delegation())
2814                    }) {
2815                        if let Some(next) = calls.next() {
2816                            delegation_batch.push(next);
2817                        }
2818                    }
2819
2820                    let buffer_size = delegation_batch.len();
2821                    all_results.extend(
2822                        futures::stream::iter(
2823                            delegation_batch.into_iter().map(|call| self.execute(call)),
2824                        )
2825                        .buffer_unordered(buffer_size)
2826                        .collect::<Vec<_>>()
2827                        .await
2828                        .into_iter()
2829                        .collect::<Result<Vec<_>>>()?,
2830                    );
2831                }
2832                all_results
2833            }
2834            ToolDispatchMode::Auto => {
2835                use futures::StreamExt as _;
2836
2837                // A call may overlap another only when its tool is read-only *and* declares
2838                // concurrency safety. Only a run of adjacent such calls overlaps; any other
2839                // call runs alone, in the model's order, so it starts only after every call
2840                // listed before it has finished.
2841                let is_concurrent = |call: &PendingToolCall| {
2842                    self.tool_map.get(&call.name).is_some_and(|tool| {
2843                        tool.is_read_only()
2844                            && tool.is_concurrency_safe()
2845                            && tool.batch_group().is_none()
2846                    })
2847                };
2848                let mut all_results = Vec::with_capacity(fc_parts.len());
2849                let mut calls = fc_parts.into_iter().peekable();
2850                while let Some(call) = calls.next() {
2851                    if !is_concurrent(&call) {
2852                        all_results.push(self.execute(call).await?);
2853                        continue;
2854                    }
2855
2856                    let mut concurrent_batch = vec![call];
2857                    while calls.peek().is_some_and(is_concurrent) {
2858                        if let Some(next) = calls.next() {
2859                            concurrent_batch.push(next);
2860                        }
2861                    }
2862
2863                    // Concurrency enforcement is handled by the semaphore inside ToolExecutor.
2864                    let buffer_size = concurrent_batch.len();
2865                    all_results.extend(
2866                        futures::stream::iter(
2867                            concurrent_batch.into_iter().map(|call| self.execute(call)),
2868                        )
2869                        .buffer_unordered(buffer_size)
2870                        .collect::<Vec<_>>()
2871                        .await
2872                        .into_iter()
2873                        .collect::<Result<Vec<_>>>()?,
2874                    );
2875                }
2876                all_results
2877            }
2878        };
2879        Ok(results)
2880    }
2881
2882    async fn execute(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
2883        let screened_call =
2884            (!self.tool_guardrails.is_empty()).then(|| (call.name.clone(), call.args.clone()));
2885        // The run's call a person asked for: its answer carries the mark, as its call does.
2886        let requested = self
2887            .ctx
2888            .run_config()
2889            .requested_call
2890            .as_ref()
2891            .filter(|requested| requested.function_call_id == call.function_call_id);
2892        let batch = self.batch_of(&call.name);
2893        let halted = batch.as_ref().is_some_and(|batch| {
2894            self.halted_batches
2895                .lock()
2896                .unwrap_or_else(|e| e.into_inner())
2897                .contains(batch.name.as_ref())
2898        });
2899        let mut result = match &batch {
2900            Some(batch) if halted => self.halted_call(call, batch).await?,
2901            _ => self.execute_inner(call).await?,
2902        };
2903        // A call of an ordered batch that did not complete stops the rest of the batch.
2904        if let Some(batch) = &batch
2905            && !completed(&result)
2906        {
2907            self.halted_batches
2908                .lock()
2909                .unwrap_or_else(|e| e.into_inner())
2910                .insert(batch.name.to_string());
2911        }
2912        // Tool guardrails see the result the model is about to be sent, after every after-tool
2913        // stage. A held call's pending response is not a result.
2914        if let Some((name, args)) = screened_call
2915            && result.pending.is_none()
2916        {
2917            let (content, withheld) = screen_tool_result(
2918                self.tool_guardrails,
2919                &name,
2920                &args,
2921                result.executed,
2922                result.content,
2923            )
2924            .await;
2925            result.content = content;
2926            for reason in withheld {
2927                // A guardrail's reason can describe the result it withheld.
2928                tracing::debug!(
2929                    tool.name = %name,
2930                    reason = %self.logged_message(&reason),
2931                    "tool result withheld"
2932                );
2933            }
2934        }
2935        // A result that ends the turn is the final response, so it is screened like one,
2936        // before the client or the session sees it.
2937        let mut warnings = Warnings::default();
2938        if result.escalate_or_skip && result.pending.is_none() && !self.output_guardrails.is_empty()
2939        {
2940            let screened =
2941                screen_terminal_tool_output(self.output_guardrails, result.content).await?;
2942            result.content = screened.content;
2943            warnings = screened.warnings;
2944        }
2945        let mut event = Event::new(self.invocation_id);
2946        event.author = self.agent_name.to_owned();
2947        event.branch = self.ctx.branch().to_owned();
2948        warnings.record_on(&mut event);
2949        event.actions = result.actions.clone();
2950        event.llm_response.content = Some(result.content.clone());
2951        if let Some(requested) = requested {
2952            requested.mark(&mut event);
2953        }
2954        // Runner commits each result while other calls are still awaiting approval.
2955        let _ = self.progress_tx.send(event).await;
2956        Ok(result)
2957    }
2958
2959    /// The ordered batch a call to `name` belongs to.
2960    fn batch_of(&self, name: &str) -> Option<adk_core::BatchGroup> {
2961        self.tool_map.get(name).and_then(|tool| tool.batch_group())
2962    }
2963
2964    /// Answers a call of a halted batch with the batch's halt text, without running it.
2965    async fn halted_call(
2966        &self,
2967        call: PendingToolCall,
2968        batch: &adk_core::BatchGroup,
2969    ) -> Result<ToolExecutionResult> {
2970        self.record_short_circuit(&call.name, &call.function_call_id, &call.args, "batch_halt")
2971            .await?;
2972        let mut part = Part::FunctionResponse {
2973            function_response: FunctionResponseData::new(
2974                call.name,
2975                serde_json::Value::String(batch.halt_text.to_string()),
2976            ),
2977            id: call.id,
2978            annotations: None,
2979        };
2980        part.set_tool_result_status(ToolResultStatus::NotRun, None);
2981        Ok(ToolExecutionResult {
2982            index: call.index,
2983            content: Content { role: "function".to_string(), parts: vec![part] },
2984            actions: EventActions::default(),
2985            escalate_or_skip: false,
2986            pending: None,
2987            executed: false,
2988        })
2989    }
2990
2991    /// The text logged for an error message, see [`traced_message`].
2992    fn logged_message(&self, message: &str) -> String {
2993        traced_message(self.ctx.run_config(), message)
2994    }
2995
2996    /// Records, through the run's audit trail, a call that `answered_by` answered before
2997    /// the governed path saw it, so the trail shows every call that skipped authorization.
2998    ///
2999    /// # Errors
3000    ///
3001    /// Returns `audit.record_failed`, which ends the turn, when the record cannot be
3002    /// written under [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block).
3003    async fn record_short_circuit(
3004        &self,
3005        name: &str,
3006        function_call_id: &str,
3007        args: &serde_json::Value,
3008        answered_by: &str,
3009    ) -> Result<()> {
3010        tracing::debug!(
3011            tool.name = %name,
3012            tool.answered_by = %answered_by,
3013            "tool call answered before authorization; the tool was not run"
3014        );
3015        let Some(trail) = &self.ctx.run_config().audit else {
3016            return Ok(());
3017        };
3018        let mut draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, SHORT_CIRCUIT_ACTION)
3019            .actor(AuditActor::for_context(self.ctx.as_ref()))
3020            .args_digest(trail.digest(args))
3021            .outcome(AuditRecordOutcome::NotRun)
3022            .ext("toolName", serde_json::Value::String(name.to_string()))
3023            .ext("agentName", serde_json::Value::String(self.agent_name.to_string()))
3024            .ext("answeredBy", serde_json::Value::String(answered_by.to_string()))
3025            .ext("functionCallId", serde_json::Value::String(function_call_id.to_string()))
3026            .ext("sessionId", serde_json::Value::String(self.ctx.session_id().to_string()));
3027        if let Some(tool) = self.tool_map.get(name) {
3028            let origin = adk_core::ToolOrigin::of(tool.as_ref());
3029            draft = draft
3030                .ext("toolSource", serde_json::Value::String(origin.source))
3031                .ext("declarationDigest", serde_json::Value::String(origin.declaration_digest));
3032        }
3033        if let Err(error) = trail.record(draft).await {
3034            self.approval_failed.send_replace(true);
3035            return Err(error);
3036        }
3037        Ok(())
3038    }
3039
3040    async fn execute_inner(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
3041        let PendingToolCall { index, name, args, id, function_call_id, resumes } = call;
3042        // A resumed held call runs under a later invocation, so it is ledgered under its
3043        // original identity, which every resumption of it shares (spec 3.1 §7.12, I37).
3044        let resumed_ledger_key = resumes.as_ref().map(|held| {
3045            crate::tool_ledger::held_call_ledger_key(
3046                self.ctx.app_name(),
3047                self.ctx.user_id(),
3048                self.ctx.session_id(),
3049                &function_call_id,
3050                &held.fingerprint(),
3051            )
3052        });
3053        let mut tool_actions = EventActions::default();
3054        let mut response_content: Option<Content> = None;
3055        let mut run_after_tool_callbacks = true;
3056        let mut tool_outcome_for_callback: Option<ToolOutcome> = None;
3057        let mut executed_tool: Option<Arc<dyn Tool>> = None;
3058        let mut executed_tool_response: Option<serde_json::Value> = None;
3059        // Set once `execute` was called, so its side effect may have happened.
3060        let mut tool_executed = false;
3061        let mut pending_confirmation: Option<ToolConfirmationRequest> = None;
3062        // Set when a call that ran ended with an unknown outcome: no later stage settles it.
3063        let mut unknown_outcome: Option<Arc<adk_core::AdkError>> = None;
3064        // An answer the agent writes in place of the tool's result, with its status.
3065        let answer = |response: serde_json::Value,
3066                      status: Option<ToolResultStatus>,
3067                      cause: Option<&adk_core::AdkError>| {
3068            let mut part = Part::FunctionResponse {
3069                function_response: FunctionResponseData::from_tool_result(name.clone(), response),
3070                id: id.clone(),
3071                annotations: None,
3072            };
3073            if let Some(status) = status {
3074                part.set_tool_result_status(status, cause);
3075            }
3076            Content { role: "function".to_string(), parts: vec![part] }
3077        };
3078        let not_run = |message: String, cause: Option<&adk_core::AdkError>| {
3079            answer(serde_json::json!({ "error": message }), Some(ToolResultStatus::NotRun), cause)
3080        };
3081        // A callback's error message stays local unless the agent exposes error messages.
3082        let callback_failure = |error: &adk_core::AdkError| {
3083            if self.expose_tool_error_messages { error.to_string() } else { error.redacted() }
3084        };
3085
3086        // The provider could not decode the model's arguments into an object, so there is
3087        // nothing to authorize or execute; the model is asked to send the call again.
3088        if let Some(reason) = adk_core::invalid_tool_arguments_reason(&args) {
3089            tracing::warn!(
3090                tool.name = %name,
3091                reason = %reason,
3092                "tool call arguments are not a JSON object; answering without executing"
3093            );
3094            return Ok(ToolExecutionResult {
3095                index,
3096                content: not_run(
3097                    format!(
3098                        "tool '{name}' was not run: {reason}. Call it again with arguments that \
3099                         are one JSON object matching its parameters."
3100                    ),
3101                    None,
3102                ),
3103                actions: tool_actions,
3104                escalate_or_skip: false,
3105                pending: None,
3106                executed: false,
3107            });
3108        }
3109
3110        // Before-tool hooks run first and may rewrite the arguments. Governance below sees
3111        // only the final arguments, so nothing can change a call after it is authorized.
3112        let mut final_args = args;
3113
3114        // ===== ENHANCED PLUGIN: BEFORE TOOL CALL =====
3115        #[cfg(feature = "enhanced-plugins")]
3116        if let Some(epm) = self.enhanced_plugin_manager.as_ref()
3117            && let Some(tool_ref) = self.tool_map.get(&name)
3118        {
3119            match epm
3120                .run_before_tool_call(
3121                    tool_ref.clone(),
3122                    final_args.clone(),
3123                    self.ctx.clone() as Arc<dyn CallbackContext>,
3124                )
3125                .await
3126            {
3127                Ok(BeforeToolCallResult::Continue(modified_args)) => {
3128                    final_args = modified_args;
3129                }
3130                Ok(BeforeToolCallResult::ShortCircuit(synthetic_result)) => {
3131                    // Short-circuit: use synthetic result, skip tool execution
3132                    self.record_short_circuit(
3133                        &name,
3134                        &function_call_id,
3135                        &final_args,
3136                        SHORT_CIRCUIT_BY_ENHANCED_PLUGIN,
3137                    )
3138                    .await?;
3139                    response_content = Some(Content {
3140                        role: "function".to_string(),
3141                        parts: vec![Part::FunctionResponse {
3142                            function_response: FunctionResponseData::from_tool_result(
3143                                name.clone(),
3144                                synthetic_result,
3145                            ),
3146                            id: id.clone(),
3147                            annotations: None,
3148                        }],
3149                    });
3150                    executed_tool = Some(tool_ref.clone());
3151                }
3152                Err(e) => {
3153                    tracing::warn!(
3154                        tool.name = %name,
3155                        error.code = %e.code,
3156                        error.category = %e.category,
3157                        error.message = %self.logged_message(&e.message),
3158                        "before-tool plugin failed; the tool was not run"
3159                    );
3160                    response_content = Some(not_run(
3161                        format!(
3162                            "tool '{name}' was not run: a before-tool plugin failed with {}",
3163                            callback_failure(&e)
3164                        ),
3165                        Some(&e),
3166                    ));
3167                    run_after_tool_callbacks = false;
3168                }
3169            }
3170        }
3171
3172        if response_content.is_none() {
3173            let tool_ctx = Arc::new(ToolCallbackContext::new(
3174                self.ctx.clone(),
3175                name.clone(),
3176                final_args.clone(),
3177            ));
3178            let hooks = self.hook_callbacks.before_tool.len();
3179            for (position, callback) in self
3180                .hook_callbacks
3181                .before_tool
3182                .iter()
3183                .chain(self.before_tool_callbacks.iter())
3184                .enumerate()
3185            {
3186                // A panic fails the call closed, as an error does.
3187                let decided = adk_core::guard_callback(
3188                    "before-tool callback",
3189                    callback(tool_ctx.clone() as Arc<dyn CallbackContext>),
3190                )
3191                .await;
3192                match decided {
3193                    Ok(Some(c)) => {
3194                        let answered_by = if position < hooks {
3195                            SHORT_CIRCUIT_BY_INVOCATION_HOOK
3196                        } else {
3197                            SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK
3198                        };
3199                        self.record_short_circuit(
3200                            &name,
3201                            &function_call_id,
3202                            &final_args,
3203                            answered_by,
3204                        )
3205                        .await?;
3206                        // The tool did not run, so text is reported as the call's error.
3207                        response_content = Some(callback_tool_response(
3208                            c,
3209                            &name,
3210                            id.as_ref(),
3211                            |text| serde_json::json!({ "error": text }),
3212                            Some(ToolResultStatus::NotRun),
3213                        ));
3214                        break;
3215                    }
3216                    Ok(None) => continue,
3217                    Err(e) => {
3218                        tracing::warn!(
3219                            tool.name = %name,
3220                            error.code = %e.code,
3221                            error.category = %e.category,
3222                            error.message = %self.logged_message(&e.message),
3223                            "before-tool callback failed; the tool was not run"
3224                        );
3225                        response_content = Some(not_run(
3226                            format!(
3227                                "tool '{name}' was not run: a before-tool callback failed with {}",
3228                                callback_failure(&e)
3229                            ),
3230                            Some(&e),
3231                        ));
3232                        run_after_tool_callbacks = false;
3233                        break;
3234                    }
3235                }
3236            }
3237        }
3238
3239        // Circuit breaker check
3240        if response_content.is_none() {
3241            let guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
3242            if let Some(ref cb_state) = *guard
3243                && cb_state.is_open(&name)
3244            {
3245                let msg = format!(
3246                    "Tool '{}' is temporarily disabled after {} consecutive failures",
3247                    name, cb_state.threshold
3248                );
3249                tracing::warn!(tool.name = %name, "circuit breaker open, skipping tool execution");
3250                response_content = Some(not_run(msg, None));
3251                run_after_tool_callbacks = false;
3252            }
3253            drop(guard);
3254        }
3255
3256        // ===== GOVERNED PATH: POLICY, GUARDRAILS, CONFIRMATION =====
3257        // Runtime-injected requirements such as team relationship approval gate execution
3258        // exactly like the agent's own confirmation policy.
3259        if response_content.is_none()
3260            && let Some(tool) = self.tool_map.get(&name)
3261        {
3262            let screen = GuardrailScreen(self.tool_guardrails);
3263            let mut gate = ToolGate::for_context(self.ctx.as_ref())
3264                .with_abandon_signal(self.approval_failed.subscribe());
3265            if !self.tool_guardrails.is_empty() {
3266                gate = gate.with_screen(&screen);
3267            }
3268            let mut call =
3269                GovernedCall::for_tool(tool.as_ref(), function_call_id.clone(), final_args.clone())
3270                    .requiring_confirmation(
3271                        self.tool_confirmation_policy.requires_confirmation(&name)
3272                            || self.ctx.requires_tool_confirmation(&name),
3273                    );
3274            // The governed path resumes a held call only for the agent and tool it was held
3275            // for. A request naming another tool belongs to a delegate the tool runs, whose
3276            // own governed path binds it.
3277            let resumed = resumes.filter(|held| held.tool_name == name);
3278            if let Some(held) = resumed.clone() {
3279                call = call.resuming(held);
3280            }
3281            // A call a person asked for is held for them however the agent is configured,
3282            // and runs only on their decision when it resumes (spec 3.3 §7.4 rule 5).
3283            call = call.requested(adk_core::RequestedCall::is_requested_id(&function_call_id));
3284            match authorize_tool_call(&gate, call).await {
3285                Ok(ToolAuthorization::Execute { args, confirmation }) => {
3286                    final_args = args;
3287                    tool_actions.tool_confirmation_decision = confirmation;
3288                }
3289                Ok(ToolAuthorization::Refuse { reason, confirmation }) => {
3290                    // A guardrail's reason can quote the arguments it refused.
3291                    tracing::debug!(
3292                        tool.name = %name,
3293                        reason = %self.logged_message(&reason),
3294                        "tool call refused"
3295                    );
3296                    tool_actions.tool_confirmation_decision = confirmation;
3297                    response_content = Some(answer(
3298                        serde_json::json!({ "error": reason }),
3299                        Some(ToolResultStatus::Refused),
3300                        None,
3301                    ));
3302                    run_after_tool_callbacks = false;
3303                }
3304                Ok(ToolAuthorization::Pending { request, reason }) => {
3305                    response_content = Some(answer(
3306                        adk_core::confirmation_pending_response(reason),
3307                        Some(ToolResultStatus::Held),
3308                        None,
3309                    ));
3310                    pending_confirmation = Some(request);
3311                    run_after_tool_callbacks = false;
3312                }
3313                // The kill switch refused the call mid-turn: it is answered `not run`, the
3314                // batch's remaining calls meet the same refusal, and the turn ends at the
3315                // next model call, where a durable worker parks the run (spec 3.2 §10 S3).
3316                Err(error)
3317                    if error.code == adk_core::GOVERNANCE_FROZEN_CODE
3318                        || error.code == adk_core::GOVERNANCE_STALE_CODE =>
3319                {
3320                    tracing::info!(
3321                        tool.name = %name,
3322                        error = %error.diagnostics(),
3323                        "tool call not run: the governance control refuses work"
3324                    );
3325                    // The answer releases a resumed call's hold, so the decision it was
3326                    // resumed on is spent with it: after an unfreeze it cannot run an
3327                    // identical call that nobody decided (spec 3.3 §7.3).
3328                    if let Some(held) = &resumed {
3329                        adk_core::withdraw_held_call(&gate, held).await?;
3330                    }
3331                    response_content = Some(not_run(adk_core::not_run_text(&error), Some(&error)));
3332                    run_after_tool_callbacks = false;
3333                }
3334                Err(error) => {
3335                    self.approval_failed.send_replace(true);
3336                    return Err(error);
3337                }
3338            }
3339        }
3340
3341        // Acquire concurrency permit after confirmation, so an approval waiting on a person
3342        // does not hold the tool's slot, and a call that will not run takes none.
3343        // The permit is held for the entire duration of this tool call
3344        // and released on drop when this async block completes.
3345        let _concurrency_permit = if response_content.is_some() {
3346            None
3347        } else {
3348            match self.concurrency_manager.acquire(&name).await {
3349                Ok(permit) => Some(permit),
3350                Err(e) => {
3351                    // Concurrency limit reached with Fail policy — return error
3352                    return Ok(ToolExecutionResult {
3353                        index,
3354                        content: not_run(e.to_string(), Some(&e)),
3355                        actions: tool_actions,
3356                        escalate_or_skip: false,
3357                        pending: None,
3358                        executed: false,
3359                    });
3360                }
3361            }
3362        };
3363
3364        // Execute tool with retry budget and tracing
3365        if response_content.is_none() {
3366            if let Some(tool) = self.tool_map.get(&name) {
3367                // Each attempt gets its own context, so the state delta and escalation of an
3368                // attempt that is retried are never committed.
3369                let attempt_context = || -> Arc<dyn ToolContext> {
3370                    Arc::new(
3371                        AgentToolContext::new(self.ctx.clone(), function_call_id.clone())
3372                            .with_tool_name(tool.name())
3373                            .with_agent_tools(self.tool_map.keys().cloned())
3374                            .with_idempotency_key(resumed_ledger_key.clone())
3375                            .with_progress(
3376                                self.progress_tx.clone(),
3377                                self.progress_overflow.clone(),
3378                            ),
3379                    )
3380                };
3381                let mut tool_ctx = attempt_context();
3382                let effect = tool.effect();
3383
3384                // A non-idempotent call executes at most once per idempotency key. A record
3385                // that exists answers the call; a ledger that cannot be read or written
3386                // fails the call closed.
3387                let ledgered = match crate::tool_ledger::begin_ledgered_call(
3388                    self.ctx.as_ref(),
3389                    effect,
3390                    // A resumed call's context answers its held call's key.
3391                    tool_ctx.idempotency_key(),
3392                    &name,
3393                    &final_args,
3394                )
3395                .await?
3396                {
3397                    Ok(ledgered) => ledgered,
3398                    Err(recorded) => {
3399                        return Ok(ToolExecutionResult {
3400                            index,
3401                            content: answer(
3402                                recorded.response,
3403                                Some(recorded.status),
3404                                recorded.cause.as_ref(),
3405                            ),
3406                            actions: tool_actions,
3407                            escalate_or_skip: false,
3408                            pending: None,
3409                            executed: false,
3410                        });
3411                    }
3412                };
3413
3414                // The kill switch again, after the ledger write, which can take long enough
3415                // for a freeze to arrive: a call it refuses now never starts (spec 3.1 I20).
3416                // It is answered as at authorization, and its begun record is completed
3417                // with that answer, so a replay is answered the same way.
3418                if let Err(refusal) = self.ctx.run_config().check_governance() {
3419                    let text = adk_core::not_run_text(&refusal);
3420                    tracing::info!(
3421                        tool.name = %name,
3422                        error = %refusal.diagnostics(),
3423                        "tool call not run: the governance control refused it before it started"
3424                    );
3425                    if let Some(trail) = &self.ctx.run_config().audit {
3426                        let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, &name)
3427                            .actor(AuditActor::for_context(self.ctx.as_ref()))
3428                            .args_digest(trail.digest(&final_args))
3429                            .outcome(AuditRecordOutcome::NotRun)
3430                            .ext("reason", serde_json::Value::String(text.clone()))
3431                            .ext(
3432                                "sessionId",
3433                                serde_json::Value::String(self.ctx.session_id().to_string()),
3434                            );
3435                        trail.record(draft).await?;
3436                    }
3437                    if let Some(ledgered) = ledgered {
3438                        ledgered.complete(&name, None, &text).await;
3439                    }
3440                    return Ok(ToolExecutionResult {
3441                        index,
3442                        content: not_run(text, Some(&refusal)),
3443                        actions: tool_actions,
3444                        escalate_or_skip: false,
3445                        pending: None,
3446                        executed: false,
3447                    });
3448                }
3449
3450                // The GenAI `execute_tool` span; `tool.name` and the `gcp.vertex.agent.*`
3451                // fields stay for the in-process debug exporter.
3452                let span_name = format!("execute_tool {name}");
3453                let tool_span = tracing::info_span!(
3454                    "",
3455                    otel.name = %span_name,
3456                    otel.kind = "internal",
3457                    "gen_ai.operation.name" = "execute_tool",
3458                    "gen_ai.tool.name" = %name,
3459                    "gen_ai.tool.type" = "function",
3460                    "gen_ai.tool.call.id" = tracing::field::Empty,
3461                    "gen_ai.tool.description" = %tool.description(),
3462                    "gen_ai.agent.name" = %self.agent_name,
3463                    "gen_ai.tool.call.arguments" = tracing::field::Empty,
3464                    "gen_ai.tool.call.result" = tracing::field::Empty,
3465                    "error.type" = tracing::field::Empty,
3466                    tool.name = %name,
3467                    "gcp.vertex.agent.event_id" = %format!("{}_{}", self.invocation_id, name),
3468                    "gcp.vertex.agent.invocation_id" = %self.invocation_id,
3469                    "gcp.vertex.agent.session_id" = %self.ctx.session_id(),
3470                    "gen_ai.conversation.id" = %self.ctx.session_id()
3471                );
3472                // Conditionally required: only an id the model supplied.
3473                if let Some(call_id) =
3474                    id.as_deref().filter(|id| !id.starts_with(adk_core::GENERATED_CALL_ID_PREFIX))
3475                {
3476                    tool_span.record("gen_ai.tool.call.id", call_id);
3477                }
3478                let capture_on_span = adk_telemetry::config::capture_content().on_spans();
3479                if capture_on_span {
3480                    tool_span.record("gen_ai.tool.call.arguments", final_args.to_string().as_str());
3481                }
3482
3483                // Only a call that cannot repeat a side effect is retried.
3484                let budget = self
3485                    .tool_retry_budgets
3486                    .get(&name)
3487                    .or(self.default_retry_budget.as_ref())
3488                    .filter(|_| effect.is_retry_safe());
3489                let max_attempts = budget.map(|b| b.max_retries + 1).unwrap_or(1);
3490                let timeout = tool.timeout_override().unwrap_or(Some(self.tool_timeout));
3491
3492                let mut started = Event::new(self.invocation_id);
3493                started.author = self.agent_name.to_owned();
3494                started.branch = self.ctx.branch().to_owned();
3495                // Partial, as tool progress is: never persisted, never a final response.
3496                started.llm_response.partial = true;
3497                started.provider_metadata.insert(
3498                    "adk_tool_started".into(),
3499                    serde_json::json!({"id": id, "name": name}).to_string(),
3500                );
3501                let _ = self.progress_tx.send(started).await;
3502                tool_executed = true;
3503                let tool_clone = tool.clone();
3504                let tool_start = std::time::Instant::now();
3505                let mut last_error: Option<Arc<adk_core::AdkError>> = None;
3506                // Set when the last attempt ended mid-flight (timeout or panic), so its side
3507                // effect may or may not have happened. Such an error is the agent's own, and
3508                // its message is always shown to the model.
3509                let mut interrupted = false;
3510                let mut final_attempt: u32 = 0;
3511                let mut retry_result: Option<serde_json::Value> = None;
3512
3513                for attempt in 0..max_attempts {
3514                    if attempt > 0 {
3515                        if let Some(budget) = budget {
3516                            tokio::time::sleep(budget.backoff_delay(attempt)).await;
3517                        }
3518                        // A retry is a new start, and none begins once a freeze is observed;
3519                        // the last attempt's failure stands.
3520                        if self.ctx.run_config().check_governance().is_err() {
3521                            break;
3522                        }
3523                        tool_ctx = attempt_context();
3524                    }
3525                    final_attempt = attempt;
3526                    let attempt_result = async {
3527                        let args_payload = trace_json_payload(
3528                            &final_args,
3529                            self.ctx.run_config().record_payloads,
3530                            self.ctx.run_config().trace_payload_max_bytes,
3531                        );
3532                        tracing::debug!(tool.name = %name, tool.args = %args_payload, attempt = attempt, "tool_call");
3533                        let exec_future = execute_tool(
3534                            Arc::clone(&tool_clone),
3535                            tool_ctx.clone(),
3536                            final_args.clone(),
3537                        );
3538                        let bounded = async {
3539                            match timeout {
3540                                Some(limit) => tokio::time::timeout(limit, exec_future)
3541                                    .await
3542                                    .map_err(|_| limit),
3543                                None => Ok(exec_future.await),
3544                            }
3545                        };
3546                        match futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(bounded)).await {
3547                            Ok(Ok(result)) => result.map_err(|error| {
3548                                let retryable = error.is_retryable();
3549                                (error, retryable, false)
3550                            }),
3551                            Ok(Err(limit)) => Err((
3552                                adk_core::AdkError::new(
3553                                    adk_core::ErrorComponent::Tool,
3554                                    adk_core::ErrorCategory::Timeout,
3555                                    "tool.timeout",
3556                                    format!("Tool '{name}' timed out after {limit:?}"),
3557                                ),
3558                                true,
3559                                true,
3560                            )),
3561                            Err(_panic) => Err((
3562                                adk_core::AdkError::new(
3563                                    adk_core::ErrorComponent::Tool,
3564                                    adk_core::ErrorCategory::Internal,
3565                                    "tool.panicked",
3566                                    format!("tool '{name}' panicked during execution"),
3567                                ),
3568                                false,
3569                                true,
3570                            )),
3571                        }
3572                    }
3573                    .instrument(tool_span.clone())
3574                    .await;
3575                    match attempt_result {
3576                        Ok(value) => {
3577                            let result_payload = trace_json_payload(
3578                                &value,
3579                                self.ctx.run_config().record_payloads,
3580                                self.ctx.run_config().trace_payload_max_bytes,
3581                            );
3582                            tracing::debug!(tool.name = %name, tool.result = %result_payload, "tool_result");
3583                            if capture_on_span {
3584                                tool_span
3585                                    .record("gen_ai.tool.call.result", value.to_string().as_str());
3586                            }
3587                            retry_result = Some(value);
3588                            break;
3589                        }
3590                        Err((error, retryable, mid_flight)) => {
3591                            interrupted = mid_flight;
3592                            let message = if mid_flight {
3593                                error.message.clone()
3594                            } else {
3595                                self.logged_message(&error.message)
3596                            };
3597                            if retryable && attempt + 1 < max_attempts {
3598                                tracing::warn!(tool.name = %name, attempt = attempt, error.code = %error.code, error.category = %error.category, error.message = %message, "tool execution failed, retrying");
3599                            } else {
3600                                tracing::warn!(tool.name = %name, error.code = %error.code, error.category = %error.category, error.message = %message, "tool_error");
3601                            }
3602                            let retry = retryable && attempt + 1 < max_attempts;
3603                            if !retry {
3604                                tool_span.record("error.type", error.code);
3605                            }
3606                            last_error = Some(Arc::new(error));
3607                            if !retry {
3608                                break;
3609                            }
3610                        }
3611                    }
3612                }
3613
3614                let outcome_unknown = interrupted && effect == ToolEffect::NonIdempotent;
3615                // What the model is told about the failure: the agent's own timeout and panic
3616                // messages, or the tool error without its message by default.
3617                let failure_response = match (&retry_result, &last_error) {
3618                    (None, Some(error)) if outcome_unknown => {
3619                        Some(crate::tool_ledger::interrupted_call_response(&error.message))
3620                    }
3621                    (None, Some(error)) if interrupted => {
3622                        Some(serde_json::json!({ "error": error.message }))
3623                    }
3624                    (None, Some(error)) => Some(adk_core::tool_error_response(
3625                        &name,
3626                        error,
3627                        self.expose_tool_error_messages,
3628                    )),
3629                    (None, None) | (Some(_), _) => None,
3630                };
3631                if outcome_unknown {
3632                    crate::tool_ledger::record_outcome_unknown(
3633                        self.ctx.as_ref(),
3634                        &name,
3635                        &final_args,
3636                        "interrupted",
3637                    )
3638                    .await?;
3639                }
3640                // A call that ended mid-flight keeps its begun record, so a replay is answered
3641                // with an unknown outcome instead of executing again. The ledger records what
3642                // the model was told, since a replay answers with it.
3643                if let Some(ledgered) = ledgered
3644                    && !outcome_unknown
3645                {
3646                    let failure_text = failure_response
3647                        .as_ref()
3648                        .and_then(|response| response.get("error"))
3649                        .and_then(serde_json::Value::as_str)
3650                        .unwrap_or_default();
3651                    ledgered.complete(&name, retry_result.as_ref(), failure_text).await;
3652                }
3653
3654                let tool_duration = tool_start.elapsed();
3655                // Callbacks run in this process, so they see the full message.
3656                let error_message =
3657                    last_error.as_ref().filter(|_| retry_result.is_none()).map(|error| {
3658                        if interrupted { error.message.clone() } else { error.to_string() }
3659                    });
3660                let tool_success = retry_result.is_some();
3661                // What the answer reports when the tool did not return a result.
3662                let mut status = match last_error.as_deref() {
3663                    _ if tool_success => None,
3664                    _ if outcome_unknown => Some(ToolResultStatus::OutcomeUnknown),
3665                    Some(error) => Some(ToolResultStatus::of_tool_error(error)),
3666                    None => Some(ToolResultStatus::Failed),
3667                };
3668                if outcome_unknown {
3669                    unknown_outcome = last_error.clone();
3670                }
3671                let function_response = match retry_result {
3672                    Some(value) => value,
3673                    None => failure_response.unwrap_or_else(
3674                        || serde_json::json!({ "error": format!("tool '{name}' failed") }),
3675                    ),
3676                };
3677
3678                let outcome = ToolOutcome {
3679                    tool_name: name.clone(),
3680                    tool_args: final_args.clone(),
3681                    success: tool_success,
3682                    duration: tool_duration,
3683                    error_message: error_message.clone(),
3684                    error: if tool_success { None } else { last_error.clone() },
3685                    attempt: final_attempt,
3686                };
3687
3688                // Circuit breaker recording
3689                {
3690                    let mut guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
3691                    if let Some(ref mut cb_state) = *guard {
3692                        cb_state.record(&outcome);
3693                    }
3694                }
3695
3696                // On-tool-error callbacks
3697                let final_function_response = if !tool_success {
3698                    let error_ctx: Arc<dyn CallbackContext> =
3699                        Arc::new(ToolOutcomeCallbackContext {
3700                            inner: self.ctx.clone() as Arc<dyn CallbackContext>,
3701                            outcome: outcome.clone(),
3702                        });
3703                    let mut fallback_result = None;
3704                    let error_msg = error_message.unwrap_or_default();
3705                    for callback in self
3706                        .hook_callbacks
3707                        .on_tool_error
3708                        .iter()
3709                        .chain(self.on_tool_error_callbacks.iter())
3710                    {
3711                        match callback(
3712                            error_ctx.clone(),
3713                            tool.clone(),
3714                            final_args.clone(),
3715                            error_msg.clone(),
3716                        )
3717                        .await
3718                        {
3719                            Ok(Some(result)) => {
3720                                fallback_result = Some(result);
3721                                break;
3722                            }
3723                            Ok(None) => continue,
3724                            Err(e) => {
3725                                tracing::warn!(error.code = %e.code, error.message = %self.logged_message(&e.message), "on_tool_error callback failed");
3726                                break;
3727                            }
3728                        }
3729                    }
3730                    match fallback_result {
3731                        // The fallback is the answer the model reads; only an unknown outcome,
3732                        // which no fallback settles, keeps its status.
3733                        Some(result) => {
3734                            if !outcome_unknown {
3735                                status = None;
3736                            }
3737                            result
3738                        }
3739                        None => function_response,
3740                    }
3741                } else {
3742                    function_response
3743                };
3744                tool_outcome_for_callback = Some(outcome);
3745
3746                let confirmation_decision = tool_actions.tool_confirmation_decision;
3747                tool_actions = tool_ctx.actions();
3748                if tool_actions.tool_confirmation_decision.is_none() {
3749                    tool_actions.tool_confirmation_decision = confirmation_decision;
3750                }
3751                // An agent tool whose delegate held a call of its own holds this call with it:
3752                // the run ends on the delegate's request, and this call resumes once that
3753                // request has a decision.
3754                let final_function_response = match tool_actions.tool_confirmation.take() {
3755                    // A call that may have taken effect is not held to run again on a decision.
3756                    // Its request is withdrawn, so no decision on it authorizes an identical
3757                    // call, and the call is answered with its unknown outcome.
3758                    Some(request) if outcome_unknown => {
3759                        tracing::warn!(
3760                            tool.name = %name,
3761                            "a call with an unknown outcome asked for a confirmation; withdrawing the request"
3762                        );
3763                        let gate = ToolGate::for_context(self.ctx.as_ref());
3764                        if let Err(error) = adk_core::withdraw_held_call(&gate, &request).await {
3765                            self.approval_failed.send_replace(true);
3766                            return Err(error);
3767                        }
3768                        final_function_response
3769                    }
3770                    Some(request) => {
3771                        tool_actions.skip_summarization = false;
3772                        tool_actions.escalate = false;
3773                        pending_confirmation = Some(request);
3774                        run_after_tool_callbacks = false;
3775                        status = Some(ToolResultStatus::Held);
3776                        if adk_core::is_confirmation_pending(&final_function_response) {
3777                            final_function_response
3778                        } else {
3779                            adk_core::confirmation_pending_response(format!(
3780                                "Tool '{name}' is waiting for a confirmation"
3781                            ))
3782                        }
3783                    }
3784                    None => final_function_response,
3785                };
3786                executed_tool = Some(tool.clone());
3787                executed_tool_response = Some(final_function_response.clone());
3788                let cause =
3789                    last_error.as_deref().filter(|_| status != Some(ToolResultStatus::Held));
3790                response_content = Some(answer(final_function_response, status, cause));
3791            } else {
3792                response_content = Some(not_run(format!("Tool {name} not found"), None));
3793            }
3794        }
3795
3796        // ===== AFTER-TOOL PIPELINE =====
3797        // Runner hooks and `after_tool_callback`s, then `after_tool_callback_full`s, then
3798        // enhanced plugins. The first failure ends the pipeline: a later stage may be handed the
3799        // unscreened result, so none runs once a redaction or screening stage has failed.
3800        let mut response_content = response_content.expect("tool response content is set");
3801        if run_after_tool_callbacks {
3802            let mut failure: Option<adk_core::AdkError> = None;
3803            let outcome_ctx: Arc<dyn CallbackContext> = match tool_outcome_for_callback {
3804                Some(outcome) => Arc::new(ToolOutcomeCallbackContext {
3805                    inner: self.ctx.clone() as Arc<dyn CallbackContext>,
3806                    outcome,
3807                }),
3808                None => self.ctx.clone() as Arc<dyn CallbackContext>,
3809            };
3810            let cb_ctx: Arc<dyn CallbackContext> =
3811                Arc::new(ToolCallbackContext::new(outcome_ctx, name.clone(), final_args.clone()));
3812            for callback in
3813                self.hook_callbacks.after_tool.iter().chain(self.after_tool_callbacks.iter())
3814            {
3815                match callback(cb_ctx.clone()).await {
3816                    Ok(Some(modified)) => {
3817                        response_content = callback_tool_response(
3818                            modified,
3819                            &name,
3820                            id.as_ref(),
3821                            |text| serde_json::json!({ "result": text }),
3822                            None,
3823                        );
3824                        break;
3825                    }
3826                    Ok(None) => continue,
3827                    Err(e) => {
3828                        failure = Some(e);
3829                        break;
3830                    }
3831                }
3832            }
3833            if failure.is_none()
3834                && let (Some(tool_ref), Some(tool_resp)) = (&executed_tool, executed_tool_response)
3835            {
3836                for callback in self.after_tool_callbacks_full.as_ref() {
3837                    match callback(
3838                        cb_ctx.clone(),
3839                        tool_ref.clone(),
3840                        final_args.clone(),
3841                        tool_resp.clone(),
3842                    )
3843                    .await
3844                    {
3845                        Ok(Some(modified_value)) => {
3846                            response_content = answer(modified_value, None, None);
3847                            break;
3848                        }
3849                        Ok(None) => continue,
3850                        Err(e) => {
3851                            failure = Some(e);
3852                            break;
3853                        }
3854                    }
3855                }
3856            }
3857
3858            // ===== ENHANCED PLUGIN: AFTER TOOL CALL =====
3859            // Enhanced plugins can modify the tool result after legacy callbacks.
3860            #[cfg(feature = "enhanced-plugins")]
3861            if failure.is_none()
3862                && let Some(epm) = self.enhanced_plugin_manager.as_ref()
3863                && let Some(tool_ref) = &executed_tool
3864            {
3865                // Extract the result value from the response content
3866                let result_value = response_content
3867                    .parts
3868                    .iter()
3869                    .find_map(|p| {
3870                        if let Part::FunctionResponse { function_response, .. } = p {
3871                            Some(function_response.response.clone())
3872                        } else {
3873                            None
3874                        }
3875                    })
3876                    .unwrap_or(serde_json::json!(null));
3877
3878                // The outcome context carries the full error message, which the function
3879                // response no longer does, so plugins can still classify the failure.
3880                match epm
3881                    .run_after_tool_call(
3882                        tool_ref.clone(),
3883                        &final_args,
3884                        result_value.clone(),
3885                        cb_ctx.clone(),
3886                    )
3887                    .await
3888                {
3889                    // A result the plugins passed through stays the answer, with its status.
3890                    Ok(adk_plugin::AfterToolCallResult::Continue(modified_result)) => {
3891                        if modified_result != result_value {
3892                            response_content = answer(modified_result, None, None);
3893                        }
3894                    }
3895                    Err(e) => failure = Some(e),
3896                }
3897            }
3898
3899            if let Some(error) = failure {
3900                tracing::error!(
3901                    tool.name = %name,
3902                    tool.executed = tool_executed,
3903                    error.code = %error.code,
3904                    error.category = %error.category,
3905                    error.message = %self.logged_message(&error.message),
3906                    "after-tool pipeline failed; withholding the tool result"
3907                );
3908                // The tool's side effect stands and its ledger record says so; the model is
3909                // told not to repeat it, since a new call has a new idempotency key.
3910                response_content = if tool_executed {
3911                    answer(
3912                        adk_core::result_withheld_response(
3913                            &name,
3914                            &error,
3915                            self.expose_tool_error_messages,
3916                        ),
3917                        Some(ToolResultStatus::Withheld),
3918                        Some(&error),
3919                    )
3920                } else {
3921                    not_run(
3922                        format!(
3923                            "tool '{name}' was not run, and its after-tool pipeline failed with {}",
3924                            callback_failure(&error)
3925                        ),
3926                        Some(&error),
3927                    )
3928                };
3929            }
3930            // A stage that replaced or withheld the answer did not settle an unknown outcome.
3931            if let Some(cause) = &unknown_outcome {
3932                for part in &mut response_content.parts {
3933                    part.set_tool_result_status(ToolResultStatus::OutcomeUnknown, Some(cause));
3934                }
3935            }
3936        }
3937
3938        let escalate_or_skip = tool_actions.escalate || tool_actions.skip_summarization;
3939        Ok(ToolExecutionResult {
3940            index,
3941            content: response_content,
3942            actions: tool_actions,
3943            escalate_or_skip,
3944            pending: pending_confirmation,
3945            executed: tool_executed,
3946        })
3947    }
3948}
3949
3950#[async_trait]
3951impl Agent for LlmAgent {
3952    fn name(&self) -> &str {
3953        &self.name
3954    }
3955
3956    fn description(&self) -> &str {
3957        &self.description
3958    }
3959
3960    fn profile(&self) -> adk_core::AgentProfile {
3961        adk_core::AgentProfile {
3962            kind: adk_core::AgentKind::Llm,
3963            instruction: self.instruction.clone().filter(|text| !text.is_empty()),
3964            global_instruction: self.global_instruction.clone().filter(|text| !text.is_empty()),
3965            tools: self
3966                .tools
3967                .iter()
3968                .map(|tool| adk_core::ToolProfile {
3969                    name: tool.name().to_string(),
3970                    description: tool.description().to_string(),
3971                })
3972                .collect(),
3973        }
3974    }
3975
3976    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
3977        &self.sub_agents
3978    }
3979
3980    fn allows_transfer_to_parent(&self) -> bool {
3981        !self.disallow_transfer_to_parent
3982    }
3983
3984    fn allows_transfer_to_peers(&self) -> bool {
3985        !self.disallow_transfer_to_peers
3986    }
3987
3988    async fn close(&self) {
3989        for toolset in &self.toolsets {
3990            toolset.close().await;
3991        }
3992        #[cfg(feature = "enhanced-plugins")]
3993        if let Some(manager) = &self.enhanced_plugin_manager {
3994            manager.close().await;
3995        }
3996        for agent in &self.sub_agents {
3997            agent.close().await;
3998        }
3999    }
4000
4001    /// Opens the model's connection, then prewarms the sub-agents. Toolsets resolve their
4002    /// tools against a turn's context, so they are left to the turn.
4003    async fn prewarm(&self) -> Result<()> {
4004        self.model.prewarm().await?;
4005        for agent in &self.sub_agents {
4006            agent.prewarm().await?;
4007        }
4008        Ok(())
4009    }
4010
4011    fn capabilities(&self) -> adk_core::AgentCapabilities {
4012        adk_core::AgentCapabilities {
4013            runtime_tools: true,
4014            handoff: true,
4015            relationship_confirmation: true,
4016            checkpoint_resume: false,
4017            shared_state: true,
4018            invocation_metadata: true,
4019        }
4020    }
4021
4022    async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
4023        let own = if self.input_guardrails.is_empty() {
4024            None
4025        } else {
4026            Some(
4027                enforce_guardrails(self.input_guardrails.as_ref(), content, Phase::Input)
4028                    .await?
4029                    .content,
4030            )
4031        };
4032        let below =
4033            adk_core::screen_user_input_with(&self.sub_agents, own.as_ref().unwrap_or(content))
4034                .await?;
4035        Ok(below.or(own))
4036    }
4037
4038    #[adk_telemetry::instrument(
4039        skip(self, ctx),
4040        fields(
4041            agent.name = %self.name,
4042            agent.description = %self.description,
4043            invocation.id = %ctx.invocation_id(),
4044            user.id = %ctx.user_id(),
4045            session.id = %ctx.session_id()
4046        )
4047    )]
4048    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
4049        adk_telemetry::info!("Starting agent execution");
4050        // A call a person asked for is taken by the agent the run starts with (spec 3.3 §7.4
4051        // rule 5), never by a workflow or team member.
4052        let starts_run = ctx.agent_name() == self.name;
4053        // Under a workflow or team parent, the agent still acts as itself.
4054        let ctx = crate::acting_agent_context::ActingAgentContext::scope(ctx, &self.name);
4055        let ctx = Self::apply_input_guardrails(ctx, self.input_guardrails.clone()).await?;
4056
4057        let agent_name = self.name.clone();
4058        let invocation_id = ctx.invocation_id().to_string();
4059        let model = self.model.clone();
4060        let prompt_config = PromptConfig::from_agent(self);
4061        let tool_setup = ToolSetup::from_agent(self);
4062        let output_key = self.output_key.clone();
4063        let output_max_retries = self.output_max_retries;
4064        let generate_content_config = self.generate_content_config.clone();
4065        let max_iterations = self.max_iterations;
4066        let tool_timeout = self.tool_timeout;
4067        let expose_tool_error_messages = self.expose_tool_error_messages;
4068        // Clone Arc references (cheap)
4069        let before_agent_callbacks = self.before_callbacks.clone();
4070        let after_agent_callbacks = self.after_callbacks.clone();
4071        let history_processors = self.history_processors.clone();
4072        let before_model_callbacks = self.before_model_callbacks.clone();
4073        let after_model_callbacks = self.after_model_callbacks.clone();
4074        let before_tool_callbacks = self.before_tool_callbacks.clone();
4075        let after_tool_callbacks = self.after_tool_callbacks.clone();
4076        let on_tool_error_callbacks = self.on_tool_error_callbacks.clone();
4077        let after_tool_callbacks_full = self.after_tool_callbacks_full.clone();
4078        let default_retry_budget = self.default_retry_budget.clone();
4079        let tool_retry_budgets = self.tool_retry_budgets.clone();
4080        let circuit_breaker_threshold = self.circuit_breaker_threshold;
4081        let tool_confirmation_policy = self.tool_confirmation_policy.clone();
4082        let tool_guardrails = Arc::clone(&self.tool_guardrails);
4083        let output_guardrails = self.output_guardrails.clone();
4084        let agent_tool_execution_strategy = self.tool_execution_strategy;
4085        let parallelize_agent_delegations = self.parallelize_agent_delegations;
4086        #[cfg(feature = "enhanced-plugins")]
4087        let enhanced_plugin_manager = self.enhanced_plugin_manager.clone();
4088        // Runner plugins and other run-wide hooks reach this agent through the run config.
4089        let mut hook_callbacks = HookCallbacks::new(&ctx.run_config().invocation_hooks);
4090        // The before- and after-agent stages run around `body`, which runs the model and tools.
4091        let hook_before_agent = std::mem::take(&mut hook_callbacks.before_agent);
4092        let hook_after_agent = Arc::new(std::mem::take(&mut hook_callbacks.after_agent));
4093        let stage_ctx = ctx.clone();
4094        let stage_invocation_id = invocation_id.clone();
4095        let stage_agent_name = agent_name.clone();
4096        let stage_output_key = output_key.clone();
4097        let structured_output = self.output_schema.is_some();
4098
4099        // Boxed where it is built, so the stage stream below holds a pointer: a body moved
4100        // into it would put a copy of the whole body state on the stack of every poll, once
4101        // per nested agent behind an `AgentTool`.
4102        let body: adk_core::EventStream = Box::pin(stream! {
4103            // ===== MAIN AGENT EXECUTION =====
4104            let mut conversation_history = match prompt_config
4105                .prepare_conversation(&ctx, &agent_name)
4106                .await
4107            {
4108                Ok(history) => history,
4109                Err(error) => {
4110                    yield Err(error);
4111                    return;
4112                }
4113            };
4114
4115            let resolved_tools = match tool_setup.resolve(&ctx).await {
4116                Ok(tools) => tools,
4117                Err(error) => {
4118                    yield Err(error);
4119                    return;
4120                }
4121            };
4122            let mut tool_map = resolved_tools.map;
4123            let mut tool_declarations = resolved_tools.declarations;
4124            let mut valid_transfer_targets = resolved_tools.transfer_targets;
4125            // The transfer guidance joins the instructions, after the leading system contents.
4126            if let Some(guidance) = resolved_tools.transfer_guidance {
4127                let at = conversation_history
4128                    .iter()
4129                    .position(|content| content.role != "system")
4130                    .unwrap_or(conversation_history.len());
4131                conversation_history.insert(at, Content::new("system").with_text(guidance));
4132            }
4133
4134            // ===== CIRCUIT BREAKER STATE =====
4135            // Created fresh per invocation so it resets between runs.
4136            let mut circuit_breaker_state = circuit_breaker_threshold.map(CircuitBreakerState::new);
4137
4138            // ===== RESPONSE-ID CONTINUITY (provider-neutral) =====
4139            // Tracks the `interaction_id` carried by the most recent model
4140            // response so the next request can continue the conversation via
4141            // `LlmRequest.previous_response_id`. This is generic plumbing: it
4142            // contains no Gemini- or transport-specific logic. Providers that
4143            // do not support response chaining leave `interaction_id` as `None`,
4144            // so this stays `None` and `previous_response_id` is never set
4145            // (a no-op for generateContent and all other providers).
4146            let mut last_interaction_id: Option<String> = None;
4147
4148            // Shared with sub-agents, transfer targets and agent tools through the run config.
4149            let budget_tracker = ctx.run_config().budget_tracker.clone();
4150            // Provider-executed built-in tools never reach the governed call path, so the
4151            // policy and budget decide before each request whether they are attached.
4152            let mut builtin_governor = adk_core::BuiltinToolGovernor::new();
4153
4154            // ===== RESUME HELD CALLS =====
4155            // A call held for confirmation in an earlier run, with a decision now, is
4156            // dispatched again as the same call before the first model call, so the
4157            // decision applies whether or not the model would issue the call again. It
4158            // runs the whole tool path, where the governed path finds the decision.
4159            let mut resumed_calls = Vec::<PendingToolCall>::new();
4160            // The run ends once its held calls and a person's call are dealt with: a resumed
4161            // call ended the turn, or one was held again.
4162            let mut ends_here = false;
4163            // Set by each tool step, so the next model call is preceded by a safe point.
4164            let mut steering_due = false;
4165            {
4166                let gate = ToolGate::for_context(ctx.as_ref());
4167                for held in ctx.session().held_tool_calls(&agent_name, ctx.branch()) {
4168                    let Some(function_call_id) = held.request.function_call_id.clone() else {
4169                        continue;
4170                    };
4171                    match adk_core::confirmation_decision_available(&gate, &held.request).await {
4172                        // An agent tool holds its one call for every call its delegate holds,
4173                        // so the call runs once, for its latest request with a decision, and
4174                        // the delegate resumes each of its calls that has one (spec 3.1 §10 F4).
4175                        Ok(true) => match resumed_calls
4176                            .iter_mut()
4177                            .find(|resumed| resumed.function_call_id == function_call_id)
4178                        {
4179                            Some(resumed) => resumed.resumes = Some(held.request),
4180                            None => resumed_calls.push(PendingToolCall {
4181                                index: resumed_calls.len(),
4182                                name: held.name,
4183                                args: held.args,
4184                                id: held.id,
4185                                function_call_id,
4186                                resumes: Some(held.request),
4187                            }),
4188                        },
4189                        Ok(false) => {}
4190                        Err(error) => {
4191                            yield Err(error);
4192                            return;
4193                        }
4194                    }
4195                }
4196            }
4197            // Sources the run's tool calls recorded, which the final answer may cite.
4198            let mut retrieved: Vec<adk_core::GroundingSource> = Vec::new();
4199            if !resumed_calls.is_empty() {
4200                if ctx.is_cancelled() {
4201                    return;
4202                }
4203                // The held calls keep their pending responses, so a refused batch leaves
4204                // them held for a later run.
4205                if let Some(tracker) = budget_tracker.as_ref()
4206                    && let Err(exceeded) = tracker.begin_tool_calls(resumed_calls.len() as u64)
4207                {
4208                    yield Err(exceeded.into());
4209                    return;
4210                }
4211                tracing::info!(
4212                    agent.name = %agent_name,
4213                    tool.calls = resumed_calls.len(),
4214                    "resuming tool calls held for confirmation"
4215                );
4216                let strategy = ToolDispatchMode::resolve(
4217                    agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
4218                    parallelize_agent_delegations,
4219                );
4220                let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
4221                let concurrency_manager =
4222                    adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
4223                let (progress_tx, mut progress_rx) =
4224                    tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
4225                let progress_overflow = ProgressOverflow::default();
4226                let executor = ToolExecutor {
4227                    ctx: ctx.clone(),
4228                    agent_name: &agent_name,
4229                    tool_map: &tool_map,
4230                    tool_retry_budgets: &tool_retry_budgets,
4231                    default_retry_budget: &default_retry_budget,
4232                    output_guardrails: output_guardrails.as_ref(),
4233                    before_tool_callbacks: &before_tool_callbacks,
4234                    after_tool_callbacks: &after_tool_callbacks,
4235                    after_tool_callbacks_full: &after_tool_callbacks_full,
4236                    on_tool_error_callbacks: &on_tool_error_callbacks,
4237                    hook_callbacks: &hook_callbacks,
4238                    tool_confirmation_policy: &tool_confirmation_policy,
4239                    tool_guardrails: tool_guardrails.as_ref(),
4240                    cb_mutex: &cb_mutex,
4241                    invocation_id: &invocation_id,
4242                    concurrency_manager: &concurrency_manager,
4243                    progress_tx,
4244                    progress_overflow: progress_overflow.clone(),
4245                    tool_timeout,
4246                    expose_tool_error_messages,
4247                    approval_failed: tokio::sync::watch::channel(false).0,
4248                    halted_batches: Default::default(),
4249                    #[cfg(feature = "enhanced-plugins")]
4250                    enhanced_plugin_manager: &enhanced_plugin_manager,
4251                };
4252                let mut results = {
4253                    let dispatch = executor.dispatch(strategy, resumed_calls);
4254                    tokio::pin!(dispatch);
4255                    let results = loop {
4256                        tokio::select! {
4257                            biased;
4258                            Some(progress_event) = progress_rx.recv() => {
4259                                yield Ok(progress_event);
4260                            }
4261                            done = &mut dispatch => break done,
4262                        }
4263                    };
4264                    while let Ok(progress_event) = progress_rx.try_recv() {
4265                        yield Ok(progress_event);
4266                    }
4267                    let markers = std::mem::take(
4268                        &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
4269                    );
4270                    for marker in markers {
4271                        yield Ok(marker);
4272                    }
4273                    match results {
4274                        Ok(results) => results,
4275                        Err(error) => {
4276                            yield Err(error);
4277                            return;
4278                        }
4279                    }
4280                };
4281                results.sort_by_key(|r| r.index);
4282                drop(executor);
4283                circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());
4284
4285                // A call held again has not run, and counts when a later run resumes it.
4286                if let Some(tracker) = budget_tracker.as_ref() {
4287                    let held = results.iter().filter(|result| result.pending.is_some()).count();
4288                    tracker.release_tool_calls(held as u64);
4289                }
4290                let mut held_again = Vec::new();
4291                for result in results {
4292                    if result.escalate_or_skip {
4293                        // The call ends the turn before any model call, so a message this
4294                        // run brought would otherwise go unanswered without a word.
4295                        if ctx.user_content().carries_user_input() {
4296                            yield Err(adk_core::AdkError::new(
4297                                adk_core::ErrorComponent::Agent,
4298                                adk_core::ErrorCategory::InvalidInput,
4299                                "agent.resume_ended_turn",
4300                                "a resumed tool call ended the turn, so the message sent with \
4301                                 this run is saved but was not answered; run again with an \
4302                                 empty message to answer it, or resume held calls with an \
4303                                 empty message before sending a new one",
4304                            ));
4305                            return;
4306                        }
4307                        ends_here = true;
4308                        break;
4309                    }
4310                    held_again.extend(result.pending);
4311                    retrieved.extend(result.actions.grounding_sources);
4312                    // Each result takes the place of its call's pending response, matched by
4313                    // call ID, so the model sees one response per call.
4314                    let _ = adk_core::supersede_pending_responses(
4315                        &mut conversation_history,
4316                        result.content,
4317                    );
4318                }
4319                if !ends_here && !held_again.is_empty() {
4320                    for request in held_again {
4321                        yield Ok(confirmation_event(&invocation_id, &agent_name, request));
4322                    }
4323                    ends_here = true;
4324                }
4325
4326                if !ends_here {
4327                    let refreshed_tools = match tool_setup.resolve(&ctx).await {
4328                        Ok(tools) => tools,
4329                        Err(error) => {
4330                            yield Err(error);
4331                            return;
4332                        }
4333                    };
4334                    tool_map = refreshed_tools.map;
4335                    tool_declarations = refreshed_tools.declarations;
4336                    valid_transfer_targets = refreshed_tools.transfer_targets;
4337                    steering_due = true;
4338                }
4339            }
4340
4341            // ===== A CALL A PERSON ASKED FOR =====
4342            // Held for the person's decision as this agent, or refused, before any model
4343            // call; the run ends either way (spec 3.3 §7.4 rule 5). It takes the tool path
4344            // a model's call takes, so a before-tool plugin, hook or callback and the circuit
4345            // breaker see it before it is authorized as requested.
4346            if starts_run
4347                && let Some(requested) = ctx.run_config().requested_call.as_ref()
4348                && !crate::requested_call::taken(ctx.as_ref(), requested)
4349            {
4350                if let Some(reason) =
4351                    crate::requested_call::refusal(ctx.as_ref(), &tool_map, requested)
4352                {
4353                    for event in crate::requested_call::refusal_events(
4354                        ctx.as_ref(),
4355                        &agent_name,
4356                        requested,
4357                        &reason,
4358                    ) {
4359                        yield Ok(event);
4360                    }
4361                    return;
4362                }
4363                for event in crate::requested_call::asked_events(ctx.as_ref(), &agent_name, requested) {
4364                    yield Ok(event);
4365                }
4366                let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
4367                let concurrency_manager =
4368                    adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
4369                let (progress_tx, mut progress_rx) =
4370                    tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
4371                let progress_overflow = ProgressOverflow::default();
4372                let executor = ToolExecutor {
4373                    ctx: ctx.clone(),
4374                    agent_name: &agent_name,
4375                    tool_map: &tool_map,
4376                    tool_retry_budgets: &tool_retry_budgets,
4377                    default_retry_budget: &default_retry_budget,
4378                    output_guardrails: output_guardrails.as_ref(),
4379                    before_tool_callbacks: &before_tool_callbacks,
4380                    after_tool_callbacks: &after_tool_callbacks,
4381                    after_tool_callbacks_full: &after_tool_callbacks_full,
4382                    on_tool_error_callbacks: &on_tool_error_callbacks,
4383                    hook_callbacks: &hook_callbacks,
4384                    tool_confirmation_policy: &tool_confirmation_policy,
4385                    tool_guardrails: tool_guardrails.as_ref(),
4386                    cb_mutex: &cb_mutex,
4387                    invocation_id: &invocation_id,
4388                    concurrency_manager: &concurrency_manager,
4389                    progress_tx,
4390                    progress_overflow: progress_overflow.clone(),
4391                    tool_timeout,
4392                    expose_tool_error_messages,
4393                    approval_failed: tokio::sync::watch::channel(false).0,
4394                    halted_batches: Default::default(),
4395                    #[cfg(feature = "enhanced-plugins")]
4396                    enhanced_plugin_manager: &enhanced_plugin_manager,
4397                };
4398                let call = PendingToolCall {
4399                    index: 0,
4400                    name: requested.tool_name.clone(),
4401                    args: requested.args.clone(),
4402                    id: Some(requested.function_call_id.clone()),
4403                    function_call_id: requested.function_call_id.clone(),
4404                    resumes: None,
4405                };
4406                let results = {
4407                    let dispatch = executor.dispatch(ToolDispatchMode::Sequential, vec![call]);
4408                    tokio::pin!(dispatch);
4409                    let results = loop {
4410                        tokio::select! {
4411                            biased;
4412                            Some(progress_event) = progress_rx.recv() => {
4413                                yield Ok(progress_event);
4414                            }
4415                            done = &mut dispatch => break done,
4416                        }
4417                    };
4418                    while let Ok(progress_event) = progress_rx.try_recv() {
4419                        yield Ok(progress_event);
4420                    }
4421                    let markers = std::mem::take(
4422                        &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
4423                    );
4424                    for marker in markers {
4425                        yield Ok(marker);
4426                    }
4427                    results
4428                };
4429                match results {
4430                    Ok(results) => {
4431                        for request in results.into_iter().filter_map(|result| result.pending) {
4432                            yield Ok(crate::requested_call::held_event(
4433                                ctx.as_ref(),
4434                                &agent_name,
4435                                requested,
4436                                request,
4437                            ));
4438                        }
4439                    }
4440                    Err(error) => yield Err(error),
4441                }
4442                return;
4443            }
4444            if ends_here {
4445                return;
4446            }
4447
4448            // Multi-turn loop with max iterations
4449            let mut iteration = 0;
4450            let mut schema_retry_count: usize = 0;
4451            // The prompt tokens the provider reported for the last request, which the
4452            // compactor weighs against its threshold until the history is compacted.
4453            let mut reported_prompt_tokens: Option<u64> = None;
4454            // A request the model rejected as longer than its context window, which the next
4455            // pass compacts for and sends once more; set once per model call.
4456            let mut rejected_as_too_long: Option<adk_core::AdkError> = None;
4457            let mut resent_after_compaction = false;
4458
4459            'model_calls: loop {
4460                // Cooperative cancellation: exit before starting another turn
4461                // if the invocation was cancelled (e.g. Runner::interrupt()).
4462                if ctx.is_cancelled() {
4463                    tracing::info!(agent.name = %agent_name, "invocation cancelled — stopping agent loop");
4464                    return;
4465                }
4466                // The kill switch is checked before every model call.
4467                if let Err(error) = ctx.run_config().check_governance() {
4468                    yield Err(error);
4469                    return;
4470                }
4471                iteration += 1;
4472                if iteration > max_iterations {
4473                    yield Err(adk_core::AdkError::agent(
4474                        format!("Max iterations ({max_iterations}) exceeded")
4475                    ));
4476                    return;
4477                }
4478
4479                // ===== STEERING =====
4480                // The safe point: the last tool step's results are in the history and the next
4481                // request is not built yet, so a steering message lands after them. It is taken
4482                // only once the checks above pass, so a run they end returns its queued
4483                // messages to their senders instead of saving one no model call will carry.
4484                if std::mem::take(&mut steering_due)
4485                    && let Some(inbox) = ctx.steering_inbox()
4486                {
4487                    for message in inbox.drain() {
4488                        tracing::debug!(
4489                            agent.name = %agent_name,
4490                            steer.id = %message.marker.steer_id,
4491                            "steering message added to the history"
4492                        );
4493                        yield Ok(message.to_event(&invocation_id, ctx.branch()));
4494                        conversation_history.push(message.content);
4495                    }
4496                }
4497
4498                let config = build_generation_config(
4499                    generate_content_config.as_ref(),
4500                    prompt_config.output_schema.as_ref(),
4501                    ctx.run_config().cached_content.as_deref(),
4502                );
4503
4504                // The processors own the agent's history; what toolsets, plugins, run hooks
4505                // and before-model callbacks add below stays in this one request.
4506                let history_len = conversation_history.len();
4507                for processor in history_processors.iter() {
4508                    match processor(
4509                        ctx.clone() as Arc<dyn CallbackContext>,
4510                        std::mem::take(&mut conversation_history),
4511                    )
4512                    .await
4513                    {
4514                        Ok(history) => conversation_history = history,
4515                        Err(error) => {
4516                            yield Err(error);
4517                            return;
4518                        }
4519                    }
4520                }
4521                if conversation_history.len() != history_len {
4522                    tracing::debug!(
4523                        agent.name = %agent_name,
4524                        history.before = history_len,
4525                        history.after = conversation_history.len(),
4526                        "history processors rewrote the history"
4527                    );
4528                }
4529
4530                // ===== AUTO-COMPACTION =====
4531                // Before every model call, and once more after the model rejected a request as
4532                // too long; the instructions at the head of the history are never compacted.
4533                let rejected = rejected_as_too_long.take();
4534                if let Some(compactor) = ctx.run_config().history_compactor.clone() {
4535                    let preamble = conversation_history
4536                        .iter()
4537                        .take_while(|content| content.role == "system")
4538                        .count();
4539                    let trigger = if rejected.is_some() {
4540                        adk_core::CompactionTrigger::ContextLimitExceeded
4541                    } else {
4542                        adk_core::CompactionTrigger::BeforeModelCall
4543                    };
4544                    let request = adk_core::HistoryCompactionRequest::new(
4545                        &conversation_history[preamble..],
4546                        trigger,
4547                    )
4548                    .with_preamble(&conversation_history[..preamble])
4549                    .with_reported_prompt_tokens(reported_prompt_tokens)
4550                    .with_tools(&tool_declarations)
4551                    .with_config(config.as_ref());
4552                    match compactor.compact(ctx.clone(), model.clone(), request).await {
4553                        Ok(Some(compacted)) => {
4554                            conversation_history.truncate(preamble);
4555                            conversation_history.extend(compacted.history);
4556                            reported_prompt_tokens = None;
4557                            if let Some(event) = compacted.event {
4558                                yield Ok(event);
4559                            }
4560                        }
4561                        Ok(None) => {
4562                            // Sending the same request again would be rejected again.
4563                            if let Some(error) = rejected {
4564                                yield Err(error);
4565                                return;
4566                            }
4567                        }
4568                        Err(error) => {
4569                            yield Err(error);
4570                            return;
4571                        }
4572                    }
4573                }
4574
4575                // Call IDs the agent generated for a provider that sent none stay out of
4576                // what the provider receives.
4577                let mut contents = crate::requested_call::for_model(conversation_history.clone());
4578                contents.iter_mut().for_each(Content::strip_generated_call_ids);
4579                // Only the agent's own model turns carry provider-native items; a user turn
4580                // (A2A input included) or a tool result never hands a provider one.
4581                contents
4582                    .iter_mut()
4583                    .filter(|content| !matches!(content.role.as_str(), "model" | "assistant"))
4584                    .for_each(adk_core::history::strip_native);
4585                let mut request = LlmRequest {
4586                    model: model.name().to_string(),
4587                    contents,
4588                    tools: tool_declarations.clone(),
4589                    config,
4590                    // Provider-neutral continuity: carry the most recent
4591                    // response's `interaction_id` forward so transports that
4592                    // support response chaining (e.g. the Gemini Interactions
4593                    // transport, which maps this to `previous_interaction_id`)
4594                    // can continue server-side. `None` for the first turn and
4595                    // for providers that never populate `interaction_id`.
4596                    previous_response_id: last_interaction_id.clone(),
4597                };
4598
4599                if let Err(error) = tool_setup.process_llm_request(&ctx, &mut request).await {
4600                    yield Err(error);
4601                    return;
4602                }
4603
4604                // ===== ENHANCED PLUGIN: BEFORE MODEL CALL =====
4605                // Enhanced plugins can modify the request or short-circuit the model call.
4606                // They run before legacy before_model_callbacks.
4607                #[cfg(feature = "enhanced-plugins")]
4608                let (request, model_response_override_from_plugin) = {
4609                    if let Some(epm) = &enhanced_plugin_manager {
4610                        match epm.run_before_model_call(request, ctx.clone() as Arc<dyn CallbackContext>).await {
4611                            Ok(BeforeModelCallResult::Continue(modified_request)) => {
4612                                (modified_request, None)
4613                            }
4614                            Ok(BeforeModelCallResult::ShortCircuit(response)) => {
4615                                // Use a default request since we're short-circuiting
4616                                (LlmRequest::new("", vec![]), Some(response))
4617                            }
4618                            Err(e) => {
4619                                yield Err(e);
4620                                return;
4621                            }
4622                        }
4623                    } else {
4624                        (request, None)
4625                    }
4626                };
4627                #[cfg(not(feature = "enhanced-plugins"))]
4628                let model_response_override_from_plugin: Option<LlmResponse> = None;
4629
4630                // ===== BEFORE MODEL CALLBACKS =====
4631                // These can modify the request or skip the model call by returning a response
4632                let mut current_request = request;
4633                let mut model_response_override = model_response_override_from_plugin;
4634                if model_response_override.is_none() {
4635                    // Each callback takes the request; the event of a skipped call records the
4636                    // request it skipped only when the run records payloads, so only then is
4637                    // the request copied before a callback sees it.
4638                    let record_payloads = ctx.run_config().record_payloads;
4639                    for callback in
4640                        hook_callbacks.before_model.iter().chain(before_model_callbacks.iter())
4641                    {
4642                        let skipped_request = record_payloads.then(|| current_request.clone());
4643                        let request =
4644                            std::mem::replace(&mut current_request, LlmRequest::new("", vec![]));
4645                        match callback(ctx.clone() as Arc<dyn CallbackContext>, request).await {
4646                            Ok(BeforeModelResult::Continue(modified_request)) => {
4647                                // Callback may have modified the request, continue with it
4648                                current_request = modified_request;
4649                            }
4650                            Ok(BeforeModelResult::Skip(response)) => {
4651                                // Callback returned a response - skip model call
4652                                if let Some(skipped_request) = skipped_request {
4653                                    current_request = skipped_request;
4654                                }
4655                                model_response_override = Some(response);
4656                                break;
4657                            }
4658                            Err(e) => {
4659                                // Callback failed - propagate error
4660                                yield Err(e);
4661                                return;
4662                            }
4663                        }
4664                    }
4665                }
4666                let mut request = current_request;
4667                // Governed after every request rewrite, so a callback cannot re-attach a
4668                // withheld tool. A skipped model call sends nothing, so it is not governed.
4669                let withheld_builtins = if model_response_override.is_none() {
4670                    let gate = ToolGate::for_context(ctx.as_ref());
4671                    match builtin_governor.govern(&gate, &mut request.tools, &tool_map).await {
4672                        Ok(withheld) => withheld,
4673                        Err(error) => {
4674                            yield Err(error);
4675                            return;
4676                        }
4677                    }
4678                } else {
4679                    Vec::new()
4680                };
4681                let withheld_builtins = (!withheld_builtins.is_empty())
4682                    .then(|| serde_json::to_string(&withheld_builtins).unwrap_or_default());
4683                let request = request;
4684
4685                // Determine streaming source: cached response or real model
4686                let mut accumulated_content: Option<Content> = None;
4687                let mut final_provider_metadata: Option<serde_json::Value> = None;
4688
4689                let produced_by_model = model_response_override.is_none();
4690                let mut last_turn_finish_reason = None;
4691                if let Some(cached_response) = model_response_override {
4692                    // Use callback-provided response (e.g., from cache)
4693                    // Yield it as an event
4694                    accumulated_content = cached_response.content.clone();
4695                    final_provider_metadata = cached_response.provider_metadata.clone();
4696                    normalize_option_content(&mut accumulated_content);
4697                    // Text beside a tool call, or in a paused turn, reaches the client and the
4698                    // session as the final text does, so it is screened too.
4699                    let mut output_warnings = Warnings::default();
4700                    let mut citations = cached_response.citation_metadata.clone();
4701                    if let Some(content) = accumulated_content.take() {
4702                        let preamble = content
4703                            .parts
4704                            .iter()
4705                            .any(|part| matches!(part, Part::FunctionCall { .. }))
4706                            || Self::continues_turn(final_provider_metadata.as_ref());
4707                        let shown_citations = (!preamble)
4708                            .then(|| answer_citations(&content, &retrieved, citations.as_ref()))
4709                            .flatten();
4710                        let grounding =
4711                            Grounding { retrieved: &retrieved, citations: shown_citations.as_ref() };
4712                        let screened =
4713                            screen_model_output(output_guardrails.as_ref(), content, preamble, grounding).await?;
4714                        if !preamble {
4715                            citations =
4716                                answer_citations(&screened.content, &retrieved, citations.as_ref());
4717                        }
4718                        accumulated_content = Some(screened.content);
4719                        output_warnings = screened.warnings;
4720                    }
4721
4722                    let mut cached_event = Event::new(&invocation_id);
4723                    cached_event.author = agent_name.clone();
4724                    output_warnings.record_on(&mut cached_event);
4725                    cached_event.llm_response.content = accumulated_content.clone();
4726                    cached_event.llm_response.turn_complete = cached_response.turn_complete;
4727                    cached_event.llm_response.citation_metadata = citations;
4728                    cached_event.llm_response.provider_metadata = cached_response.provider_metadata.clone();
4729                    // Surface and track the response id for provider-neutral continuity.
4730                    cached_event.llm_response.interaction_id = cached_response.interaction_id.clone();
4731                    if cached_response.interaction_id.is_some() {
4732                        last_interaction_id = cached_response.interaction_id.clone();
4733                    }
4734                    cached_event.llm_request = Some(trace_json_payload(
4735                        &request,
4736                        ctx.run_config().record_payloads,
4737                        ctx.run_config().trace_payload_max_bytes,
4738                    ));
4739                    // The debug copy carries the screened content, not what the guardrails replaced.
4740                    let mut debug_response = cached_response.clone();
4741                    if !output_guardrails.is_empty() {
4742                        debug_response.content = accumulated_content.clone();
4743                    }
4744                    cached_event.provider_metadata.insert("gcp.vertex.agent.llm_response".to_string(), serde_json::to_string(&debug_response).unwrap_or_default());
4745
4746                    // Populate long_running_tool_ids for function calls from long-running tools
4747                    if let Some(ref content) = accumulated_content {
4748                        cached_event.long_running_tool_ids =
4749                            collect_long_running_tool_ids(&tool_map, content);
4750                    }
4751
4752                    yield Ok(cached_event);
4753                } else {
4754                    // One bounded copy of the request serves the span and the event.
4755                    let trace_request_json = trace_json_payload(
4756                        &request,
4757                        ctx.run_config().record_payloads,
4758                        ctx.run_config().trace_payload_max_bytes,
4759                    );
4760
4761                    // Create call_llm span with GCP attributes (works for all model types)
4762                    let llm_ts = std::time::SystemTime::now()
4763                        .duration_since(std::time::UNIX_EPOCH)
4764                        .unwrap_or_default()
4765                        .as_nanos();
4766                    let llm_event_id = format!("{}_llm_{}", invocation_id, llm_ts);
4767                    let llm_span = tracing::info_span!(
4768                        "call_llm",
4769                        "gcp.vertex.agent.event_id" = %llm_event_id,
4770                        "gcp.vertex.agent.invocation_id" = %invocation_id,
4771                        "gcp.vertex.agent.session_id" = %ctx.session_id(),
4772                        "gen_ai.conversation.id" = %ctx.session_id(),
4773                        "gcp.vertex.agent.llm_request" = %trace_request_json,
4774                        "gcp.vertex.agent.llm_response" = tracing::field::Empty  // Placeholder for later recording
4775                    );
4776                    // NOTE: do not `llm_span.enter()` here. This is an
4777                    // `async_stream` generator body: an entered guard is tied to the
4778                    // current thread, not the task, so it is neither exited when the
4779                    // generator suspends at an `.await`/`yield` nor re-entered when
4780                    // it resumes (possibly on another worker thread). That both
4781                    // detaches everything after the first suspension point from
4782                    // `call_llm` and leaks the entry onto the worker thread, where
4783                    // unrelated tasks then inherit it as a parent. Instrument the
4784                    // individual futures instead — `Instrumented::poll` enters the
4785                    // span per poll, so it is correct across suspension.
4786
4787                    // Check streaming mode from run config
4788                    use adk_core::StreamingMode;
4789                    let streaming_mode = ctx.run_config().streaming_mode;
4790                    let should_stream_to_client = matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi)
4791                        && output_guardrails.is_empty();
4792
4793                    // Reserves the call's upper-bound cost in the spend ledger and one model
4794                    // call in the run budget before it starts; the stream records the call's
4795                    // usage once, from its first non-partial response carrying usage, and
4796                    // commits its cost. A refusal stops the run before anything is sent.
4797                    let call_scope = adk_core::ModelCallScope::for_run(
4798                        ctx.run_config(),
4799                        ctx.app_name(),
4800                        &agent_name,
4801                    );
4802                    let call_metered = call_scope.budget().is_some();
4803                    // Kept for the run's `on_model_error` hooks, which see what the model was sent.
4804                    let failed_request = ctx
4805                        .run_config()
4806                        .invocation_hooks
4807                        .iter()
4808                        .any(|hook| hook.handles_model_errors())
4809                        .then(|| request.clone());
4810                    // A run without streaming asks the model for one complete response
4811                    // (Gemini's `generateContent`, as adk-python and adk-go do); otherwise
4812                    // the model streams, even when output guardrails hold the chunks back.
4813                    let stream_model =
4814                        matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi);
4815                    let mut response_stream = match call_scope
4816                        .generate(model.as_ref(), request, stream_model)
4817                        .instrument(llm_span.clone())
4818                        .await
4819                    {
4820                        Ok(stream) => stream,
4821                        Err(error) => {
4822                            // Provider errors can echo the prompt, so the message follows the
4823                            // payload rule.
4824                            llm_span.in_scope(|| {
4825                                tracing::warn!(
4826                                    agent.name = %agent_name,
4827                                    error = %error.diagnostics(),
4828                                    error.message = %traced_message(ctx.run_config(), &error.message),
4829                                    "model call failed"
4830                                )
4831                            });
4832                            // A request too long for the model is compacted and sent once more.
4833                            if ctx.run_config().history_compactor.is_some()
4834                                && adk_core::intra_compaction::is_context_limit_error(&error)
4835                                && !std::mem::replace(&mut resent_after_compaction, true)
4836                            {
4837                                rejected_as_too_long = Some(error);
4838                                iteration -= 1;
4839                                continue 'model_calls;
4840                            }
4841                            // A hook's response, from a fallback model for example, answers
4842                            // the turn in the failed call's place.
4843                            match recover_model_error(&ctx, failed_request.as_ref(), &error).await {
4844                                Ok(Some(response)) => {
4845                                    Box::pin(futures::stream::iter([Ok(response)]))
4846                                        as adk_core::LlmResponseStream
4847                                }
4848                                Ok(None) => {
4849                                    yield Err(error);
4850                                    return;
4851                                }
4852                                Err(hook_error) => {
4853                                    yield Err(hook_error);
4854                                    return;
4855                                }
4856                            }
4857                        }
4858                    };
4859
4860                    use futures::StreamExt;
4861
4862                    // Track last chunk for final event metadata (used in None mode)
4863                    let mut last_chunk: Option<LlmResponse> = None;
4864
4865                    // Stream and process chunks with AfterModel callbacks
4866                    while let Some(chunk_result) =
4867                        response_stream.next().instrument(llm_span.clone()).await
4868                    {
4869                        // Cooperative cancellation: stop consuming the model
4870                        // stream promptly when the invocation is cancelled. This
4871                        // drops `response_stream`, releasing the provider connection.
4872                        if ctx.is_cancelled() {
4873                            llm_span.in_scope(|| {
4874                                tracing::info!(agent.name = %agent_name, "invocation cancelled during LLM streaming")
4875                            });
4876                            return;
4877                        }
4878                        let mut chunk = match chunk_result {
4879                            Ok(c) => c,
4880                            Err(e) => {
4881                                llm_span.in_scope(|| {
4882                                    tracing::warn!(
4883                                        agent.name = %agent_name,
4884                                        error = %e.diagnostics(),
4885                                        error.message = %traced_message(ctx.run_config(), &e.message),
4886                                        "model stream failed"
4887                                    )
4888                                });
4889                                // A request too long for the model fails before any output;
4890                                // it is compacted and sent once more.
4891                                if last_chunk.is_none()
4892                                    && ctx.run_config().history_compactor.is_some()
4893                                    && adk_core::intra_compaction::is_context_limit_error(&e)
4894                                    && !std::mem::replace(&mut resent_after_compaction, true)
4895                                {
4896                                    rejected_as_too_long = Some(e);
4897                                    iteration -= 1;
4898                                    continue 'model_calls;
4899                                }
4900                                // A hook's response replaces the whole failed response, so
4901                                // the deltas already received are dropped.
4902                                match recover_model_error(&ctx, failed_request.as_ref(), &e).await {
4903                                    Ok(Some(response)) => {
4904                                        accumulated_content = None;
4905                                        response_stream = Box::pin(futures::stream::iter([Ok(response)]));
4906                                        continue;
4907                                    }
4908                                    Ok(None) => {
4909                                        yield Err(e);
4910                                        return;
4911                                    }
4912                                    Err(hook_error) => {
4913                                        yield Err(hook_error);
4914                                        return;
4915                                    }
4916                                }
4917                            }
4918                        };
4919                        // ===== AFTER MODEL CALLBACKS (per chunk) =====
4920                        // Callbacks can modify each streaming chunk
4921                        for callback in
4922                            hook_callbacks.after_model.iter().chain(after_model_callbacks.iter())
4923                        {
4924                            match callback(ctx.clone() as Arc<dyn CallbackContext>, chunk.clone())
4925                                .instrument(llm_span.clone())
4926                                .await
4927                            {
4928                                Ok(Some(modified_chunk)) => {
4929                                    chunk = replace_chunk(&chunk, modified_chunk);
4930                                    break;
4931                                }
4932                                Ok(None) => {
4933                                    // Continue to next callback
4934                                    continue;
4935                                }
4936                                Err(e) => {
4937                                    // Callback failed - propagate error
4938                                    yield Err(e);
4939                                    return;
4940                                }
4941                            }
4942                        }
4943
4944                        normalize_option_content(&mut chunk.content);
4945
4946                        // Accumulate content for conversation history (always needed)
4947                        if let Some(chunk_content) = chunk.content.clone() {
4948                            if !chunk.partial && chunk.provider_metadata.as_ref()
4949                                .and_then(|metadata| metadata.get("content_complete"))
4950                                .and_then(serde_json::Value::as_bool) == Some(true)
4951                            {
4952                                accumulated_content = Some(chunk_content);
4953                            } else if let Some(ref mut acc) = accumulated_content {
4954                                append_streamed_parts(&mut acc.parts, chunk_content.parts);
4955                            } else {
4956                                accumulated_content = Some(chunk_content);
4957                            }
4958                        }
4959                        // Tool-call markup can span deltas, so it is parsed again once the
4960                        // text is complete.
4961                        if !chunk.partial {
4962                            normalize_option_content(&mut accumulated_content);
4963                        }
4964
4965                        // For SSE/Bidi mode: yield each chunk immediately with stable event ID
4966                        if should_stream_to_client {
4967                            let long_running_tool_ids = chunk
4968                                .content
4969                                .as_ref()
4970                                .map(|content| collect_long_running_tool_ids(&tool_map, content))
4971                                .unwrap_or_default();
4972                            let mut event = build_partial_llm_event(
4973                                &llm_event_id,
4974                                &invocation_id,
4975                                &agent_name,
4976                                &trace_request_json,
4977                                &chunk,
4978                                long_running_tool_ids,
4979                            );
4980                            if call_metered {
4981                                event.provider_metadata.insert(
4982                                    adk_core::BUDGET_RECORDED_KEY.to_string(),
4983                                    "true".to_string(),
4984                                );
4985                            }
4986                            if !chunk.partial
4987                                && let Some(withheld) = &withheld_builtins
4988                            {
4989                                event.provider_metadata.insert(
4990                                    adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
4991                                    withheld.clone(),
4992                                );
4993                            }
4994                            // Runner persists terminal events as complete content.
4995                            // Providers can finish with tools/metadata after text
4996                            // deltas, so the last chunk alone is insufficient.
4997                            if !chunk.partial {
4998                                event.llm_response.content = accumulated_content.clone();
4999                                if let Some(metadata) = event.llm_response.provider_metadata
5000                                    .get_or_insert_with(|| serde_json::json!({}))
5001                                    .as_object_mut()
5002                                {
5003                                    metadata.insert("content_complete".into(), true.into());
5004                                }
5005                            }
5006                            yield Ok(event);
5007                        }
5008
5009                        // Track the response id for provider-neutral continuity.
5010                        // Transports that support response chaining populate
5011                        // `interaction_id`; others leave it `None` (no-op).
5012                        if chunk.interaction_id.is_some() {
5013                            last_interaction_id = chunk.interaction_id.clone();
5014                        }
5015
5016                        if let Some(usage) = &chunk.usage_metadata
5017                            && usage.prompt_token_count > 0
5018                        {
5019                            reported_prompt_tokens = Some(usage.prompt_token_count as u64);
5020                        }
5021                        if chunk.finish_reason.is_some() {
5022                            last_turn_finish_reason = chunk.finish_reason;
5023                        }
5024                        // Store last chunk for final event metadata
5025                        last_chunk = Some(chunk.clone());
5026
5027                        // Check if turn is complete
5028                        if chunk.turn_complete {
5029                            break;
5030                        }
5031                    }
5032
5033                    if let Some(last) = &last_chunk {
5034                        final_provider_metadata = last.provider_metadata.clone();
5035                    }
5036                    resent_after_compaction = false;
5037                    normalize_option_content(&mut accumulated_content);
5038
5039                    // A stream whose last chunk is partial never produced the complete event
5040                    // the runner persists, so one is emitted here with the whole response.
5041                    if should_stream_to_client
5042                        && let Some(last) = last_chunk.as_ref().filter(|chunk| chunk.partial)
5043                        && accumulated_content.is_some()
5044                    {
5045                        let mut closing = last.clone();
5046                        closing.partial = false;
5047                        closing.content = accumulated_content.clone();
5048                        closing.turn_complete = !closing
5049                            .content
5050                            .as_ref()
5051                            .is_some_and(|content| {
5052                                content.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
5053                            });
5054                        let long_running_tool_ids = closing
5055                            .content
5056                            .as_ref()
5057                            .map(|content| collect_long_running_tool_ids(&tool_map, content))
5058                            .unwrap_or_default();
5059                        let mut event = build_partial_llm_event(
5060                            &llm_event_id,
5061                            &invocation_id,
5062                            &agent_name,
5063                            &trace_request_json,
5064                            &closing,
5065                            long_running_tool_ids,
5066                        );
5067                        if call_metered {
5068                            event.provider_metadata.insert(
5069                                adk_core::BUDGET_RECORDED_KEY.to_string(),
5070                                "true".to_string(),
5071                            );
5072                        }
5073                        if let Some(withheld) = &withheld_builtins {
5074                            event.provider_metadata.insert(
5075                                adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
5076                                withheld.clone(),
5077                            );
5078                        }
5079                        if let Some(metadata) = event.llm_response.provider_metadata
5080                            .get_or_insert_with(|| serde_json::json!({}))
5081                            .as_object_mut()
5082                        {
5083                            metadata.insert("content_complete".into(), true.into());
5084                        }
5085                        yield Ok(event);
5086                    }
5087                    // A stream that ended without a non-partial usage report is settled
5088                    // here, before any tool runs, from the best usage it carried.
5089                    drop(response_stream);
5090                    let metered = call_metered;
5091
5092                    // For None mode: yield single final event with accumulated content
5093                    if !should_stream_to_client {
5094                        // Text beside a tool call, or in a paused turn, reaches the client and
5095                        // the session as the final text does, so it is screened too.
5096                        let mut output_warnings = Warnings::default();
5097                        let provider_citations =
5098                            last_chunk.as_ref().and_then(|chunk| chunk.citation_metadata.clone());
5099                        let mut citations = provider_citations.clone();
5100                        if let Some(content) = accumulated_content.take() {
5101                            let preamble = content
5102                                .parts
5103                                .iter()
5104                                .any(|part| matches!(part, Part::FunctionCall { .. }))
5105                                || Self::continues_turn(final_provider_metadata.as_ref());
5106                            let shown_citations = (!preamble)
5107                                .then(|| {
5108                                    answer_citations(&content, &retrieved, provider_citations.as_ref())
5109                                })
5110                                .flatten();
5111                            let grounding = Grounding {
5112                                retrieved: &retrieved,
5113                                citations: shown_citations.as_ref(),
5114                            };
5115                            let screened = screen_model_output(
5116                                output_guardrails.as_ref(),
5117                                content,
5118                                preamble,
5119                                grounding,
5120                            )
5121                            .instrument(llm_span.clone())
5122                            .await?;
5123                            if !preamble {
5124                                citations = answer_citations(
5125                                    &screened.content,
5126                                    &retrieved,
5127                                    provider_citations.as_ref(),
5128                                );
5129                            }
5130                            accumulated_content = Some(screened.content);
5131                            output_warnings = screened.warnings;
5132                        }
5133                        // The debug copy of the last chunk carries the screened content, not
5134                        // what the guardrails replaced.
5135                        if !output_guardrails.is_empty()
5136                            && let Some(last) = last_chunk.as_mut()
5137                            && last.content.is_some()
5138                        {
5139                            last.content = accumulated_content.clone();
5140                        }
5141
5142                        let long_running_tool_ids = accumulated_content
5143                            .as_ref()
5144                            .map(|content| collect_long_running_tool_ids(&tool_map, content))
5145                            .unwrap_or_default();
5146                        let mut final_event = build_final_llm_event(
5147                            &llm_event_id,
5148                            &invocation_id,
5149                            &agent_name,
5150                            &trace_request_json,
5151                            accumulated_content.as_ref(),
5152                            last_chunk.as_ref(),
5153                            long_running_tool_ids,
5154                        );
5155                        output_warnings.record_on(&mut final_event);
5156                        final_event.llm_response.citation_metadata = citations;
5157                        if metered {
5158                            final_event.provider_metadata.insert(
5159                                adk_core::BUDGET_RECORDED_KEY.to_string(),
5160                                "true".to_string(),
5161                            );
5162                        }
5163                        if let Some(withheld) = &withheld_builtins {
5164                            final_event.provider_metadata.insert(
5165                                adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
5166                                withheld.clone(),
5167                            );
5168                        }
5169                        yield Ok(final_event);
5170                    }
5171
5172                    // A provider that reports a terminal error inside an `Ok`
5173                    // response ends the turn. The event above already carries the
5174                    // error fields so the failure is observable and persisted;
5175                    // this converts it into a `Result` failure so callers, retry
5176                    // policy, and telemetry see it rather than reading an empty
5177                    // turn as success.
5178                    //
5179                    // In this workspace `error_code` marks a genuine failure —
5180                    // truncation is reported through `finish_reason`
5181                    // (`FinishReason::MaxTokens`), not through `error_code`.
5182                    //
5183                    // A refusal or a malformed tool call ends the turn the same way, with
5184                    // or without an `error_code`: the event above keeps the refusal text
5185                    // and finish reason, and no tool call of the turn runs.
5186                    let finish_failure = finish_error(
5187                        last_turn_finish_reason,
5188                        last_chunk
5189                            .as_ref()
5190                            .and_then(|last| last.error_message.clone())
5191                            .or_else(|| {
5192                                accumulated_content.as_ref().map(|content| {
5193                                    content.parts.iter().filter_map(Part::text).collect::<String>()
5194                                })
5195                            })
5196                            .as_deref(),
5197                        last_chunk.as_ref().and_then(|last| last.error_code.as_deref()),
5198                    );
5199                    if let Some(error) = finish_failure {
5200                        llm_span.in_scope(|| {
5201                            tracing::error!(
5202                                error = %error.diagnostics(),
5203                                agent = %agent_name,
5204                                "model turn ended without an answer it can act on"
5205                            )
5206                        });
5207                        yield Err(error);
5208                        return;
5209                    }
5210                    if let Some(ref last) = last_chunk
5211                        && let Some(ref code) = last.error_code
5212                    {
5213                        // Provider text can echo the request, so the caller gets a bounded
5214                        // excerpt and the log follows the payload rule.
5215                        let message = last
5216                            .error_message
5217                            .as_deref()
5218                            .map(adk_core::upstream_excerpt)
5219                            .unwrap_or("provider reported a terminal error");
5220                        // The provider's own code is preserved in the ADK error code
5221                        // so retry policy and telemetry can key on it.
5222                        // Built before the yield point: a borrow may not cross it.
5223                        // `AdkError::code` is `&'static str`, so the provider's own
5224                        // code travels in the details metadata instead, where retry
5225                        // policy and telemetry can read it.
5226                        let mut details = adk_core::ErrorDetails::default();
5227                        details
5228                            .metadata
5229                            .insert("provider_error_code".to_string(), serde_json::json!(code));
5230                        let provider_error = adk_core::AdkError::new(
5231                            adk_core::ErrorComponent::Model,
5232                            adk_core::ErrorCategory::Internal,
5233                            "model.provider_error",
5234                            format!("{code}: {message}"),
5235                        )
5236                        .with_details(details);
5237                        llm_span.in_scope(|| {
5238                            tracing::error!(
5239                                error = %provider_error.diagnostics(),
5240                                error.message = %traced_message(ctx.run_config(), message),
5241                                agent = %agent_name,
5242                                "model reported a terminal error"
5243                            )
5244                        });
5245                        yield Err(provider_error);
5246                        return;
5247                    }
5248
5249                    // Record LLM response to span before guard drops
5250                    if let Some(ref content) = accumulated_content {
5251                        let response_json = trace_json_payload(
5252                            content,
5253                            ctx.run_config().record_payloads,
5254                            ctx.run_config().trace_payload_max_bytes,
5255                        );
5256                        llm_span.record("gcp.vertex.agent.llm_response", &response_json);
5257                    }
5258                }
5259
5260                // ===== ENHANCED PLUGIN: AFTER MODEL CALL =====
5261                // Enhanced plugins can modify the accumulated model response.
5262                // They run after the full response is accumulated (not per-chunk).
5263                #[cfg(feature = "enhanced-plugins")]
5264                if let Some(epm) = &enhanced_plugin_manager
5265                    && let Some(ref content) = accumulated_content {
5266                        let response_for_hook = LlmResponse {
5267                            content: Some(content.clone()),
5268                            provider_metadata: final_provider_metadata.clone(),
5269                            ..Default::default()
5270                        };
5271                        match epm.run_after_model_call(response_for_hook, ctx.clone() as Arc<dyn CallbackContext>).await {
5272                            Ok(adk_plugin::AfterModelCallResult::Continue(modified_response)) => {
5273                                accumulated_content = modified_response.content;
5274                                if modified_response.provider_metadata.is_some() {
5275                                    final_provider_metadata = modified_response.provider_metadata;
5276                                }
5277                            }
5278                            Err(e) => {
5279                                yield Err(e);
5280                                return;
5281                            }
5282                        }
5283                    }
5284
5285                // After streaming/caching completes, check for function calls in accumulated content
5286                let function_call_names: Vec<String> = accumulated_content.as_ref()
5287                    .map(|c| c.parts.iter()
5288                        .filter_map(|p| {
5289                            if let Part::FunctionCall { name, .. } = p {
5290                                Some(name.clone())
5291                            } else {
5292                                None
5293                            }
5294                        })
5295                        .collect())
5296                    .unwrap_or_default();
5297
5298                let has_function_calls = !function_call_names.is_empty();
5299                let continues_turn = Self::continues_turn(final_provider_metadata.as_ref());
5300
5301                // Check if ALL function calls are from long-running tools
5302                // If so, we should NOT continue the loop - the tool returned a pending status
5303                // and the agent/client will poll for completion later
5304                let all_calls_are_long_running = has_function_calls && function_call_names.iter().all(|name| {
5305                    tool_map.get(name)
5306                        .map(|t| t.is_long_running())
5307                        .unwrap_or(false)
5308                });
5309
5310                // Add final content to history
5311                if let Some(ref content) = accumulated_content {
5312                    conversation_history.push(Self::augment_content_for_history(
5313                        content,
5314                        final_provider_metadata.as_ref(),
5315                    ));
5316                }
5317
5318                // Native server tools can pause a turn without calling a client
5319                // tool. Continue through this same bounded, cancellable loop.
5320                if !has_function_calls && continues_turn {
5321                    continue;
5322                }
5323
5324                if !has_function_calls {
5325                    // ===== EMPTY MODEL TURN =====
5326                    // A turn the model ended with no answer — no parts, only thinking, or only
5327                    // whitespace — fails the run, so callers and retry policy can tell it from
5328                    // an answer. A callback that answered instead of the model is not checked.
5329                    if produced_by_model
5330                        && !accumulated_content.as_ref().is_some_and(has_answer_content)
5331                    {
5332                        yield Err(empty_response_error(last_turn_finish_reason));
5333                        return;
5334                    }
5335
5336                    // ===== OUTPUT SCHEMA VALIDATION =====
5337                    // When output_schema is set, validate the response text against
5338                    // the schema. If invalid, retry with a correction prompt up to
5339                    // output_max_retries times.
5340                    if let Some(schema) = &prompt_config.output_schema {
5341                        let text = accumulated_content
5342                            .as_ref()
5343                            .map(|c| {
5344                                c.parts
5345                                    .iter()
5346                                    .filter_map(|p| {
5347                                        if let Part::Text { text } = p {
5348                                            Some(text.as_str())
5349                                        } else {
5350                                            None
5351                                        }
5352                                    })
5353                                    .collect::<Vec<_>>()
5354                                    .join("")
5355                            })
5356                            .unwrap_or_default();
5357
5358                        if !text.is_empty()
5359                            && let Err(validation_error) = validate_output_against_schema(&text, schema)
5360                        {
5361                                if schema_retry_count >= output_max_retries {
5362                                    yield Err(adk_core::AdkError::agent(format!(
5363                                        "output schema validation failed after {} attempts",
5364                                        output_max_retries
5365                                    )));
5366                                    return;
5367                                }
5368                                schema_retry_count += 1;
5369
5370                                // Append a correction prompt and retry
5371                                let correction = format!(
5372                                    "Your output did not match the required schema. Error: {}. Please produce valid JSON matching the schema.",
5373                                    validation_error
5374                                );
5375                                conversation_history.push(Content {
5376                                    role: "user".to_string(),
5377                                    parts: vec![Part::Text { text: correction }],
5378                                });
5379                                continue;
5380                        }
5381                    }
5382
5383                    // Persist the final output only once it has passed schema validation, so a
5384                    // rejected attempt never lands in `state[output_key]`.
5385                    if let Some(ref output_key) = output_key
5386                        && let Some(ref content) = accumulated_content
5387                    {
5388                        // Structured output is stored as the JSON it validated as.
5389                        let text_parts =
5390                            output_text(content, prompt_config.output_schema.is_some());
5391                        if !text_parts.is_empty() {
5392                            let mut state_event = Event::new(&invocation_id);
5393                            state_event.author = agent_name.clone();
5394                            state_event.actions.state_delta.insert(
5395                                output_key.clone(),
5396                                serde_json::Value::String(text_parts),
5397                            );
5398                            yield Ok(state_event);
5399                        }
5400                    }
5401
5402                    // No function calls, we're done
5403                    // Record LLM response for tracing
5404                    if let Some(ref content) = accumulated_content {
5405                        let response_json = trace_json_payload(
5406                            content,
5407                            ctx.run_config().record_payloads,
5408                            ctx.run_config().trace_payload_max_bytes,
5409                        );
5410                        tracing::Span::current().record("gcp.vertex.agent.llm_response", &response_json);
5411                    }
5412
5413                    tracing::info!(agent.name = %agent_name, "Agent execution complete");
5414                    break;
5415                }
5416
5417                // Execute function calls and add responses to history
5418                if let Some(content) = &accumulated_content {
5419                    // ===== RESOLVE TOOL EXECUTION STRATEGY =====
5420                    // Per-agent override; defaults to Sequential if not set.
5421                    let strategy = ToolDispatchMode::resolve(
5422                        agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
5423                        parallelize_agent_delegations,
5424                    );
5425
5426                    // Providers that omit call IDs get one unique to this model turn, so two
5427                    // turns of one invocation never share an idempotency key.
5428                    let fc_parts = collect_function_calls(
5429                        content,
5430                        &format!("{invocation_id}_{}", uuid::Uuid::new_v4().simple()),
5431                    );
5432
5433                    // ===== HANDLE transfer_to_agent BEFORE DISPATCH =====
5434                    // Transfer calls cause an immediate return from the stream,
5435                    // so they must be handled inline regardless of strategy.
5436                    let mut transfer_handled = false;
5437                    // Calls already answered by an invalid-target error, so a later valid
5438                    // transfer does not answer them a second time.
5439                    let mut answered_calls = HashSet::new();
5440                    for call in &fc_parts {
5441                        if call.name == "transfer_to_agent" {
5442                            let target_agent = call
5443                                .args
5444                                .get("agent_name")
5445                                .and_then(|value| value.as_str())
5446                                .unwrap_or_default()
5447                                .to_string();
5448
5449                            let valid_target = valid_transfer_targets.iter().any(|n| n == &target_agent);
5450                            if !valid_target {
5451                                let mut refusal = Part::FunctionResponse {
5452                                    function_response: FunctionResponseData::new(
5453                                        call.name.clone(),
5454                                        serde_json::json!({
5455                                            "error": format!(
5456                                                "Agent '{}' not found. Available agents: {:?}",
5457                                                target_agent, valid_transfer_targets
5458                                            )
5459                                        }),
5460                                    ),
5461                                    id: call.id.clone(),
5462                                    annotations: None,
5463                                };
5464                                refusal.set_tool_result_status(ToolResultStatus::NotRun, None);
5465                                let error_content =
5466                                    Content { role: "function".to_string(), parts: vec![refusal] };
5467                                conversation_history.push(error_content.clone());
5468                                let mut error_event = Event::new(&invocation_id);
5469                                error_event.author = agent_name.clone();
5470                                error_event.llm_response.content = Some(error_content);
5471                                yield Ok(error_event);
5472                                answered_calls.insert(call.index);
5473                                continue;
5474                            }
5475
5476                            // Every call in this model turn gets exactly one response, so providers
5477                            // that require one per call accept any later history containing it.
5478                            let responses = fc_parts
5479                                .iter()
5480                                .filter(|other| !answered_calls.contains(&other.index))
5481                                .map(|other| {
5482                                    let transfers = other.index == call.index;
5483                                    let response = if transfers {
5484                                        serde_json::json!({ "transferred_to": target_agent })
5485                                    } else {
5486                                        serde_json::json!({
5487                                            "error": format!("not run: control transferred to {target_agent}")
5488                                        })
5489                                    };
5490                                    let mut part = Part::FunctionResponse {
5491                                        function_response: FunctionResponseData::new(
5492                                            other.name.clone(),
5493                                            response,
5494                                        ),
5495                                        id: other.id.clone(),
5496                                        annotations: None,
5497                                    };
5498                                    if !transfers {
5499                                        part.set_tool_result_status(ToolResultStatus::NotRun, None);
5500                                    }
5501                                    part
5502                                })
5503                                .collect();
5504                            let mut transfer_event = Event::new(&invocation_id);
5505                            transfer_event.author = agent_name.clone();
5506                            transfer_event.llm_response.content =
5507                                Some(Content { role: "function".to_string(), parts: responses });
5508                            transfer_event.actions.transfer_to_agent = Some(target_agent);
5509                            yield Ok(transfer_event);
5510                            transfer_handled = true;
5511                            break;
5512                        }
5513                    }
5514                    if transfer_handled {
5515                        return;
5516                    }
5517
5518                    // Filter out transfer_to_agent and built-in tools
5519                    let fc_parts: Vec<_> = fc_parts
5520                        .into_iter()
5521                        .filter(|call| {
5522                            if call.name == "transfer_to_agent" {
5523                                return false;
5524                            }
5525                            if let Some(tool) = tool_map.get(&call.name)
5526                                && tool.is_builtin()
5527                            {
5528                                adk_telemetry::debug!(tool.name = %call.name, "skipping built-in tool execution");
5529                                return false;
5530                            }
5531                            true
5532                        })
5533                        .collect();
5534
5535                    // ===== RUN BUDGET: TOOL CALLS =====
5536                    // The whole batch is reserved before any call starts. A batch that does
5537                    // not fit is answered with "not run" responses, so the history keeps one
5538                    // response per call, and the run ends with the budget error.
5539                    if let Some(tracker) = budget_tracker.as_ref()
5540                        && let Err(exceeded) = tracker.begin_tool_calls(fc_parts.len() as u64)
5541                    {
5542                        let cause = adk_core::AdkError::from(exceeded.clone());
5543                        let parts = fc_parts
5544                            .iter()
5545                            .map(|call| {
5546                                let mut part = Part::FunctionResponse {
5547                                    function_response: FunctionResponseData::new(
5548                                        call.name.clone(),
5549                                        serde_json::json!({ "error": format!("not run: {exceeded}") }),
5550                                    ),
5551                                    id: call.id.clone(),
5552                                    annotations: None,
5553                                };
5554                                part.set_tool_result_status(ToolResultStatus::NotRun, Some(&cause));
5555                                part
5556                            })
5557                            .collect();
5558                        let mut budget_event = Event::new(&invocation_id);
5559                        budget_event.author = agent_name.clone();
5560                        budget_event.llm_response.content =
5561                            Some(Content { role: "function".to_string(), parts });
5562                        yield Ok(budget_event);
5563                        yield Err(exceeded.into());
5564                        return;
5565                    }
5566
5567                    // ===== THE BATCH, BEFORE DISPATCH =====
5568                    // The confirmation handler sees the turn's calls once, so it can review
5569                    // several held edits as one change set (spec 3.1 §7.26, §10 A2).
5570                    if !fc_parts.is_empty()
5571                        && let Some(handler) = ctx.run_config().tool_confirmation_handler.clone()
5572                    {
5573                        let origins: Vec<Option<adk_core::ToolOrigin>> = fc_parts
5574                            .iter()
5575                            .map(|call| {
5576                                tool_map.get(&call.name).map(|tool| adk_core::ToolOrigin::of(tool.as_ref()))
5577                            })
5578                            .collect();
5579                        let batch: Vec<adk_core::BatchCall<'_>> = fc_parts
5580                            .iter()
5581                            .zip(&origins)
5582                            .map(|(call, origin)| {
5583                                let entry = adk_core::BatchCall::new(&call.name, &call.args)
5584                                    .with_function_call_id(&call.function_call_id);
5585                                match origin {
5586                                    Some(origin) => entry.with_origin(origin),
5587                                    None => entry,
5588                                }
5589                            })
5590                            .collect();
5591                        handler.batch_started(&batch).await;
5592                    }
5593
5594                    // Wrap circuit breaker in Mutex for shared access across parallel futures.
5595                    let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
5596
5597                    // Create concurrency manager for semaphore-based tool dispatch enforcement.
5598                    // Per-tool overrides take precedence over the global limit.
5599                    let concurrency_manager = adk_core::ToolConcurrencyManager::new(
5600                        &ctx.run_config().tool_concurrency,
5601                    );
5602
5603                    // Channel for streaming tool progress (stdout/stderr) onto the
5604                    // agent's EventStream while tools are still executing. Each
5605                    // AgentToolContext gets a clone; the dispatch loop below drains
5606                    // it concurrently and yields progress events to the client.
5607                    let (progress_tx, mut progress_rx) =
5608                        tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
5609                    let progress_overflow = ProgressOverflow::default();
5610
5611                    let executor = ToolExecutor {
5612                        ctx: ctx.clone(),
5613                        agent_name: &agent_name,
5614                        tool_map: &tool_map,
5615                        tool_retry_budgets: &tool_retry_budgets,
5616                        default_retry_budget: &default_retry_budget,
5617                        output_guardrails: output_guardrails.as_ref(),
5618                        before_tool_callbacks: &before_tool_callbacks,
5619                        after_tool_callbacks: &after_tool_callbacks,
5620                        after_tool_callbacks_full: &after_tool_callbacks_full,
5621                        on_tool_error_callbacks: &on_tool_error_callbacks,
5622                        hook_callbacks: &hook_callbacks,
5623                        tool_confirmation_policy: &tool_confirmation_policy,
5624                        tool_guardrails: tool_guardrails.as_ref(),
5625                        cb_mutex: &cb_mutex,
5626                        invocation_id: &invocation_id,
5627                        concurrency_manager: &concurrency_manager,
5628                        progress_tx: progress_tx.clone(),
5629                        progress_overflow: progress_overflow.clone(),
5630                        tool_timeout,
5631                        expose_tool_error_messages,
5632                        approval_failed: tokio::sync::watch::channel(false).0,
5633                        halted_batches: Default::default(),
5634                        #[cfg(feature = "enhanced-plugins")]
5635                        enhanced_plugin_manager: &enhanced_plugin_manager,
5636                    };
5637
5638                    // Cooperative cancellation: skip tool execution if the
5639                    // invocation was cancelled while the model was streaming.
5640                    if ctx.is_cancelled() {
5641                        tracing::info!(agent.name = %agent_name, "invocation cancelled before tool dispatch");
5642                        return;
5643                    }
5644
5645                    // ===== DISPATCH BASED ON STRATEGY =====
5646                    // Scoped so the dispatch future (which borrows the executor
5647                    // and circuit-breaker mutex) is dropped before we reclaim
5648                    // `cb_mutex` below.
5649                    let mut results = {
5650                        let dispatch = executor.dispatch(strategy, fc_parts);
5651
5652                        // Drain tool progress concurrently with execution, yielding
5653                        // each chunk as a partial Event the moment it arrives. The
5654                        // dispatch future and the progress receiver are polled together
5655                        // so output streams live rather than buffering until the tool
5656                        // finishes.
5657                        tokio::pin!(dispatch);
5658                        let results = loop {
5659                            tokio::select! {
5660                                biased;
5661                                Some(progress_event) = progress_rx.recv() => {
5662                                    yield Ok(progress_event);
5663                                }
5664                                done = &mut dispatch => break done,
5665                            }
5666                        };
5667                        // Flush any progress chunks buffered between the last poll and completion.
5668                        while let Ok(progress_event) = progress_rx.try_recv() {
5669                            yield Ok(progress_event);
5670                        }
5671                        // Then the markers that found the queue full.
5672                        let markers = std::mem::take(
5673                            &mut *progress_overflow
5674                                .lock()
5675                                .unwrap_or_else(std::sync::PoisonError::into_inner),
5676                        );
5677                        for marker in markers {
5678                            yield Ok(marker);
5679                        }
5680                        match results {
5681                            Ok(results) => results,
5682                            Err(error) => {
5683                                yield Err(error);
5684                                return;
5685                            }
5686                        }
5687                    };
5688                    // Preserve LLM-returned order even when tool futures finish out of order.
5689                    results.sort_by_key(|r| r.index);
5690
5691                    // Restore circuit breaker state from the mutex
5692                    circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());
5693
5694                    // Events were already emitted on completion. Only model context
5695                    // is assembled in call order; never emit a second result event.
5696                    // A held call has not run; it counts once, when a later run resumes it.
5697                    if let Some(tracker) = budget_tracker.as_ref() {
5698                        let held = results.iter().filter(|result| result.pending.is_some()).count();
5699                        tracker.release_tool_calls(held as u64);
5700                    }
5701                    let mut held_for_confirmation = Vec::new();
5702                    for result in results {
5703                        if result.escalate_or_skip {
5704                            return;
5705                        }
5706                        held_for_confirmation.extend(result.pending);
5707                        retrieved.extend(result.actions.grounding_sources);
5708                        conversation_history.push(result.content);
5709                    }
5710
5711                    // ===== TOOL CONFIRMATION INTERRUPT =====
5712                    // A call held for a decision ends the run. Its request carries the final
5713                    // arguments, and the next run that has a decision for it resumes the call
5714                    // before its first model call.
5715                    if !held_for_confirmation.is_empty() {
5716                        for request in held_for_confirmation {
5717                            yield Ok(confirmation_event(&invocation_id, &agent_name, request));
5718                        }
5719                        return;
5720                    }
5721
5722                    // A tool can update session state as part of its response. Resolve
5723                    // toolsets again before the next model turn so context-sensitive
5724                    // toolsets (notably progressive skills) can expose newly activated
5725                    // capabilities in the same invocation.
5726                    let refreshed_tools = match tool_setup.resolve(&ctx).await {
5727                        Ok(tools) => tools,
5728                        Err(error) => {
5729                            yield Err(error);
5730                            return;
5731                        }
5732                    };
5733                    tool_map = refreshed_tools.map;
5734                    tool_declarations = refreshed_tools.declarations;
5735                    valid_transfer_targets = refreshed_tools.transfer_targets;
5736                    steering_due = true;
5737                }
5738
5739                // If all function calls were from long-running tools, we need ONE more model call
5740                // to let the model generate a user-friendly response about the pending task
5741                // But we mark this as the final iteration to prevent infinite loops
5742                if all_calls_are_long_running {
5743                    // Continue to next iteration for model to respond, but this will be the last
5744                    // The model will see the tool response and generate text like "Started task X..."
5745                    // On next iteration, there won't be function calls, so we'll break naturally
5746                }
5747            }
5748        });
5749
5750        let s = stream! {
5751            use futures::StreamExt;
5752            let ctx = stage_ctx;
5753            let invocation_id = stage_invocation_id;
5754            let agent_name = stage_agent_name;
5755
5756            // ===== BEFORE AGENT CALLBACKS =====
5757            // The first callback that returns content answers for the agent, which then skips
5758            // its body and goes to the after-agent stage.
5759            let mut answered = false;
5760            for callback in hook_before_agent.iter().chain(before_agent_callbacks.iter()) {
5761                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
5762                    Ok(Some(content)) => {
5763                        let mut early_event = Event::new(&invocation_id);
5764                        early_event.author = agent_name.clone();
5765                        // The callback's answer is the agent's output, so `output_key` keeps it.
5766                        if let Some(key) = &stage_output_key {
5767                            let text = output_text(&content, structured_output);
5768                            if !text.is_empty() {
5769                                early_event
5770                                    .actions
5771                                    .state_delta
5772                                    .insert(key.clone(), serde_json::Value::String(text));
5773                            }
5774                        }
5775                        early_event.llm_response.content = Some(content);
5776                        yield Ok(early_event);
5777                        answered = true;
5778                        break;
5779                    }
5780                    Ok(None) => {}
5781                    Err(e) => {
5782                        yield Err(e);
5783                        return;
5784                    }
5785                }
5786            }
5787
5788            if !answered {
5789                // A body that is dropped before it finishes — the run cancelled, the client
5790                // gone, a parallel sibling escalated — still runs the after-agent stage. A
5791                // durable attempt dropped by its worker is resumed by the worker that
5792                // recovers the run, which runs the stage then.
5793                let mut on_drop = AfterAgentOnDrop::armed(
5794                    Arc::clone(&hook_after_agent),
5795                    Arc::clone(&after_agent_callbacks),
5796                    ctx.clone() as Arc<dyn CallbackContext>,
5797                );
5798                if ctx.run_config().durable_run_id.is_some() {
5799                    on_drop.disarm();
5800                }
5801                let mut body = body;
5802                let mut finished = true;
5803                while let Some(item) = body.next().await {
5804                    // A failed agent has not completed, and a held call resumes the agent in a
5805                    // later run, which runs the stage then.
5806                    let pauses = match &item {
5807                        Err(_) => true,
5808                        Ok(event) => event.actions.tool_confirmation.is_some(),
5809                    };
5810                    if pauses {
5811                        finished = false;
5812                        on_drop.disarm();
5813                    }
5814                    yield item;
5815                }
5816                on_drop.disarm();
5817                if !finished {
5818                    return;
5819                }
5820            }
5821
5822            // ===== AFTER AGENT CALLBACKS =====
5823            // Runs on every other exit: an answer, a transfer, a turn-ending tool result, and
5824            // a cancellation the agent observed. The first callback that returns content wins.
5825            for callback in hook_after_agent.iter().chain(after_agent_callbacks.iter()) {
5826                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
5827                    Ok(Some(content)) => {
5828                        let mut after_event = Event::new(&invocation_id);
5829                        after_event.author = agent_name.clone();
5830                        after_event.llm_response.content = Some(content);
5831                        yield Ok(after_event);
5832                        break;
5833                    }
5834                    Ok(None) => {}
5835                    Err(e) => {
5836                        yield Err(e);
5837                        return;
5838                    }
5839                }
5840            }
5841        };
5842
5843        Ok(Box::pin(s))
5844    }
5845}
5846
5847/// Runs an agent's after-agent callbacks when its stream is dropped before the agent
5848/// finishes, on the current Tokio runtime.
5849///
5850/// Nothing reads the stream any more, so content a callback returns is discarded.
5851struct AfterAgentOnDrop {
5852    hooks: Arc<Vec<AfterAgentCallback>>,
5853    callbacks: Arc<Vec<AfterAgentCallback>>,
5854    ctx: Arc<dyn CallbackContext>,
5855    armed: bool,
5856}
5857
5858impl AfterAgentOnDrop {
5859    fn armed(
5860        hooks: Arc<Vec<AfterAgentCallback>>,
5861        callbacks: Arc<Vec<AfterAgentCallback>>,
5862        ctx: Arc<dyn CallbackContext>,
5863    ) -> Self {
5864        Self { hooks, callbacks, ctx, armed: true }
5865    }
5866
5867    fn disarm(&mut self) {
5868        self.armed = false;
5869    }
5870}
5871
5872impl Drop for AfterAgentOnDrop {
5873    fn drop(&mut self) {
5874        if !self.armed {
5875            return;
5876        }
5877        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
5878            tracing::warn!(
5879                agent.name = %self.ctx.agent_name(),
5880                "no Tokio runtime to run after-agent callbacks on; they are skipped"
5881            );
5882            return;
5883        };
5884        let (hooks, callbacks, ctx) =
5885            (Arc::clone(&self.hooks), Arc::clone(&self.callbacks), Arc::clone(&self.ctx));
5886        runtime.spawn(async move {
5887            for callback in hooks.iter().chain(callbacks.iter()) {
5888                match callback(ctx.clone()).await {
5889                    Ok(Some(_)) => break,
5890                    Ok(None) => {}
5891                    Err(error) => {
5892                        tracing::warn!(
5893                            agent.name = %ctx.agent_name(),
5894                            error.code = %error.code,
5895                            "after-agent callback failed after the agent stopped"
5896                        );
5897                        break;
5898                    }
5899                }
5900            }
5901        });
5902    }
5903}
5904
5905/// Runs one tool call. An agent-delegation tool, such as an `AgentTool`, runs on a Tokio task
5906/// of its own.
5907///
5908/// A delegate's agent is polled from inside this agent's tool call, and its own delegates from
5909/// inside its tool calls, so without a task boundary every level of delegation stacks another
5910/// agent's frames on one thread's stack — several hundred KiB per level in debug builds,
5911/// enough for three levels to overflow a 2 MiB worker thread. The task is aborted when this
5912/// call is dropped, by cancellation or a timeout, and a panic in it resumes here.
5913async fn execute_tool(
5914    tool: Arc<dyn Tool>,
5915    ctx: Arc<dyn ToolContext>,
5916    args: serde_json::Value,
5917) -> Result<serde_json::Value> {
5918    let runtime = tokio::runtime::Handle::try_current().ok().filter(|_| tool.is_agent_delegation());
5919    // The run's scope is current inside the tool, so media calls it makes count against the run.
5920    let Some(runtime) = runtime else {
5921        return adk_core::ModelCallScope::within_tool(
5922            ctx.as_ref(),
5923            tool.execute(ctx.clone(), args),
5924        )
5925        .await;
5926    };
5927    let call = async move {
5928        adk_core::ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await
5929    };
5930    let mut task = AbortOnDrop(runtime.spawn(call.in_current_span()));
5931    match (&mut task.0).await {
5932        Ok(result) => result,
5933        Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
5934        Err(_) => Err(adk_core::AdkError::new(
5935            adk_core::ErrorComponent::Tool,
5936            adk_core::ErrorCategory::Cancelled,
5937            "tool.cancelled",
5938            "the delegated call's task was cancelled before it finished",
5939        )),
5940    }
5941}
5942
5943/// Aborts a spawned task when it is dropped unfinished.
5944struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
5945
5946impl<T> Drop for AbortOnDrop<T> {
5947    fn drop(&mut self) {
5948        self.0.abort();
5949    }
5950}
5951
5952/// The text `output_key` stores for `content`: its text parts, and for structured output
5953/// the JSON inside a surrounding code fence.
5954fn output_text(content: &Content, structured: bool) -> String {
5955    let text: String = content.parts.iter().filter_map(Part::text).collect();
5956    if structured { strip_json_code_fence(&text).to_string() } else { text }
5957}
5958
5959/// Whether `error` is the run's own budget or spend ledger refusing a model call, which no
5960/// fallback may answer.
5961fn is_run_limit_refusal(error: &adk_core::AdkError) -> bool {
5962    error.component == adk_core::ErrorComponent::Guardrail
5963        || (error.component == adk_core::ErrorComponent::Agent
5964            && error.category == adk_core::ErrorCategory::ResourceExhausted)
5965}
5966
5967/// Asks the run's hooks for a response to a failed model call; the first response wins.
5968///
5969/// # Errors
5970///
5971/// Returns the error of a hook that fails.
5972async fn recover_model_error(
5973    ctx: &Arc<dyn InvocationContext>,
5974    request: Option<&LlmRequest>,
5975    error: &adk_core::AdkError,
5976) -> Result<Option<LlmResponse>> {
5977    let Some(request) = request else {
5978        return Ok(None);
5979    };
5980    if is_run_limit_refusal(error) {
5981        return Ok(None);
5982    }
5983    for hook in &ctx.run_config().invocation_hooks {
5984        if let Some(response) = hook
5985            .on_model_error(ctx.clone() as Arc<dyn CallbackContext>, request.clone(), error)
5986            .await?
5987        {
5988            return Ok(Some(response));
5989        }
5990    }
5991    Ok(None)
5992}
5993
5994#[cfg(test)]
5995mod run_helper_tests {
5996    use super::*;
5997
5998    #[test]
5999    fn generation_config_layers_schema_and_cached_content() {
6000        let base =
6001            adk_core::GenerateContentConfig { temperature: Some(0.25), ..Default::default() };
6002        let schema = serde_json::json!({"type": "object"});
6003
6004        let config = build_generation_config(Some(&base), Some(&schema), Some("cached/example"))
6005            .expect("config should be present");
6006
6007        assert_eq!(config.temperature, Some(0.25));
6008        assert_eq!(config.response_schema, Some(schema));
6009        assert_eq!(config.cached_content.as_deref(), Some("cached/example"));
6010    }
6011
6012    #[test]
6013    fn function_calls_preserve_order_and_create_fallback_ids() {
6014        let content = Content {
6015            role: "model".to_string(),
6016            parts: vec![
6017                Part::Text { text: "before".to_string() },
6018                Part::FunctionCall {
6019                    name: "first".to_string(),
6020                    args: serde_json::json!({"value": 1}),
6021                    id: None,
6022                    thought_signature: None,
6023                },
6024                Part::FunctionCall {
6025                    name: "second".to_string(),
6026                    args: serde_json::json!({"value": 2}),
6027                    id: Some("provider-id".to_string()),
6028                    thought_signature: None,
6029                },
6030            ],
6031        };
6032
6033        let calls = collect_function_calls(&content, "invocation");
6034
6035        assert_eq!(calls.len(), 2);
6036        assert_eq!(calls[0].index, 0);
6037        assert_eq!(calls[0].name, "first");
6038        assert_eq!(calls[0].function_call_id, "invocation_first_0");
6039        assert_eq!(calls[1].index, 1);
6040        assert_eq!(calls[1].name, "second");
6041        assert_eq!(calls[1].function_call_id, "provider-id");
6042    }
6043
6044    #[test]
6045    fn partial_stream_events_do_not_repeat_large_payloads() {
6046        let marker = "PRIVATE-REQUEST-PAYLOAD";
6047        let request_json = format!("{marker}{}", "x".repeat(128 * 1024));
6048        let chunk = LlmResponse {
6049            content: Some(Content::new("model").with_text("x")),
6050            partial: true,
6051            ..Default::default()
6052        };
6053        let mut serialized_bytes = 0;
6054
6055        for index in 0..64 {
6056            let event = build_partial_llm_event(
6057                &format!("event-{index}"),
6058                "invocation",
6059                "agent",
6060                &request_json,
6061                &chunk,
6062                Vec::new(),
6063            );
6064            let serialized = serde_json::to_string(&event).expect("event should serialize");
6065
6066            assert!(!serialized.contains(marker));
6067            assert!(event.llm_request.is_none());
6068            assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_request"));
6069            assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_response"));
6070            serialized_bytes += serialized.len();
6071        }
6072
6073        assert!(
6074            serialized_bytes < 1024 * 1024,
6075            "64 tiny chunks unexpectedly serialized to {serialized_bytes} bytes"
6076        );
6077    }
6078}