Skip to main content

adk_realtime/
agent.rs

1//! RealtimeAgent - an Agent implementation for real-time voice interactions.
2//!
3//! This module provides `RealtimeAgent`, which implements the `adk_core::Agent` trait
4//! and provides the same callback/tool/instruction features as `LlmAgent`, but uses
5//! real-time bidirectional audio streaming instead of text-based LLM calls.
6//!
7//! # Architecture
8//!
9//! ```text
10//!                     ┌─────────────────────────────────────────┐
11//!                     │              Agent Trait                │
12//!                     │  (name, description, run, sub_agents)   │
13//!                     └────────────────┬────────────────────────┘
14//!                                      │
15//!              ┌───────────────────────┼───────────────────────┐
16//!              │                       │                       │
17//!     ┌────────▼────────┐    ┌─────────▼─────────┐   ┌─────────▼─────────┐
18//!     │    LlmAgent     │    │  RealtimeAgent    │   │  SequentialAgent  │
19//!     │  (text-based)   │    │  (voice-based)    │   │   (workflow)      │
20//!     └─────────────────┘    └───────────────────┘   └───────────────────┘
21//! ```
22//!
23//! # Shared Features with LlmAgent
24//!
25//! - **Tools**: Function tools that can be called during conversation
26//! - **Callbacks**: before_agent, after_agent, before_tool, after_tool
27//! - **Instructions**: Static or dynamic instruction providers
28//! - **Sub-agents**: Agent handoff/transfer support
29//! - **Context**: Full access to InvocationContext (session, memory, artifacts)
30//!
31//! # Example
32//!
33//! ```rust,ignore
34//! use adk_realtime::RealtimeAgent;
35//! use adk_realtime::openai::OpenAIRealtimeModel;
36//!
37//! let model = OpenAIRealtimeModel::new(api_key, "gpt-realtime-2.1");
38//!
39//! let agent = RealtimeAgent::builder("voice_assistant")
40//!     .model(Box::new(model))
41//!     .instruction("You are a helpful voice assistant.")
42//!     .voice("alloy")
43//!     .tool(Arc::new(weather_tool))
44//!     .before_agent_callback(|ctx| async move {
45//!         println!("Starting voice session for user: {}", ctx.user_id());
46//!         Ok(None)
47//!     })
48//!     .build()?;
49//!
50//! // Run through standard ADK runner
51//! let runner = Runner::new(agent);
52//! runner.run(session, user_content).await?;
53//! ```
54
55use crate::config::{RealtimeConfig, ToolDefinition, VadConfig, VadMode};
56use crate::events::{ServerEvent, ToolResponse};
57use crate::metering::{RealtimePricing, RealtimeUsage, ResponseMeter};
58use adk_core::{
59    AdkError, AfterAgentCallback, AfterToolCallback, Agent, AgentInteractionMode,
60    BeforeAgentCallback, BeforeToolCallback, CallbackContext, Content, Event, EventActions,
61    EventStream, GlobalInstructionProvider, InstructionProvider, InvocationContext, MemoryEntry,
62    Part, ReadonlyContext, Result, RunConfig, Tool, ToolCallbackContext, ToolContext,
63    ToolResultStatus, Toolset,
64};
65use async_stream::stream;
66use async_trait::async_trait;
67
68use std::sync::{Arc, Mutex};
69
70const MAX_BUFFERED_PLAYBACK_AUDIO_BYTES: usize = 16 * 1024 * 1024;
71
72/// Shared realtime model type (thread-safe for async usage).
73pub type BoxedRealtimeModel = Arc<dyn crate::model::RealtimeModel>;
74
75/// A real-time voice agent that implements the ADK Agent trait.
76///
77/// `RealtimeAgent` provides bidirectional audio streaming while maintaining
78/// compatibility with the standard ADK agent ecosystem. It supports the same
79/// callbacks, tools, and instruction patterns as `LlmAgent`.
80pub struct RealtimeAgent {
81    name: String,
82    description: String,
83    model: BoxedRealtimeModel,
84
85    // Instructions (same as LlmAgent)
86    instruction: Option<String>,
87    instruction_provider: Option<Arc<InstructionProvider>>,
88    global_instruction: Option<String>,
89    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
90
91    // Voice-specific settings
92    voice: Option<String>,
93    vad_config: Option<VadConfig>,
94    modalities: Option<Vec<String>>,
95    transcription: bool,
96
97    // Tools (same as LlmAgent)
98    tools: Vec<Arc<dyn Tool>>,
99    toolsets: Vec<Arc<dyn Toolset>>,
100    sub_agents: Vec<Arc<dyn Agent>>,
101
102    // Callbacks (same as LlmAgent)
103    before_callbacks: Arc<Vec<BeforeAgentCallback>>,
104    after_callbacks: Arc<Vec<AfterAgentCallback>>,
105    before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
106    after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
107    tool_results: ToolResultPolicy,
108
109    // Realtime-specific callbacks
110    on_audio: Option<AudioCallback>,
111    on_transcript: Option<TranscriptCallback>,
112    on_speech_started: Option<SpeechCallback>,
113    on_speech_stopped: Option<SpeechCallback>,
114
115    /// Output guardrails on the model's text and transcripts.
116    #[cfg(feature = "guardrails")]
117    output_guardrails: Option<Arc<adk_guardrail::GuardrailSet>>,
118    /// Prices each response's usage for the spend ledger.
119    pricing: Option<RealtimePricing>,
120
121    // Video avatar configuration
122    #[cfg(feature = "video-avatar")]
123    avatar_config: Option<crate::avatar::AvatarConfig>,
124
125    // Video avatar provider instance
126    #[cfg(feature = "video-avatar")]
127    avatar_provider: Option<std::sync::Arc<dyn crate::avatar::AvatarProvider>>,
128}
129
130/// Callback for audio output events (receives raw PCM bytes).
131pub type AudioCallback = Arc<
132    dyn Fn(&[u8], &str) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
133        + Send
134        + Sync,
135>;
136
137/// Callback for transcript events.
138pub type TranscriptCallback = Arc<
139    dyn Fn(&str, &str) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
140        + Send
141        + Sync,
142>;
143
144/// Callback for speech detection events.
145pub type SpeechCallback = Arc<
146    dyn Fn(u64) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> + Send + Sync,
147>;
148
149impl std::fmt::Debug for RealtimeAgent {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("RealtimeAgent")
152            .field("name", &self.name)
153            .field("description", &self.description)
154            .field("model", &self.model.model_id())
155            .field("voice", &self.voice)
156            .field("tools_count", &self.tools.len())
157            .field("toolsets_count", &self.toolsets.len())
158            .field("sub_agents_count", &self.sub_agents.len())
159            .finish()
160    }
161}
162
163/// Builder for RealtimeAgent.
164pub struct RealtimeAgentBuilder {
165    name: String,
166    description: Option<String>,
167    model: Option<BoxedRealtimeModel>,
168    instruction: Option<String>,
169    instruction_provider: Option<Arc<InstructionProvider>>,
170    global_instruction: Option<String>,
171    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
172    voice: Option<String>,
173    vad_config: Option<VadConfig>,
174    modalities: Option<Vec<String>>,
175    transcription: bool,
176    tools: Vec<Arc<dyn Tool>>,
177    toolsets: Vec<Arc<dyn Toolset>>,
178    sub_agents: Vec<Arc<dyn Agent>>,
179    before_callbacks: Vec<BeforeAgentCallback>,
180    after_callbacks: Vec<AfterAgentCallback>,
181    before_tool_callbacks: Vec<BeforeToolCallback>,
182    after_tool_callbacks: Vec<AfterToolCallback>,
183    tool_timeout: std::time::Duration,
184    tool_result_screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
185    expose_tool_error_messages: bool,
186    tool_confirmation_policy: adk_core::ToolConfirmationPolicy,
187    #[cfg(feature = "guardrails")]
188    output_guardrails: Option<adk_guardrail::GuardrailSet>,
189    pricing: Option<RealtimePricing>,
190    on_audio: Option<AudioCallback>,
191    on_transcript: Option<TranscriptCallback>,
192    on_speech_started: Option<SpeechCallback>,
193    on_speech_stopped: Option<SpeechCallback>,
194
195    #[cfg(feature = "video-avatar")]
196    avatar_config: Option<crate::avatar::AvatarConfig>,
197
198    #[cfg(feature = "video-avatar")]
199    avatar_provider: Option<std::sync::Arc<dyn crate::avatar::AvatarProvider>>,
200}
201
202impl RealtimeAgentBuilder {
203    /// Create a new builder with the given agent name.
204    pub fn new(name: impl Into<String>) -> Self {
205        Self {
206            name: name.into(),
207            description: None,
208            model: None,
209            instruction: None,
210            instruction_provider: None,
211            global_instruction: None,
212            global_instruction_provider: None,
213            voice: None,
214            vad_config: None,
215            modalities: None,
216            transcription: false,
217            tools: Vec::new(),
218            toolsets: Vec::new(),
219            sub_agents: Vec::new(),
220            before_callbacks: Vec::new(),
221            after_callbacks: Vec::new(),
222            before_tool_callbacks: Vec::new(),
223            after_tool_callbacks: Vec::new(),
224            tool_timeout: crate::runner::DEFAULT_REALTIME_TOOL_TIMEOUT,
225            tool_result_screen: None,
226            expose_tool_error_messages: false,
227            tool_confirmation_policy: adk_core::ToolConfirmationPolicy::Never,
228            #[cfg(feature = "guardrails")]
229            output_guardrails: None,
230            pricing: None,
231            on_audio: None,
232            on_transcript: None,
233            on_speech_started: None,
234            on_speech_stopped: None,
235            #[cfg(feature = "video-avatar")]
236            avatar_config: None,
237            #[cfg(feature = "video-avatar")]
238            avatar_provider: None,
239        }
240    }
241
242    /// Set the agent description.
243    pub fn description(mut self, desc: impl Into<String>) -> Self {
244        self.description = Some(desc.into());
245        self
246    }
247
248    /// Set the realtime model.
249    pub fn model(mut self, model: BoxedRealtimeModel) -> Self {
250        self.model = Some(model);
251        self
252    }
253
254    /// Set a static instruction.
255    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
256        self.instruction = Some(instruction.into());
257        self
258    }
259
260    /// Set a dynamic instruction provider.
261    pub fn instruction_provider(mut self, provider: InstructionProvider) -> Self {
262        self.instruction_provider = Some(Arc::new(provider));
263        self
264    }
265
266    /// Set a static global instruction.
267    pub fn global_instruction(mut self, instruction: impl Into<String>) -> Self {
268        self.global_instruction = Some(instruction.into());
269        self
270    }
271
272    /// Set a dynamic global instruction provider.
273    pub fn global_instruction_provider(mut self, provider: GlobalInstructionProvider) -> Self {
274        self.global_instruction_provider = Some(Arc::new(provider));
275        self
276    }
277
278    /// Set the voice for audio output.
279    pub fn voice(mut self, voice: impl Into<String>) -> Self {
280        self.voice = Some(voice.into());
281        self
282    }
283
284    /// Set voice activity detection configuration.
285    pub fn vad(mut self, config: VadConfig) -> Self {
286        self.vad_config = Some(config);
287        self
288    }
289
290    /// Enable server-side VAD with default settings.
291    pub fn server_vad(mut self) -> Self {
292        self.vad_config = Some(VadConfig {
293            mode: VadMode::ServerVad,
294            threshold: Some(0.5),
295            prefix_padding_ms: Some(300),
296            silence_duration_ms: Some(500),
297            interrupt_response: Some(true),
298            eagerness: None,
299        });
300        self
301    }
302
303    /// Set output modalities, such as `["audio"]` or `["text"]`.
304    ///
305    /// Unset, the provider's default applies: audio, with a transcript, on the OpenAI Realtime
306    /// API and on Gemini Live. A provider refuses a combination it does not support — Gemini
307    /// Live accepts one response modality per session, and `gemini-3.1-flash-live-preview`
308    /// only `audio` — and the run then ends with the provider's reason as its error.
309    pub fn modalities(mut self, modalities: Vec<String>) -> Self {
310        self.modalities = Some(modalities);
311        self
312    }
313
314    /// Transcribe the user's speech, as [`RealtimeConfig::with_transcription`] does, so each
315    /// spoken turn is saved to the session as a user event. On Gemini Live this also
316    /// transcribes the model's speech, so its spoken replies are saved as text.
317    ///
318    /// # Example
319    ///
320    /// ```rust
321    /// use adk_realtime::RealtimeAgent;
322    /// use adk_realtime::model::BoxedModel;
323    ///
324    /// fn voice_agent(model: BoxedModel) -> adk_core::Result<RealtimeAgent> {
325    ///     RealtimeAgent::builder("voice").model(model).transcription().build()
326    /// }
327    /// ```
328    pub fn transcription(mut self) -> Self {
329        self.transcription = true;
330        self
331    }
332
333    /// Add a tool.
334    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
335        self.tools.push(tool);
336        self
337    }
338
339    /// Register a dynamic toolset for per-invocation tool resolution.
340    ///
341    /// Toolsets are resolved at the start of each `run()` call using the
342    /// invocation's `ReadonlyContext`. This enables context-dependent tools
343    /// like per-user browser sessions from a pool.
344    pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
345        self.toolsets.push(toolset);
346        self
347    }
348
349    /// Add a sub-agent for handoffs.
350    pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
351        self.sub_agents.push(agent);
352        self
353    }
354
355    /// Add a before-agent callback.
356    pub fn before_agent_callback(mut self, callback: BeforeAgentCallback) -> Self {
357        self.before_callbacks.push(callback);
358        self
359    }
360
361    /// Add an after-agent callback.
362    pub fn after_agent_callback(mut self, callback: AfterAgentCallback) -> Self {
363        self.after_callbacks.push(callback);
364        self
365    }
366
367    /// Sets how long a tool may run before its call is answered with a timeout error.
368    /// Defaults to [`DEFAULT_REALTIME_TOOL_TIMEOUT`](crate::runner::DEFAULT_REALTIME_TOOL_TIMEOUT).
369    pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
370        self.tool_timeout = timeout;
371        self
372    }
373
374    /// Add a before-tool callback.
375    pub fn before_tool_callback(mut self, callback: BeforeToolCallback) -> Self {
376        self.before_tool_callbacks.push(callback);
377        self
378    }
379
380    /// Add an after-tool callback.
381    pub fn after_tool_callback(mut self, callback: AfterToolCallback) -> Self {
382        self.after_tool_callbacks.push(callback);
383        self
384    }
385
386    /// Screens every tool result before the model and the session see it.
387    ///
388    /// The screen runs on the result the agent is about to send, after the after-tool hooks
389    /// and callbacks, and before the tool event is yielded or the result is sent to the
390    /// provider. A result the screen rewrites is delivered rewritten; a result it withholds, or
391    /// that it cannot decide on (`Err`), is replaced by
392    /// [`result_blocked_response`](adk_core::result_blocked_response), so the agent fails closed.
393    /// `adk-guardrail`'s `ToolGuardrailSet` is a screen, so the same tool-result guardrails
394    /// that `LlmAgent` runs apply here.
395    ///
396    /// # Example
397    ///
398    /// ```rust,ignore
399    /// use adk_guardrail::{PiiRedactor, ResultTextGuardrail, ToolGuardrailSet};
400    ///
401    /// let agent = RealtimeAgent::builder("voice")
402    ///     .model(model)
403    ///     .tool(lookup_order)
404    ///     .tool_result_screen(Arc::new(
405    ///         ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new())),
406    ///     ))
407    ///     .build()?;
408    /// ```
409    pub fn tool_result_screen(mut self, screen: Arc<dyn adk_core::ToolResultScreen>) -> Self {
410        self.tool_result_screen = Some(screen);
411        self
412    }
413
414    /// Sends the full message of a tool or tool-callback error to the model.
415    ///
416    /// By default a call that fails with an [`AdkError`] is answered with its component,
417    /// category, and code only ([`tool_error_response`](adk_core::tool_error_response)), because
418    /// the message can quote credentials, internal hosts, or upstream bodies, and the result is
419    /// sent to the provider, can be spoken to the user, and is stored in the session. The
420    /// message is logged when [`RunConfig::record_payloads`](adk_core::RunConfig) is set.
421    /// Timeouts and the agent's own refusals keep their message.
422    ///
423    /// # Example
424    ///
425    /// ```rust,ignore
426    /// let agent = RealtimeAgent::builder("voice")
427    ///     .model(model)
428    ///     .tool(lookup_order)
429    ///     .expose_tool_error_messages(true)
430    ///     .build()?;
431    /// ```
432    pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
433        self.expose_tool_error_messages = expose;
434        self
435    }
436
437    /// Sets which tools need a person's approval before they run, as
438    /// `LlmAgentBuilder::tool_confirmation_policy` does. A call that needs one is decided by
439    /// the run's confirmation handler, approvals, or approval store, and otherwise held in the
440    /// session until a later run resumes it with a decision.
441    pub fn tool_confirmation_policy(mut self, policy: adk_core::ToolConfirmationPolicy) -> Self {
442        self.tool_confirmation_policy = policy;
443        self
444    }
445
446    /// Requires a person's approval before `tool_name` runs. See
447    /// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
448    ///
449    /// # Example
450    ///
451    /// ```rust
452    /// use adk_core::Tool;
453    /// use adk_realtime::RealtimeAgent;
454    /// use adk_realtime::model::BoxedModel;
455    /// use std::sync::Arc;
456    ///
457    /// fn agent(model: BoxedModel, refund: Arc<dyn Tool>) -> adk_core::Result<RealtimeAgent> {
458    ///     RealtimeAgent::builder("voice")
459    ///         .model(model)
460    ///         .tool(refund)
461    ///         .require_tool_confirmation("refund")
462    ///         .build()
463    /// }
464    /// ```
465    pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
466        self.tool_confirmation_policy = self.tool_confirmation_policy.with_tool(tool_name);
467        self
468    }
469
470    /// Requires a person's approval before every tool call. See
471    /// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
472    pub fn require_tool_confirmation_for_all(mut self) -> Self {
473        self.tool_confirmation_policy = adk_core::ToolConfirmationPolicy::Always;
474        self
475    }
476
477    /// Screens the model's completed text and transcripts with `guardrails` before the
478    /// final event reaches the client or the session, as `LlmAgent` screens final text. A
479    /// transform rewrites the text; a block interrupts the response, ends the run with the
480    /// guardrail's error, and closes the session.
481    ///
482    /// # Example
483    ///
484    /// ```rust,ignore
485    /// use adk_guardrail::{GuardrailSet, PiiRedactor};
486    ///
487    /// let agent = RealtimeAgent::builder("voice")
488    ///     .model(model)
489    ///     .output_guardrails(GuardrailSet::new().with(PiiRedactor::new()))
490    ///     .build()?;
491    /// ```
492    #[cfg(feature = "guardrails")]
493    pub fn output_guardrails(mut self, guardrails: adk_guardrail::GuardrailSet) -> Self {
494        self.output_guardrails = Some(guardrails);
495        self
496    }
497
498    /// Prices each response's reported usage, so the run's spend ledger is charged the
499    /// usage's price rather than the run's per-call estimate, and the usage event the agent
500    /// yields at each response's end carries a cost.
501    pub fn realtime_pricing(mut self, pricing: RealtimePricing) -> Self {
502        self.pricing = Some(pricing);
503        self
504    }
505
506    /// Set callback for audio output events.
507    pub fn on_audio(mut self, callback: AudioCallback) -> Self {
508        self.on_audio = Some(callback);
509        self
510    }
511
512    /// Set callback for transcript events.
513    pub fn on_transcript(mut self, callback: TranscriptCallback) -> Self {
514        self.on_transcript = Some(callback);
515        self
516    }
517
518    /// Set callback for speech started events.
519    pub fn on_speech_started(mut self, callback: SpeechCallback) -> Self {
520        self.on_speech_started = Some(callback);
521        self
522    }
523
524    /// Set callback for speech stopped events.
525    pub fn on_speech_stopped(mut self, callback: SpeechCallback) -> Self {
526        self.on_speech_stopped = Some(callback);
527        self
528    }
529
530    /// Set the video avatar configuration for this agent.
531    ///
532    /// When set, the avatar configuration is included in the session setup
533    /// payload sent to the realtime provider. If the provider does not support
534    /// video avatars, a warning is logged and the session proceeds audio-only.
535    ///
536    /// Requires the `video-avatar` feature flag.
537    #[cfg(feature = "video-avatar")]
538    pub fn avatar(mut self, config: crate::avatar::AvatarConfig) -> Self {
539        self.avatar_config = Some(config);
540        self
541    }
542
543    /// Set the video avatar provider for this agent.
544    ///
545    /// When both an `AvatarConfig` (with a provider kind) and an `AvatarProvider`
546    /// instance are set, the runner routes audio through the avatar provider
547    /// for lip-sync rendering instead of sending raw audio to the client.
548    ///
549    /// Requires the `video-avatar` feature flag.
550    ///
551    /// # Example
552    ///
553    /// ```rust,ignore
554    /// use std::sync::Arc;
555    /// use adk_realtime::avatar::heygen::{HeyGenConfig, HeyGenProvider};
556    ///
557    /// let provider = Arc::new(HeyGenProvider::new(HeyGenConfig::new("key")));
558    /// let agent = RealtimeAgentBuilder::new("assistant")
559    ///     .avatar(avatar_config)
560    ///     .avatar_provider(provider)
561    ///     .build()?;
562    /// ```
563    #[cfg(feature = "video-avatar")]
564    pub fn avatar_provider(
565        mut self,
566        provider: std::sync::Arc<dyn crate::avatar::AvatarProvider>,
567    ) -> Self {
568        self.avatar_provider = Some(provider);
569        self
570    }
571
572    /// Build the RealtimeAgent.
573    ///
574    /// # Errors
575    ///
576    /// Returns an error when no model was set, or when two tools added with
577    /// [`tool`](Self::tool) share a name (code `agent.duplicate_tool_name`).
578    pub fn build(self) -> Result<RealtimeAgent> {
579        let model =
580            self.model.ok_or_else(|| AdkError::agent("RealtimeModel is required".to_string()))?;
581        adk_core::ensure_unique_tool_names(&self.name, &self.tools)?;
582
583        Ok(RealtimeAgent {
584            name: self.name,
585            description: self.description.unwrap_or_default(),
586            model,
587            instruction: self.instruction,
588            instruction_provider: self.instruction_provider,
589            global_instruction: self.global_instruction,
590            global_instruction_provider: self.global_instruction_provider,
591            voice: self.voice,
592            vad_config: self.vad_config,
593            modalities: self.modalities,
594            transcription: self.transcription,
595            tools: self.tools,
596            toolsets: self.toolsets,
597            sub_agents: self.sub_agents,
598            before_callbacks: Arc::new(self.before_callbacks),
599            after_callbacks: Arc::new(self.after_callbacks),
600            before_tool_callbacks: Arc::new(self.before_tool_callbacks),
601            after_tool_callbacks: Arc::new(self.after_tool_callbacks),
602            tool_results: ToolResultPolicy {
603                timeout: self.tool_timeout,
604                screen: self.tool_result_screen,
605                expose_error_messages: self.expose_tool_error_messages,
606                confirmation: self.tool_confirmation_policy,
607            },
608            #[cfg(feature = "guardrails")]
609            output_guardrails: self.output_guardrails.map(Arc::new),
610            pricing: self.pricing,
611            on_audio: self.on_audio,
612            on_transcript: self.on_transcript,
613            on_speech_started: self.on_speech_started,
614            on_speech_stopped: self.on_speech_stopped,
615            #[cfg(feature = "video-avatar")]
616            avatar_config: self.avatar_config,
617            #[cfg(feature = "video-avatar")]
618            avatar_provider: self.avatar_provider,
619        })
620    }
621}
622
623impl RealtimeAgent {
624    /// Create a new builder.
625    pub fn builder(name: impl Into<String>) -> RealtimeAgentBuilder {
626        RealtimeAgentBuilder::new(name)
627    }
628
629    /// Get the static instruction, if set.
630    pub fn instruction(&self) -> Option<&String> {
631        self.instruction.as_ref()
632    }
633
634    /// Get the voice setting, if set.
635    pub fn voice(&self) -> Option<&String> {
636        self.voice.as_ref()
637    }
638
639    /// Get the VAD configuration, if set.
640    pub fn vad_config(&self) -> Option<&VadConfig> {
641        self.vad_config.as_ref()
642    }
643
644    /// Get the list of tools.
645    pub fn tools(&self) -> &[Arc<dyn Tool>] {
646        &self.tools
647    }
648
649    /// Get the avatar configuration, if set.
650    ///
651    /// Requires the `video-avatar` feature flag.
652    #[cfg(feature = "video-avatar")]
653    pub fn avatar_config(&self) -> Option<&crate::avatar::AvatarConfig> {
654        self.avatar_config.as_ref()
655    }
656
657    /// Get the avatar provider, if set.
658    ///
659    /// Requires the `video-avatar` feature flag.
660    #[cfg(feature = "video-avatar")]
661    pub fn avatar_provider(&self) -> Option<&std::sync::Arc<dyn crate::avatar::AvatarProvider>> {
662        self.avatar_provider.as_ref()
663    }
664
665    /// Build the realtime configuration from agent settings.
666    async fn build_config(
667        &self,
668        ctx: &Arc<dyn InvocationContext>,
669        resolved_tools: &[Arc<dyn Tool>],
670    ) -> Result<RealtimeConfig> {
671        let mut config = RealtimeConfig::default();
672
673        // Build instruction from providers or static value
674        if let Some(provider) = &self.global_instruction_provider {
675            let global_inst = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
676            if !global_inst.is_empty() {
677                config.instruction = Some(global_inst);
678            }
679        } else if let Some(ref template) = self.global_instruction {
680            let processed = adk_core::inject_session_state(ctx.as_ref(), template).await?;
681            config.instruction = Some(processed);
682        }
683
684        // Add agent-specific instruction
685        if let Some(provider) = &self.instruction_provider {
686            let inst = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
687            if !inst.is_empty() {
688                if let Some(existing) = &mut config.instruction {
689                    existing.push_str("\n\n");
690                    existing.push_str(&inst);
691                } else {
692                    config.instruction = Some(inst);
693                }
694            }
695        } else if let Some(ref template) = self.instruction {
696            let processed = adk_core::inject_session_state(ctx.as_ref(), template).await?;
697            if let Some(existing) = &mut config.instruction {
698                existing.push_str("\n\n");
699                existing.push_str(&processed);
700            } else {
701                config.instruction = Some(processed);
702            }
703        }
704
705        // Voice settings
706        config.voice = self.voice.clone();
707        config.turn_detection = self.vad_config.clone();
708        config.modalities = self.modalities.clone();
709        if self.transcription {
710            config = config.with_transcription();
711        }
712
713        // Convert ADK tools to realtime tool definitions
714        let tool_defs: Vec<ToolDefinition> = resolved_tools
715            .iter()
716            .map(|t| ToolDefinition {
717                name: t.name().to_string(),
718                description: Some(t.enhanced_description().to_string()),
719                parameters: t.parameters_schema(),
720                behavior: None,
721            })
722            .collect();
723
724        if !tool_defs.is_empty() {
725            config.tools = Some(tool_defs);
726        }
727
728        // Add transfer_to_agent tool if sub-agents exist
729        if !self.sub_agents.is_empty() {
730            let mut tools = config.tools.unwrap_or_default();
731            tools.push(ToolDefinition {
732                name: "transfer_to_agent".to_string(),
733                description: Some("Transfer execution to another agent.".to_string()),
734                parameters: Some(serde_json::json!({
735                    "type": "object",
736                    "properties": {
737                        "agent_name": {
738                            "type": "string",
739                            "description": "The name of the agent to transfer to."
740                        }
741                    },
742                    "required": ["agent_name"]
743                })),
744                behavior: None,
745            });
746            config.tools = Some(tools);
747        }
748
749        // Include avatar configuration in session setup if present.
750        // Currently no realtime provider supports video avatars natively,
751        // so we log a warning and proceed audio-only. The config is still
752        // placed in `extra` so future provider implementations can read it.
753        #[cfg(feature = "video-avatar")]
754        if let Some(ref avatar) = self.avatar_config {
755            tracing::warn!(
756                agent = %self.name,
757                source_url = %avatar.source_url,
758                "video avatar configured but the current realtime provider does not support video avatars; proceeding audio-only"
759            );
760            let avatar_json = serde_json::to_value(avatar).unwrap_or_else(|e| {
761                tracing::warn!("failed to serialize avatar config: {e}");
762                serde_json::Value::Null
763            });
764            let extra = config.extra.get_or_insert_with(|| serde_json::json!({}));
765            if let Some(obj) = extra.as_object_mut() {
766                obj.insert("avatarConfig".to_string(), avatar_json);
767            }
768        }
769
770        Ok(config)
771    }
772}
773
774#[async_trait]
775impl Agent for RealtimeAgent {
776    fn name(&self) -> &str {
777        &self.name
778    }
779
780    fn description(&self) -> &str {
781        &self.description
782    }
783
784    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
785        &self.sub_agents
786    }
787
788    fn interaction_mode(&self) -> AgentInteractionMode {
789        AgentInteractionMode::Realtime
790    }
791
792    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
793        let agent_name = self.name.clone();
794        let invocation_id = ctx.invocation_id().to_string();
795        let model = self.model.clone();
796        let _sub_agents = self.sub_agents.clone();
797
798        // Clone callback refs
799        let before_callbacks = self.before_callbacks.clone();
800        let after_callbacks = self.after_callbacks.clone();
801        let before_tool_callbacks = self.before_tool_callbacks.clone();
802        let after_tool_callbacks = self.after_tool_callbacks.clone();
803        let tool_results = self.tool_results.clone();
804        #[cfg(feature = "guardrails")]
805        let output_guardrails = self.output_guardrails.clone();
806        let pricing = self.pricing;
807        let tools = self.tools.clone();
808        let toolsets = self.toolsets.clone();
809
810        // Clone realtime callbacks
811        let on_audio = self.on_audio.clone();
812        let on_transcript = self.on_transcript.clone();
813        let on_speech_started = self.on_speech_started.clone();
814        let on_speech_stopped = self.on_speech_stopped.clone();
815
816        // Clone avatar provider for the stream closure
817        #[cfg(feature = "video-avatar")]
818        let avatar_provider = self.avatar_provider.clone();
819        #[cfg(feature = "video-avatar")]
820        let avatar_config_for_session = self.avatar_config.clone();
821
822        // ===== RESOLVE TOOLSETS =====
823        let mut resolved_tools: Vec<Arc<dyn Tool>> = tools.clone();
824        let static_tool_names: std::collections::HashSet<String> =
825            tools.iter().map(|t| t.name().to_string()).collect();
826        let mut toolset_source: std::collections::HashMap<String, String> =
827            std::collections::HashMap::new();
828
829        for toolset in &toolsets {
830            let toolset_tools = toolset.tools(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
831            for tool in &toolset_tools {
832                let name = tool.name().to_string();
833                if static_tool_names.contains(&name) {
834                    return Err(AdkError::agent(format!(
835                        "Duplicate tool name '{}': conflict between static tool and toolset '{}'",
836                        name,
837                        toolset.name()
838                    )));
839                }
840                if let Some(other_toolset_name) = toolset_source.get(&name) {
841                    return Err(AdkError::agent(format!(
842                        "Duplicate tool name '{}': conflict between toolset '{}' and toolset '{}'",
843                        name,
844                        other_toolset_name,
845                        toolset.name()
846                    )));
847                }
848                toolset_source.insert(name, toolset.name().to_string());
849                resolved_tools.push(tool.clone());
850            }
851        }
852
853        // Build config with resolved tools
854        let config = self.build_config(&ctx, &resolved_tools).await?;
855
856        // Every response is metered in the run's spend ledger, as a model call is.
857        let meter = ResponseMeter::for_run(
858            ctx.run_config(),
859            ctx.app_name(),
860            &agent_name,
861            model.model_id(),
862            pricing,
863        );
864
865        let s = stream! {
866            // ===== BEFORE AGENT CALLBACKS =====
867            // Runner plugins reach this agent through the run config, ahead of its own callbacks.
868            for hook in &ctx.run_config().invocation_hooks {
869                match hook.before_agent(ctx.clone() as Arc<dyn CallbackContext>).await {
870                    Ok(Some(content)) => {
871                        let mut early_event = Event::new(&invocation_id);
872                        early_event.author = agent_name.clone();
873                        early_event.llm_response.content = Some(content);
874                        yield Ok(early_event);
875                        return;
876                    }
877                    Ok(None) => continue,
878                    Err(e) => {
879                        yield Err(e);
880                        return;
881                    }
882                }
883            }
884            for callback in before_callbacks.as_ref() {
885                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
886                    Ok(Some(content)) => {
887                        let mut early_event = Event::new(&invocation_id);
888                        early_event.author = agent_name.clone();
889                        early_event.llm_response.content = Some(content);
890                        yield Ok(early_event);
891                        return;
892                    }
893                    Ok(None) => continue,
894                    Err(e) => {
895                        yield Err(e);
896                        return;
897                    }
898                }
899            }
900
901            // ===== CONNECT TO REALTIME SESSION =====
902            let session = match model.connect(config).await {
903                Ok(s) => s,
904                Err(e) => {
905                    yield Err(AdkError::model(format!("Failed to connect: {}", e)));
906                    return;
907                }
908            };
909
910            // Yield session started event
911            let mut start_event = Event::new(&invocation_id);
912            start_event.author = agent_name.clone();
913            start_event.llm_response.content = Some(Content {
914                role: "system".to_string(),
915                parts: vec![Part::Text {
916                    text: format!("Realtime session started: {}", session.session_id()),
917                }],
918            });
919            yield Ok(start_event);
920
921            // ===== START AVATAR SESSION (if configured) =====
922            #[cfg(feature = "video-avatar")]
923            let avatar_session_id: Option<String> = {
924                if let (Some(provider), Some(config)) = (&avatar_provider, &avatar_config_for_session) {
925                    match provider.start_session(config).await {
926                        Ok(session_info) => {
927                            tracing::info!(
928                                provider = %session_info.provider,
929                                session_id = %session_info.session_id,
930                                "avatar session started"
931                            );
932                            // Emit avatar session info as an event for the client
933                            let mut avatar_event = Event::new(&invocation_id);
934                            avatar_event.author = agent_name.clone();
935                            avatar_event.llm_response.content = Some(Content {
936                                role: "system".to_string(),
937                                parts: vec![Part::Text {
938                                    text: serde_json::to_string(&session_info).unwrap_or_default(),
939                                }],
940                            });
941                            yield Ok(avatar_event);
942                            Some(session_info.session_id)
943                        }
944                        Err(e) => {
945                            // Graceful degradation: log warning, continue audio-only
946                            tracing::warn!(
947                                error = %e,
948                                "avatar session creation failed, falling back to audio-only"
949                            );
950                            None
951                        }
952                    }
953                } else {
954                    None
955                }
956            };
957            #[cfg(not(feature = "video-avatar"))]
958            let _avatar_session_id: Option<String> = None;
959
960            // Spawn keep-alive task for avatar session
961            #[cfg(feature = "video-avatar")]
962            let _avatar_keep_alive_handle: Option<tokio::task::JoinHandle<()>> = {
963                if let (Some(provider), Some(sess_id)) = (&avatar_provider, &avatar_session_id) {
964                    Some(crate::avatar::spawn_keep_alive(
965                        provider.clone(),
966                        sess_id.clone(),
967                        std::time::Duration::from_secs(30),
968                    ))
969                } else {
970                    None
971                }
972            };
973
974            // ===== RESUME HELD CALLS =====
975            // A call held in an earlier run resumes once it has a decision, as `LlmAgent`
976            // resumes its held calls at the start of a run. The provider session is new,
977            // so the result is carried to the model as text rather than as the output of a
978            // call this session never issued.
979            {
980                let held_calls = ctx.session().held_tool_calls(&agent_name, ctx.branch());
981                if !held_calls.is_empty() {
982                    let gate = adk_core::ToolGate::for_context(ctx.as_ref());
983                    for held in held_calls {
984                        let Some(function_call_id) = held.request.function_call_id.clone() else {
985                            continue;
986                        };
987                        match adk_core::confirmation_decision_available(&gate, &held.request).await {
988                            Ok(true) => {}
989                            Ok(false) => continue,
990                            Err(error) => {
991                                yield Err(error);
992                                let _ = session.close().await;
993                                return;
994                            }
995                        }
996                        let Some(tool) = resolved_tools.iter().find(|t| t.name() == held.name).cloned() else {
997                            continue;
998                        };
999                        // A resumed call counts against the run's budget as a new one does.
1000                        if let Some(tracker) = ctx.run_config().budget_tracker.as_ref()
1001                            && let Err(exceeded) = tracker.begin_tool_calls(1)
1002                        {
1003                            yield Err(exceeded.into());
1004                            let _ = session.close().await;
1005                            return;
1006                        }
1007                        let outcome = match dispatch_tool(
1008                            &ctx,
1009                            &tool,
1010                            &function_call_id,
1011                            &held.args.to_string(),
1012                            &DispatchHooks {
1013                                before_tool_callbacks: before_tool_callbacks.as_ref(),
1014                                after_tool_callbacks: after_tool_callbacks.as_ref(),
1015                                policy: &tool_results,
1016                            },
1017                            Some(held.request.clone()),
1018                        )
1019                        .await
1020                        {
1021                            Ok(outcome) => outcome,
1022                            Err(error) => {
1023                                yield Err(error);
1024                                let _ = session.close().await;
1025                                return;
1026                            }
1027                        };
1028                        if outcome.held.is_some() {
1029                            // The decision was not live after all: the call stays held.
1030                            continue;
1031                        }
1032                        let mut tool_event = Event::new(&invocation_id);
1033                        tool_event.author = agent_name.clone();
1034                        tool_event.actions = outcome.actions.clone();
1035                        tool_event.llm_response.content = Some(Content {
1036                            role: "function".to_string(),
1037                            parts: vec![outcome.part(&held.name, &function_call_id)],
1038                        });
1039                        yield Ok(tool_event);
1040                        let rendered = outcome.result.to_string();
1041                        let rendered = if rendered.chars().count() > 2_000 {
1042                            format!("{}…", rendered.chars().take(2_000).collect::<String>())
1043                        } else {
1044                            rendered
1045                        };
1046                        if let Err(e) = session
1047                            .send_text(&format!(
1048                                "The call to {} you made earlier was decided and has now run. Its result: {rendered}",
1049                                held.name
1050                            ))
1051                            .await
1052                        {
1053                            yield Err(AdkError::model(format!("Failed to send resumed result: {e}")));
1054                            let _ = session.close().await;
1055                            return;
1056                        }
1057                    }
1058                }
1059            }
1060
1061            // ===== SEND INITIAL USER CONTENT =====
1062            // If user provided text input, send it to start the conversation
1063            let user_content = ctx.user_content();
1064            for part in &user_content.parts {
1065                if let Part::Text { text } = part {
1066                    if let Err(e) = session.send_text(text).await {
1067                        yield Err(AdkError::model(format!("Failed to send text: {}", e)));
1068                        return;
1069                    }
1070                    // Request a response
1071                    if let Err(e) = session.create_response().await {
1072                        yield Err(AdkError::model(format!("Failed to create response: {}", e)));
1073                        return;
1074                    }
1075                }
1076            }
1077
1078            // ===== PROCESS REALTIME EVENTS =====
1079            let mut audio_buffers = std::collections::HashMap::<String, Vec<u8>>::new();
1080            let mut pending_text = std::collections::HashMap::<String, String>::new();
1081            let mut pending_transcript = std::collections::HashMap::<String, String>::new();
1082            let mut oversized_audio = std::collections::HashSet::<String>::new();
1083            // The user's input transcripts streamed so far, by item, not yet saved.
1084            let mut user_transcripts = Vec::<(String, String)>::new();
1085            // The item a reply streamed without one (Gemini Live) is saved under, so each
1086            // reply's final event has its own id.
1087            let mut reply_item: Option<String> = None;
1088            // Why the provider closed the session, when its close code reports a failure.
1089            let mut failed_close: Option<crate::session::DisconnectReason> = None;
1090            loop {
1091                let event = session.next_event().await;
1092
1093                match event {
1094                    Some(Ok(server_event)) => {
1095                        // A transcript streamed without an item id (Gemini Live) is never
1096                        // completed by the provider: it ends where the model's turn starts or
1097                        // ends, so it is saved ahead of the model's reply to it.
1098                        if matches!(
1099                            server_event,
1100                            ServerEvent::ResponseCreated { .. }
1101                                | ServerEvent::AudioDelta { .. }
1102                                | ServerEvent::TextDelta { .. }
1103                                | ServerEvent::TranscriptDelta { .. }
1104                                | ServerEvent::FunctionCallDone { .. }
1105                                | ServerEvent::ResponseDone { .. }
1106                        ) && let Some(index) =
1107                            user_transcripts.iter().position(|(item_id, _)| item_id.is_empty())
1108                        {
1109                            let (_, text) = user_transcripts.remove(index);
1110                            if !text.trim().is_empty() {
1111                                yield Ok(user_turn(&invocation_id, text));
1112                            }
1113                        }
1114                        match server_event {
1115                            ServerEvent::InputTranscriptDelta { item_id, delta, .. } => {
1116                                match user_transcripts.iter_mut().find(|(id, _)| *id == item_id) {
1117                                    Some((_, text)) => text.push_str(&delta),
1118                                    None => user_transcripts.push((item_id, delta)),
1119                                }
1120                            }
1121
1122                            ServerEvent::InputTranscriptCompleted { item_id, transcript, .. } => {
1123                                let streamed = user_transcripts
1124                                    .iter()
1125                                    .position(|(id, _)| *id == item_id)
1126                                    .map(|index| user_transcripts.remove(index).1);
1127                                let text = if transcript.trim().is_empty() {
1128                                    streamed.unwrap_or_default()
1129                                } else {
1130                                    transcript
1131                                };
1132                                if !text.trim().is_empty() {
1133                                    yield Ok(user_turn(&invocation_id, text));
1134                                }
1135                            }
1136
1137                            ServerEvent::AudioDelta { delta, item_id, .. } => {
1138                                // Route audio through avatar provider if active
1139                                #[cfg(feature = "video-avatar")]
1140                                if let (Some(provider), Some(sess_id)) = (&avatar_provider, &avatar_session_id) {
1141                                    if let Err(e) = provider.send_audio(sess_id, &delta).await {
1142                                        tracing::warn!(error = %e, "avatar send_audio failed");
1143                                    }
1144                                    // Don't yield raw audio to client — avatar provides video+audio
1145                                    // Still call the on_audio callback for monitoring
1146                                    if let Some(ref cb) = on_audio {
1147                                        cb(&delta, &item_id).await;
1148                                    }
1149                                    continue;
1150                                }
1151
1152                                // No avatar provider — send raw audio to client
1153                                if let Some(ref cb) = on_audio {
1154                                    cb(&delta, &item_id).await;
1155                                }
1156
1157                                if !oversized_audio.contains(&item_id) {
1158                                    let buffer = audio_buffers.entry(item_id.clone()).or_default();
1159                                    if buffer.len().saturating_add(delta.len())
1160                                        <= MAX_BUFFERED_PLAYBACK_AUDIO_BYTES
1161                                    {
1162                                        buffer.extend_from_slice(&delta);
1163                                    } else {
1164                                        audio_buffers.remove(&item_id);
1165                                        oversized_audio.insert(item_id.clone());
1166                                        tracing::warn!(
1167                                            item.id = item_id,
1168                                            limit.bytes = MAX_BUFFERED_PLAYBACK_AUDIO_BYTES,
1169                                            "realtime playback buffer exceeded its limit; raw audio events continue"
1170                                        );
1171                                    }
1172                                }
1173
1174                                // Yield audio event (delta is already raw bytes)
1175                                let mut audio_event = Event::new(&invocation_id);
1176                                audio_event.author = agent_name.clone();
1177                                audio_event.provider_metadata.insert(
1178                                    "adk.realtime.audio_stream".to_string(),
1179                                    "pcm16-24000-mono".to_string(),
1180                                );
1181                                audio_event.llm_response.content = Some(Content {
1182                                    role: "model".to_string(),
1183                                    parts: vec![Part::InlineData {
1184                                        mime_type: "audio/pcm".to_string(),
1185                                        data: delta,
1186                                        uri: None,
1187                                        annotations: None,
1188                                    }],
1189                                });
1190                                yield Ok(audio_event);
1191                            }
1192
1193                            ServerEvent::AudioDone { item_id, .. } => {
1194                                let oversized = oversized_audio.remove(&item_id);
1195                                if !oversized
1196                                    && let Some(pcm) = audio_buffers.remove(&item_id)
1197                                    && !pcm.is_empty()
1198                                {
1199                                    let mut audio_event = Event::new(&invocation_id);
1200                                    audio_event.author = agent_name.clone();
1201                                    audio_event.provider_metadata.insert(
1202                                        "adk.realtime.audio_playback".to_string(),
1203                                        "wav-24000-mono".to_string(),
1204                                    );
1205                                    audio_event.llm_response.content = Some(Content {
1206                                        role: "model".to_string(),
1207                                        parts: vec![Part::InlineData {
1208                                            mime_type: "audio/wav".to_string(),
1209                                            data: pcm16_mono_wav(&pcm, 24_000),
1210                                            uri: None,
1211                                            annotations: None,
1212                                        }],
1213                                    });
1214                                    yield Ok(audio_event);
1215                                }
1216                            }
1217
1218                            ServerEvent::TextDelta { delta, item_id, .. } => {
1219                                let item_id = reply_item_id(item_id, &mut reply_item);
1220                                pending_text.entry(item_id.clone()).or_default().push_str(&delta);
1221                                let mut text_event = Event::with_id(
1222                                    format!("{invocation_id}:realtime-text:{item_id}"),
1223                                    &invocation_id,
1224                                );
1225                                text_event.author = agent_name.clone();
1226                                text_event.llm_response.partial = true;
1227                                text_event.llm_response.content = Some(Content {
1228                                    role: "model".to_string(),
1229                                    parts: vec![Part::Text { text: delta.clone() }],
1230                                });
1231                                yield Ok(text_event);
1232                            }
1233
1234                            ServerEvent::ResponseCreated { .. } => {
1235                                if let Some(meter) = &meter
1236                                    && let Err(e) = meter.begin_response().await
1237                                {
1238                                    yield Err(AdkError::model(e.to_string()));
1239                                    let _ = session.close().await;
1240                                    return;
1241                                }
1242                            }
1243
1244                            ServerEvent::TextDone { text, item_id, .. } => {
1245                                let item_id = reply_item_id(item_id, &mut reply_item);
1246                                pending_text.remove(&item_id);
1247                                let text = match screen_output(
1248                                    #[cfg(feature = "guardrails")]
1249                                    output_guardrails.as_deref(),
1250                                    text,
1251                                )
1252                                .await
1253                                {
1254                                    Ok(text) => text,
1255                                    Err(error) => {
1256                                        let _ = session.interrupt().await;
1257                                        yield Err(error);
1258                                        let _ = session.close().await;
1259                                        return;
1260                                    }
1261                                };
1262                                let mut text_event = Event::with_id(
1263                                    format!("{invocation_id}:realtime-text:{item_id}"),
1264                                    &invocation_id,
1265                                );
1266                                text_event.author = agent_name.clone();
1267                                text_event.llm_response.content = Some(Content {
1268                                    role: "model".to_string(),
1269                                    parts: vec![Part::Text { text }],
1270                                });
1271                                yield Ok(text_event);
1272                            }
1273
1274                            ServerEvent::TranscriptDelta { delta, item_id, .. } => {
1275                                if let Some(ref cb) = on_transcript {
1276                                    cb(&delta, &item_id).await;
1277                                }
1278                                let item_id = reply_item_id(item_id, &mut reply_item);
1279                                pending_transcript.entry(item_id.clone()).or_default().push_str(&delta);
1280                                let mut transcript_event = Event::with_id(
1281                                    format!("{invocation_id}:realtime-transcript:{item_id}"),
1282                                    &invocation_id,
1283                                );
1284                                transcript_event.author = agent_name.clone();
1285                                transcript_event.llm_response.partial = true;
1286                                transcript_event.provider_metadata.insert(
1287                                    "adk.realtime.transcript".to_string(),
1288                                    "output".to_string(),
1289                                );
1290                                transcript_event.llm_response.content = Some(Content {
1291                                    role: "model".to_string(),
1292                                    parts: vec![Part::Text { text: delta }],
1293                                });
1294                                yield Ok(transcript_event);
1295                            }
1296
1297                            ServerEvent::TranscriptDone { transcript, item_id, .. } => {
1298                                let item_id = reply_item_id(item_id, &mut reply_item);
1299                                pending_transcript.remove(&item_id);
1300                                let transcript = match screen_output(
1301                                    #[cfg(feature = "guardrails")]
1302                                    output_guardrails.as_deref(),
1303                                    transcript,
1304                                )
1305                                .await
1306                                {
1307                                    Ok(transcript) => transcript,
1308                                    Err(error) => {
1309                                        let _ = session.interrupt().await;
1310                                        yield Err(error);
1311                                        let _ = session.close().await;
1312                                        return;
1313                                    }
1314                                };
1315                                let mut transcript_event = Event::with_id(
1316                                    format!("{invocation_id}:realtime-transcript:{item_id}"),
1317                                    &invocation_id,
1318                                );
1319                                transcript_event.author = agent_name.clone();
1320                                transcript_event.provider_metadata.insert(
1321                                    "adk.realtime.transcript".to_string(),
1322                                    "output".to_string(),
1323                                );
1324                                transcript_event.llm_response.content = Some(Content {
1325                                    role: "model".to_string(),
1326                                    parts: vec![Part::Text { text: transcript }],
1327                                });
1328                                yield Ok(transcript_event);
1329                            }
1330
1331                            ServerEvent::SpeechStarted { audio_start_ms, .. } => {
1332                                if let Some(ref cb) = on_speech_started {
1333                                    cb(audio_start_ms).await;
1334                                }
1335                            }
1336
1337                            ServerEvent::SpeechStopped { audio_end_ms, .. } => {
1338                                if let Some(ref cb) = on_speech_stopped {
1339                                    cb(audio_end_ms).await;
1340                                }
1341                            }
1342
1343                            ServerEvent::FunctionCallDone {
1344                                call_id,
1345                                name,
1346                                arguments,
1347                                ..
1348                            } => {
1349                                // Handle transfer_to_agent
1350                                if name == "transfer_to_agent" {
1351                                    let target = crate::runner::parse_tool_arguments(&arguments)
1352                                        .ok()
1353                                        .and_then(|args| {
1354                                            args.get("agent_name")
1355                                                .and_then(|v| v.as_str())
1356                                                .map(str::to_string)
1357                                        })
1358                                        .filter(|target| !target.is_empty());
1359                                    if let Some(target) = target {
1360                                        let mut transfer_event = Event::new(&invocation_id);
1361                                        transfer_event.author = agent_name.clone();
1362                                        transfer_event.actions.transfer_to_agent = Some(target);
1363                                        yield Ok(transfer_event);
1364
1365                                        let _ = session.close().await;
1366                                        return;
1367                                    }
1368                                    // A transfer with no readable target is answered, not followed.
1369                                    let response = ToolResponse {
1370                                        call_id,
1371                                        output: serde_json::json!({
1372                                            "error": "transfer_to_agent needs an `agent_name` argument"
1373                                        }),
1374                                    };
1375                                    if let Err(e) = session.send_tool_response(response).await {
1376                                        yield Err(AdkError::model(format!("Failed to send tool response: {}", e)));
1377                                        let _ = session.close().await;
1378                                        return;
1379                                    }
1380                                    continue;
1381                                }
1382
1383                                // ===== RUN BUDGET: TOOL CALLS =====
1384                                // A call the run's budget cannot fit is answered as not run, and
1385                                // the run ends with the budget error, as `LlmAgent` ends it.
1386                                if let Some(tracker) = ctx.run_config().budget_tracker.as_ref()
1387                                    && let Err(exceeded) = tracker.begin_tool_calls(1)
1388                                {
1389                                    let outcome = ToolDispatch::answer(
1390                                        serde_json::json!({ "error": format!("not run: {exceeded}") }),
1391                                        ToolResultStatus::NotRun,
1392                                        Some(AdkError::from(exceeded.clone())),
1393                                    );
1394                                    let mut budget_event = Event::new(&invocation_id);
1395                                    budget_event.author = agent_name.clone();
1396                                    budget_event.llm_response.content = Some(Content {
1397                                        role: "function".to_string(),
1398                                        parts: vec![outcome.part(&name, &call_id)],
1399                                    });
1400                                    yield Ok(budget_event);
1401                                    yield Err(exceeded.into());
1402                                    let _ = session.close().await;
1403                                    return;
1404                                }
1405
1406                                // Execute tool through the governed path.
1407                                let tool = resolved_tools.iter().find(|t| t.name() == name);
1408
1409                                let outcome = if let Some(tool) = tool {
1410                                    match dispatch_tool(
1411                                        &ctx,
1412                                        tool,
1413                                        &call_id,
1414                                        &arguments,
1415                                        &DispatchHooks {
1416                                            before_tool_callbacks: before_tool_callbacks.as_ref(),
1417                                            after_tool_callbacks: after_tool_callbacks.as_ref(),
1418                                            policy: &tool_results,
1419                                        },
1420                                        None,
1421                                    )
1422                                    .await
1423                                    {
1424                                        Ok(mut outcome) => {
1425                                            if let Some(request) = outcome.held.take() {
1426                                                // Surfaced for an approver; the session continues
1427                                                // and the model is told the call was not run.
1428                                                let mut held_event = Event::new(&invocation_id);
1429                                                held_event.author = agent_name.clone();
1430                                                held_event.actions.tool_confirmation = Some(request);
1431                                                yield Ok(held_event);
1432                                            }
1433                                            outcome
1434                                        }
1435                                        Err(error) => {
1436                                            // The kill switch or the approval service ended the run.
1437                                            yield Err(error);
1438                                            let _ = session.close().await;
1439                                            return;
1440                                        }
1441                                    }
1442                                } else {
1443                                    ToolDispatch::answer(
1444                                        serde_json::json!({ "error": format!("Tool {} not found", name) }),
1445                                        ToolResultStatus::NotRun,
1446                                        None,
1447                                    )
1448                                };
1449                                let part = outcome.part(&name, &call_id);
1450                                let ToolDispatch { result, actions, .. } = outcome;
1451
1452                                // Yield tool event
1453                                let mut tool_event = Event::new(&invocation_id);
1454                                tool_event.author = agent_name.clone();
1455                                tool_event.actions = actions.clone();
1456                                tool_event.llm_response.content = Some(Content {
1457                                    role: "function".to_string(),
1458                                    parts: vec![part],
1459                                });
1460                                yield Ok(tool_event);
1461
1462                                // Check for escalation
1463                                if actions.escalate || actions.skip_summarization {
1464                                    let _ = session.close().await;
1465                                    return;
1466                                }
1467
1468                                // Send tool response back to session
1469                                let response = ToolResponse {
1470                                    call_id,
1471                                    output: result,
1472                                };
1473                                if let Err(e) = session.send_tool_response(response).await {
1474                                    yield Err(AdkError::model(format!("Failed to send tool response: {}", e)));
1475                                    let _ = session.close().await;
1476                                    return;
1477                                }
1478                            }
1479
1480                            ServerEvent::ResponseDone { response, .. } => {
1481                                // A provider that sends no `TextDone`/`TranscriptDone`
1482                                // (Gemini Live) closes its turn here: its text is final now,
1483                                // so the final events are yielded, screened, from the deltas.
1484                                for (kind, finals) in [("text", &mut pending_text), ("transcript", &mut pending_transcript)] {
1485                                    for (item_id, text) in finals.drain() {
1486                                        let text = match screen_output(
1487                                            #[cfg(feature = "guardrails")]
1488                                            output_guardrails.as_deref(),
1489                                            text,
1490                                        )
1491                                        .await
1492                                        {
1493                                            Ok(text) => text,
1494                                            Err(error) => {
1495                                                let _ = session.interrupt().await;
1496                                                yield Err(error);
1497                                                let _ = session.close().await;
1498                                                return;
1499                                            }
1500                                        };
1501                                        let mut final_event = Event::with_id(
1502                                            format!("{invocation_id}:realtime-{kind}:{item_id}"),
1503                                            &invocation_id,
1504                                        );
1505                                        final_event.author = agent_name.clone();
1506                                        if kind == "transcript" {
1507                                            final_event.provider_metadata.insert(
1508                                                "adk.realtime.transcript".to_string(),
1509                                                "output".to_string(),
1510                                            );
1511                                        }
1512                                        final_event.llm_response.content = Some(Content {
1513                                            role: "model".to_string(),
1514                                            parts: vec![Part::Text { text }],
1515                                        });
1516                                        yield Ok(final_event);
1517                                    }
1518                                }
1519                                reply_item = None;
1520
1521                                // The response's usage, metered in the run's spend ledger and
1522                                // reported on an event so cost per run is visible.
1523                                let usage = match &meter {
1524                                    Some(meter) => match meter.end_response(&response).await {
1525                                        Ok(usage) => usage,
1526                                        Err(e) => {
1527                                            yield Err(AdkError::model(e.to_string()));
1528                                            let _ = session.close().await;
1529                                            return;
1530                                        }
1531                                    },
1532                                    None => RealtimeUsage::from_response(&response).map(|usage| {
1533                                        usage.to_usage_metadata(pricing.map(|pricing| pricing.cost_usd(&usage)))
1534                                    }),
1535                                };
1536                                if let Some(usage) = usage {
1537                                    let mut usage_event = Event::new(&invocation_id);
1538                                    usage_event.author = agent_name.clone();
1539                                    usage_event.llm_response.usage_metadata = Some(usage);
1540                                    usage_event.llm_response.turn_complete = true;
1541                                    yield Ok(usage_event);
1542                                }
1543                            }
1544
1545                            ServerEvent::Error { error, .. } => {
1546                                yield Err(AdkError::model(format!(
1547                                    "Realtime error: {} - {}",
1548                                    error.code.unwrap_or_default(),
1549                                    error.message
1550                                )));
1551                            }
1552
1553
1554                            _ => {
1555                                // Ignore other events
1556                            }
1557                        }
1558                    }
1559                    Some(Err(e)) => {
1560                        yield Err(AdkError::model(format!("Session error: {}", e)));
1561                        break;
1562                    }
1563                    None => {
1564                        // A provider that refuses the setup (Gemini Live: 1007 on a response
1565                        // modality the model does not support) or fails the session closes the
1566                        // socket with a code that says so; a normal close ends the run quietly.
1567                        failed_close = session
1568                            .disconnect_reason()
1569                            .filter(|reason| reason.code.is_some_and(|code| !matches!(code, 1000 | 1001)));
1570                        break;
1571                    }
1572                }
1573            }
1574
1575            // What the user said last is kept even when the session ended before the model
1576            // answered it.
1577            for (_, text) in user_transcripts.drain(..) {
1578                if !text.trim().is_empty() {
1579                    yield Ok(user_turn(&invocation_id, text));
1580                }
1581            }
1582
1583            // 1002, 1003, 1007, 1009 and 1010 report something the client sent that the
1584            // provider refused, such as a setup the model does not support.
1585            if let Some(reason) = failed_close {
1586                let refused = reason.code.is_some_and(|code| matches!(code, 1002 | 1003 | 1007 | 1009 | 1010));
1587                let (category, guidance) = if refused {
1588                    (
1589                        adk_core::ErrorCategory::InvalidInput,
1590                        "the provider refused the session's setup or a message on it; check the \
1591                         model name, modalities, voice and tool schemas against what the model supports",
1592                    )
1593                } else {
1594                    (adk_core::ErrorCategory::Unavailable, "the provider ended the session")
1595                };
1596                yield Err(AdkError::new(
1597                    adk_core::ErrorComponent::Model,
1598                    category,
1599                    "model.realtime.session_closed",
1600                    format!("realtime session closed by the provider ({reason}): {guidance}"),
1601                ));
1602            }
1603
1604            // ===== STOP AVATAR SESSION (cleanup) =====
1605            #[cfg(feature = "video-avatar")]
1606            {
1607                // Abort keep-alive task
1608                if let Some(handle) = _avatar_keep_alive_handle {
1609                    handle.abort();
1610                }
1611                // Stop the avatar session
1612                if let (Some(provider), Some(sess_id)) = (&avatar_provider, &avatar_session_id)
1613                    && let Err(e) = provider.stop_session(sess_id).await
1614                {
1615                    tracing::warn!(error = %e, "avatar session cleanup failed");
1616                }
1617            }
1618
1619            // ===== AFTER AGENT CALLBACKS =====
1620            let mut after_handled = false;
1621            for hook in &ctx.run_config().invocation_hooks {
1622                match hook.after_agent(ctx.clone() as Arc<dyn CallbackContext>).await {
1623                    Ok(Some(content)) => {
1624                        let mut after_event = Event::new(&invocation_id);
1625                        after_event.author = agent_name.clone();
1626                        after_event.llm_response.content = Some(content);
1627                        yield Ok(after_event);
1628                        after_handled = true;
1629                        break;
1630                    }
1631                    Ok(None) => continue,
1632                    Err(e) => {
1633                        yield Err(e);
1634                        return;
1635                    }
1636                }
1637            }
1638            for callback in after_callbacks.iter().filter(|_| !after_handled) {
1639                match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
1640                    Ok(Some(content)) => {
1641                        let mut after_event = Event::new(&invocation_id);
1642                        after_event.author = agent_name.clone();
1643                        after_event.llm_response.content = Some(content);
1644                        yield Ok(after_event);
1645                        break;
1646                    }
1647                    Ok(None) => continue,
1648                    Err(e) => {
1649                        yield Err(e);
1650                        return;
1651                    }
1652                }
1653            }
1654        };
1655
1656        Ok(Box::pin(s))
1657    }
1658}
1659
1660/// The item a reply's text is saved under: the provider's item, or for a reply streamed
1661/// without one (Gemini Live) an id minted on its first delta and kept until its response ends.
1662fn reply_item_id(item_id: String, reply_item: &mut Option<String>) -> String {
1663    if !item_id.is_empty() {
1664        return item_id;
1665    }
1666    reply_item.get_or_insert_with(|| format!("reply-{}", uuid::Uuid::new_v4())).clone()
1667}
1668
1669/// The user's spoken turn, saved as the runner saves a user message: authored `user`, in the
1670/// run's invocation, marked as an input transcript.
1671fn user_turn(invocation_id: &str, text: String) -> Event {
1672    let mut event = Event::new(invocation_id);
1673    event.author = "user".to_string();
1674    event.provider_metadata.insert("adk.realtime.transcript".to_string(), "input".to_string());
1675    event.llm_response.content = Some(Content::new("user").with_text(text));
1676    event
1677}
1678
1679fn pcm16_mono_wav(pcm: &[u8], sample_rate: u32) -> Vec<u8> {
1680    let data_len = u32::try_from(pcm.len()).unwrap_or(u32::MAX);
1681    let mut wav = Vec::with_capacity(44 + pcm.len());
1682    wav.extend_from_slice(b"RIFF");
1683    wav.extend_from_slice(&(36_u32.saturating_add(data_len)).to_le_bytes());
1684    wav.extend_from_slice(b"WAVEfmt ");
1685    wav.extend_from_slice(&16_u32.to_le_bytes());
1686    wav.extend_from_slice(&1_u16.to_le_bytes());
1687    wav.extend_from_slice(&1_u16.to_le_bytes());
1688    wav.extend_from_slice(&sample_rate.to_le_bytes());
1689    wav.extend_from_slice(&sample_rate.saturating_mul(2).to_le_bytes());
1690    wav.extend_from_slice(&2_u16.to_le_bytes());
1691    wav.extend_from_slice(&16_u16.to_le_bytes());
1692    wav.extend_from_slice(b"data");
1693    wav.extend_from_slice(&data_len.to_le_bytes());
1694    wav.extend_from_slice(pcm);
1695    wav
1696}
1697
1698/// Which calls the agent asks a person about, and how it bounds, redacts, and screens tool
1699/// results.
1700#[derive(Clone)]
1701struct ToolResultPolicy {
1702    /// How long one tool call may run.
1703    timeout: std::time::Duration,
1704    /// Screens every result before the model and the session see it.
1705    screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
1706    /// Whether tool and callback error messages reach the model.
1707    expose_error_messages: bool,
1708    /// The tools that need a person's approval before they run.
1709    confirmation: adk_core::ToolConfirmationPolicy,
1710}
1711
1712/// Screens the model's completed `text` with the output guardrails, as `LlmAgent` screens
1713/// final text: a transform rewrites it, a block fails the run with the guardrail's error.
1714#[cfg(feature = "guardrails")]
1715async fn screen_output(
1716    guardrails: Option<&adk_guardrail::GuardrailSet>,
1717    text: String,
1718) -> Result<String> {
1719    use adk_guardrail::{GuardrailExecutor, GuardrailPhase};
1720
1721    let Some(guardrails) = guardrails else {
1722        return Ok(text);
1723    };
1724    if guardrails.is_empty() || text.trim().is_empty() {
1725        return Ok(text);
1726    }
1727    let content = Content::new("model").with_text(&text);
1728    let screening = GuardrailExecutor::enforce(guardrails, &content, GuardrailPhase::Output, false)
1729        .await
1730        .map_err(AdkError::from)?;
1731    Ok(screening.content.parts.iter().filter_map(|part| part.text()).collect())
1732}
1733
1734#[cfg(not(feature = "guardrails"))]
1735async fn screen_output(text: String) -> Result<String> {
1736    Ok(text)
1737}
1738
1739/// The callbacks and result policy one dispatch runs under.
1740#[derive(Clone, Copy)]
1741struct DispatchHooks<'a> {
1742    before_tool_callbacks: &'a [BeforeToolCallback],
1743    after_tool_callbacks: &'a [AfterToolCallback],
1744    policy: &'a ToolResultPolicy,
1745}
1746
1747/// What one realtime tool call produced.
1748struct ToolDispatch {
1749    /// The result sent back to the provider.
1750    result: serde_json::Value,
1751    /// The actions the tool set, carried on the tool event.
1752    actions: EventActions,
1753    /// The request for a call held for a confirmation decision.
1754    held: Option<adk_core::ToolConfirmationRequest>,
1755    /// The status of an answer the agent wrote in place of the tool's result.
1756    status: Option<ToolResultStatus>,
1757    /// The error behind `status`, when there is one.
1758    cause: Option<AdkError>,
1759}
1760
1761impl ToolDispatch {
1762    /// An answer the agent writes, before anything ran.
1763    fn answer(
1764        result: serde_json::Value,
1765        status: ToolResultStatus,
1766        cause: Option<AdkError>,
1767    ) -> Self {
1768        Self { result, actions: EventActions::default(), held: None, status: Some(status), cause }
1769    }
1770
1771    /// The function response the session records for call `call_id` to `name`.
1772    fn part(&self, name: &str, call_id: &str) -> Part {
1773        let mut part = Part::FunctionResponse {
1774            function_response: adk_core::FunctionResponseData::new(name, self.result.clone()),
1775            id: Some(call_id.to_string()),
1776            annotations: None,
1777        };
1778        if let Some(status) = self.status {
1779            part.set_tool_result_status(status, self.cause.as_ref());
1780        }
1781        part
1782    }
1783}
1784
1785/// Runs one realtime tool call: its arguments are parsed strictly, the run's invocation
1786/// hooks and the agent's before-tool callbacks run, the governed path
1787/// ([`adk_core::authorize_tool_call`]) authorizes the call, the tool runs under the policy's
1788/// timeout, the after-tool hooks and callbacks run, and the policy's screen sees the result.
1789///
1790/// The callback contract matches the standard agent loop: a before-callback returning
1791/// `Ok(Some(content))` substitutes a result and the tool does **not** run, `Ok(None)`
1792/// allows it, and an error refuses it and skips the after callbacks. Malformed arguments
1793/// are answered with an error instead of running the tool with `{}`. A tool or callback error
1794/// reaches the model as its component, category, and code unless the policy exposes messages,
1795/// and an after-tool failure withholds the result.
1796///
1797/// # Errors
1798///
1799/// Returns an error, which ends the session, when the kill switch is frozen or the
1800/// confirmation handler or approval store fails.
1801async fn dispatch_tool(
1802    ctx: &Arc<dyn InvocationContext>,
1803    tool: &Arc<dyn Tool>,
1804    call_id: &str,
1805    arguments: &str,
1806    hooks: &DispatchHooks<'_>,
1807    resumes: Option<adk_core::ToolConfirmationRequest>,
1808) -> Result<ToolDispatch> {
1809    let DispatchHooks { before_tool_callbacks, after_tool_callbacks, policy } = *hooks;
1810    let name = tool.name().to_string();
1811    let args = match crate::runner::parse_tool_arguments(arguments) {
1812        Ok(args) => args,
1813        Err(reason) => {
1814            return Ok(ToolDispatch::answer(
1815                serde_json::json!({ "error": format!("Tool '{name}' was not run: {reason}") }),
1816                ToolResultStatus::NotRun,
1817                None,
1818            ));
1819        }
1820    };
1821    let screened_args = policy.screen.as_ref().map(|_| args.clone());
1822    let tool_ctx: Arc<dyn ToolContext> =
1823        Arc::new(RealtimeToolContext::new(ctx.clone(), call_id.to_string()));
1824    let cb_ctx: Arc<dyn CallbackContext> =
1825        Arc::new(ToolCallbackContext::new(ctx.clone(), name.clone(), args.clone()));
1826    let hooks = &ctx.run_config().invocation_hooks;
1827    let record_payloads = ctx.run_config().record_payloads;
1828    // A message can quote credentials or internal hosts, so it is shown to the model only when
1829    // the agent exposes error messages, and logged only when payloads are recorded.
1830    let failure = |error: &AdkError| {
1831        if policy.expose_error_messages { error.to_string() } else { error.redacted() }
1832    };
1833    let log_failure = |error: &AdkError, stage: &str| {
1834        if record_payloads {
1835            tracing::warn!(
1836                tool.name = %name,
1837                error = %error.diagnostics(),
1838                error.message = %error.message,
1839                stage,
1840                "realtime tool call failed"
1841            );
1842        } else {
1843            tracing::warn!(
1844                tool.name = %name,
1845                error = %error.diagnostics(),
1846                stage,
1847                "realtime tool call failed"
1848            );
1849        }
1850    };
1851    let not_run = |error: &AdkError| {
1852        serde_json::json!({
1853            "error": format!(
1854                "tool '{name}' was not run: a before-tool callback failed with {}",
1855                failure(error)
1856            )
1857        })
1858    };
1859
1860    let mut short_circuit: Option<serde_json::Value> = None;
1861    let mut run_after_tool_callbacks = true;
1862    let mut status = None;
1863    let mut cause = None;
1864    for hook in hooks {
1865        match hook.before_tool(cb_ctx.clone()).await {
1866            Ok(Some(content)) => {
1867                short_circuit = Some(content_to_tool_result(&content));
1868                break;
1869            }
1870            Ok(None) => continue,
1871            Err(e) => {
1872                log_failure(&e, "before_tool");
1873                short_circuit = Some(not_run(&e));
1874                run_after_tool_callbacks = false;
1875                status = Some(ToolResultStatus::NotRun);
1876                cause = Some(e);
1877                break;
1878            }
1879        }
1880    }
1881    if short_circuit.is_none() {
1882        for callback in before_tool_callbacks {
1883            match callback(cb_ctx.clone()).await {
1884                Ok(Some(content)) => {
1885                    short_circuit = Some(content_to_tool_result(&content));
1886                    break;
1887                }
1888                Ok(None) => continue,
1889                Err(e) => {
1890                    log_failure(&e, "before_tool");
1891                    short_circuit = Some(not_run(&e));
1892                    run_after_tool_callbacks = false;
1893                    status = Some(ToolResultStatus::NotRun);
1894                    cause = Some(e);
1895                    break;
1896                }
1897            }
1898        }
1899    }
1900
1901    let mut held = None;
1902    let mut confirmation = None;
1903    let mut executed = false;
1904    // Set when a non-idempotent call timed out, so its effect is unknown.
1905    let mut outcome_unknown = false;
1906    let mut result = match short_circuit {
1907        Some(result) => result,
1908        None => {
1909            let gate = adk_core::ToolGate::for_context(ctx.as_ref());
1910            let mut call = adk_core::GovernedCall::for_tool(tool.as_ref(), call_id, args)
1911                .requiring_confirmation(
1912                    ctx.requires_tool_confirmation(&name)
1913                        || policy.confirmation.requires_confirmation(&name),
1914                );
1915            // A resumed call runs under a later invocation, so it is ledgered under its held
1916            // call's identity, as `LlmAgent` ledgers it.
1917            let ledger_key = match &resumes {
1918                Some(held) => adk_core::held_call_ledger_key(
1919                    ctx.app_name(),
1920                    ctx.user_id(),
1921                    ctx.session_id(),
1922                    call_id,
1923                    &held.fingerprint(),
1924                ),
1925                None => tool_ctx.idempotency_key(),
1926            };
1927            if let Some(held) = resumes {
1928                call = call.resuming(held);
1929            }
1930            match adk_core::authorize_tool_call(&gate, call).await? {
1931                adk_core::ToolAuthorization::Execute { args, confirmation: decision } => {
1932                    confirmation = decision;
1933                    let effect = tool.effect();
1934                    // A non-idempotent call executes at most once per idempotency key: a
1935                    // record that exists answers it, and a ledger that cannot be read or
1936                    // written fails it closed.
1937                    match adk_core::begin_ledgered_call(
1938                        ctx.run_config(),
1939                        ctx.as_ref(),
1940                        effect,
1941                        ledger_key,
1942                        &name,
1943                        &args,
1944                    )
1945                    .await?
1946                    {
1947                        Err(recorded) => {
1948                            run_after_tool_callbacks = false;
1949                            status = Some(recorded.status);
1950                            cause = recorded.cause;
1951                            recorded.response
1952                        }
1953                        Ok(ledgered) => {
1954                            // The kill switch again, after the ledger write, which can take
1955                            // long enough for a freeze to arrive. The begun record is completed
1956                            // as not run, and the freeze ends the session as it does at
1957                            // authorization.
1958                            if let Err(refusal) = ctx.run_config().check_governance() {
1959                                let text = adk_core::not_run_text(&refusal);
1960                                if let Some(ledgered) = ledgered {
1961                                    ledgered.complete(&name, None, &text).await;
1962                                }
1963                                return Err(refusal);
1964                            }
1965                            executed = true;
1966                            let timeout = policy.timeout;
1967                            let execution = adk_core::ModelCallScope::within_tool(
1968                                tool_ctx.as_ref(),
1969                                tool.execute(tool_ctx.clone(), args.clone()),
1970                            );
1971                            match tokio::time::timeout(timeout, execution).await {
1972                                Ok(Ok(value)) => {
1973                                    if let Some(ledgered) = ledgered {
1974                                        ledgered.complete(&name, Some(&value), "").await;
1975                                    }
1976                                    value
1977                                }
1978                                Ok(Err(e)) => {
1979                                    log_failure(&e, "execute");
1980                                    let response = adk_core::tool_error_response(
1981                                        &name,
1982                                        &e,
1983                                        policy.expose_error_messages,
1984                                    );
1985                                    if let Some(ledgered) = ledgered {
1986                                        ledgered.complete(&name, None, &response.to_string()).await;
1987                                    }
1988                                    status = Some(ToolResultStatus::of_tool_error(&e));
1989                                    cause = Some(e);
1990                                    response
1991                                }
1992                                Err(_) => {
1993                                    let message =
1994                                        format!("Tool '{name}' timed out after {timeout:?}");
1995                                    // A timed-out call was dropped mid-flight, as in `LlmAgent`;
1996                                    // its begun record stays open, so a replay reports it as
1997                                    // unknown instead of running it again.
1998                                    outcome_unknown = effect == adk_core::ToolEffect::NonIdempotent;
1999                                    status = Some(if outcome_unknown {
2000                                        ToolResultStatus::OutcomeUnknown
2001                                    } else {
2002                                        ToolResultStatus::Failed
2003                                    });
2004                                    cause = Some(AdkError::new(
2005                                        adk_core::ErrorComponent::Tool,
2006                                        adk_core::ErrorCategory::Timeout,
2007                                        "tool.timeout",
2008                                        message.clone(),
2009                                    ));
2010                                    if outcome_unknown {
2011                                        adk_core::record_outcome_unknown(
2012                                            ctx.run_config(),
2013                                            ctx.as_ref(),
2014                                            &name,
2015                                            &args,
2016                                            "interrupted",
2017                                        )
2018                                        .await?;
2019                                        adk_core::interrupted_call_response(&message)
2020                                    } else {
2021                                        if let Some(ledgered) = ledgered {
2022                                            ledgered.complete(&name, None, &message).await;
2023                                        }
2024                                        serde_json::json!({ "error": message })
2025                                    }
2026                                }
2027                            }
2028                        }
2029                    }
2030                }
2031                adk_core::ToolAuthorization::Refuse { reason, confirmation: decision } => {
2032                    confirmation = decision;
2033                    run_after_tool_callbacks = false;
2034                    status = Some(ToolResultStatus::Refused);
2035                    serde_json::json!({ "error": reason })
2036                }
2037                adk_core::ToolAuthorization::Pending { request, reason } => {
2038                    held = Some(request);
2039                    run_after_tool_callbacks = false;
2040                    status = Some(ToolResultStatus::Held);
2041                    serde_json::json!({ "error": reason })
2042                }
2043            }
2044        }
2045    };
2046
2047    // An agent tool whose delegate held a call of its own holds this call with it: the
2048    // run surfaces the delegate's request, and this call resumes once that request has a
2049    // decision (spec 3.1 §10 F4), as `LlmAgent` does.
2050    if executed && held.is_none() {
2051        let mut actions = tool_ctx.actions();
2052        if let Some(mut request) = actions.tool_confirmation.take() {
2053            if outcome_unknown {
2054                // A call that may have taken effect is not held to run again on a decision,
2055                // and no decision on its request may authorize an identical call.
2056                tool_ctx.set_actions(actions);
2057                adk_core::withdraw_held_call(
2058                    &adk_core::ToolGate::for_context(ctx.as_ref()),
2059                    &request,
2060                )
2061                .await?;
2062            } else {
2063                actions.skip_summarization = false;
2064                actions.escalate = false;
2065                tool_ctx.set_actions(actions);
2066                // The request describes the delegate's call; its ID is this call's, so the
2067                // hold resumes as the agent-tool call (`held_tool_calls`).
2068                request.function_call_id = Some(call_id.to_string());
2069                held = Some(request);
2070                run_after_tool_callbacks = false;
2071                status = Some(ToolResultStatus::Held);
2072                cause = None;
2073                if !adk_core::is_confirmation_pending(&result) {
2074                    result = adk_core::confirmation_pending_response(format!(
2075                        "Tool '{name}' is waiting for a confirmation"
2076                    ));
2077                }
2078            }
2079        }
2080    }
2081
2082    if run_after_tool_callbacks {
2083        let mut failed: Option<AdkError> = None;
2084        let mut replaced = false;
2085        for hook in hooks {
2086            match hook.after_tool(cb_ctx.clone()).await {
2087                Ok(Some(modified)) => {
2088                    result = content_to_tool_result(&modified);
2089                    replaced = true;
2090                    break;
2091                }
2092                Ok(None) => continue,
2093                Err(e) => {
2094                    failed = Some(e);
2095                    break;
2096                }
2097            }
2098        }
2099        if failed.is_none() && !replaced {
2100            for callback in after_tool_callbacks {
2101                match callback(cb_ctx.clone()).await {
2102                    Ok(Some(modified)) => {
2103                        result = content_to_tool_result(&modified);
2104                        replaced = true;
2105                        break;
2106                    }
2107                    Ok(None) => continue,
2108                    Err(e) => {
2109                        failed = Some(e);
2110                        break;
2111                    }
2112                }
2113            }
2114        }
2115        // An after-tool stage is where results are redacted, so the result it did not finish
2116        // with is withheld; the model is told the tool ran so it does not repeat the effect.
2117        // A replacement is the answer the model reads; only an unknown outcome outlives it.
2118        if replaced && !outcome_unknown {
2119            status = None;
2120            cause = None;
2121        }
2122        if let Some(error) = failed {
2123            log_failure(&error, "after_tool");
2124            result = if executed {
2125                adk_core::result_withheld_response(&name, &error, policy.expose_error_messages)
2126            } else {
2127                serde_json::json!({
2128                    "error": format!(
2129                        "tool '{name}' was not run, and its after-tool pipeline failed with {}",
2130                        failure(&error)
2131                    )
2132                })
2133            };
2134            if !outcome_unknown {
2135                status = Some(if executed {
2136                    ToolResultStatus::Withheld
2137                } else {
2138                    ToolResultStatus::NotRun
2139                });
2140                cause = Some(error);
2141            }
2142        }
2143    }
2144
2145    if held.is_none()
2146        && let (Some(screen), Some(args)) = (policy.screen.as_ref(), screened_args.as_ref())
2147    {
2148        let withheld;
2149        (result, withheld) =
2150            crate::runner::screen_result(screen.as_ref(), &name, args, result).await;
2151        if withheld {
2152            let screened = ToolResultStatus::when_withheld(status, executed);
2153            if status != Some(screened) {
2154                status = Some(screened);
2155                cause = None;
2156            }
2157        }
2158    }
2159
2160    let mut actions = tool_ctx.actions();
2161    if actions.tool_confirmation_decision.is_none() {
2162        actions.tool_confirmation_decision = confirmation;
2163    }
2164    Ok(ToolDispatch { result, actions, held, status, cause })
2165}
2166
2167/// Turns a callback's substitute `Content` into the result sent back to the provider.
2168///
2169/// A callback returns `Content` because that is what the standard agent loop puts on the
2170/// event stream. The realtime transport wants a JSON tool result, so a function response is
2171/// unwrapped to its payload and anything else is carried as its text.
2172fn content_to_tool_result(content: &Content) -> serde_json::Value {
2173    for part in &content.parts {
2174        if let Part::FunctionResponse { function_response, .. } = part {
2175            return function_response.response.clone();
2176        }
2177    }
2178
2179    let text: String = content.parts.iter().filter_map(|part| part.text()).collect();
2180    serde_json::json!({ "result": text })
2181}
2182
2183struct RealtimeToolContext {
2184    parent_ctx: Arc<dyn InvocationContext>,
2185    function_call_id: String,
2186    actions: Mutex<EventActions>,
2187}
2188
2189impl RealtimeToolContext {
2190    fn new(parent_ctx: Arc<dyn InvocationContext>, function_call_id: String) -> Self {
2191        Self { parent_ctx, function_call_id, actions: Mutex::new(EventActions::default()) }
2192    }
2193}
2194
2195#[async_trait]
2196impl ReadonlyContext for RealtimeToolContext {
2197    fn invocation_id(&self) -> &str {
2198        self.parent_ctx.invocation_id()
2199    }
2200
2201    fn agent_name(&self) -> &str {
2202        self.parent_ctx.agent_name()
2203    }
2204
2205    fn user_id(&self) -> &str {
2206        self.parent_ctx.user_id()
2207    }
2208
2209    fn app_name(&self) -> &str {
2210        self.parent_ctx.app_name()
2211    }
2212
2213    fn session_id(&self) -> &str {
2214        self.parent_ctx.session_id()
2215    }
2216
2217    fn branch(&self) -> &str {
2218        self.parent_ctx.branch()
2219    }
2220
2221    fn user_content(&self) -> &Content {
2222        self.parent_ctx.user_content()
2223    }
2224
2225    fn acting_context(&self) -> adk_core::ActingContext {
2226        self.parent_ctx.acting_context()
2227    }
2228
2229    fn is_authenticated(&self) -> bool {
2230        self.parent_ctx.is_authenticated()
2231    }
2232}
2233
2234#[async_trait]
2235impl CallbackContext for RealtimeToolContext {
2236    fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2237        self.parent_ctx.artifacts()
2238    }
2239
2240    /// Shared state from the parent context, so realtime tools coordinate with the rest of
2241    /// the run rather than seeing `None`.
2242    fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2243        self.parent_ctx.shared_state()
2244    }
2245}
2246
2247#[async_trait]
2248impl ToolContext for RealtimeToolContext {
2249    fn function_call_id(&self) -> &str {
2250        &self.function_call_id
2251    }
2252
2253    fn actions(&self) -> EventActions {
2254        self.actions.lock().unwrap().clone()
2255    }
2256
2257    fn set_actions(&self, actions: EventActions) {
2258        *self.actions.lock().unwrap() = actions;
2259    }
2260
2261    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>> {
2262        if let Some(memory) = self.parent_ctx.memory() {
2263            memory.search(query).await
2264        } else {
2265            Ok(vec![])
2266        }
2267    }
2268
2269    /// The caller's scopes, from the parent context.
2270    ///
2271    /// Without this the trait default returned an empty list, so a scope-checking tool saw an
2272    /// unauthenticated caller in realtime and behaved differently than in the standard loop.
2273    fn user_scopes(&self) -> Vec<String> {
2274        self.parent_ctx.user_scopes()
2275    }
2276
2277    /// Secrets resolved through the parent context.
2278    ///
2279    /// The trait default returns `None`, which a tool cannot distinguish from a secret that is
2280    /// genuinely absent.
2281    async fn get_secret(&self, name: &str) -> Result<Option<String>> {
2282        self.parent_ctx.get_secret(name).await
2283    }
2284
2285    /// The run's configuration, so a tool reads its egress policy and budget as it does in
2286    /// the standard loop.
2287    fn run_config(&self) -> Option<&RunConfig> {
2288        Some(self.parent_ctx.run_config())
2289    }
2290}
2291
2292#[cfg(test)]
2293mod tool_safety_tests {
2294    //! A before-tool callback must be able to stop a tool, and a realtime tool must see the
2295    //! same capabilities it sees in the standard loop.
2296    //!
2297    //! The dispatch loop built `(error_result, EventActions::default())` as a discarded
2298    //! expression statement and then fell through to `tool.execute`, so a denying callback
2299    //! reported a decision that had no effect. After-callback results were dropped with
2300    //! `let _ =`. `RealtimeToolContext` implemented only the required methods, inheriting
2301    //! `user_scopes() -> vec![]`, `get_secret() -> None`, and `shared_state() -> None`, so a
2302    //! scope- or secret-checking tool behaved differently in realtime than under a Runner.
2303
2304    use super::*;
2305    use adk_core::{RunConfig, SharedState, State};
2306    use std::collections::HashMap;
2307    use std::sync::atomic::{AtomicUsize, Ordering};
2308
2309    #[test]
2310    fn completed_pcm_audio_is_wrapped_as_a_playable_wav() {
2311        let pcm = [0_u8, 1, 2, 3];
2312        let wav = pcm16_mono_wav(&pcm, 24_000);
2313
2314        assert_eq!(&wav[0..4], b"RIFF");
2315        assert_eq!(&wav[8..12], b"WAVE");
2316        assert_eq!(&wav[12..16], b"fmt ");
2317        assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 24_000);
2318        assert_eq!(&wav[36..40], b"data");
2319        assert_eq!(u32::from_le_bytes(wav[40..44].try_into().unwrap()), pcm.len() as u32);
2320        assert_eq!(&wav[44..], pcm);
2321    }
2322
2323    /// Counts how many times it is executed.
2324    struct CountingTool {
2325        executions: Arc<AtomicUsize>,
2326    }
2327
2328    #[async_trait]
2329    impl Tool for CountingTool {
2330        fn name(&self) -> &str {
2331            "counting"
2332        }
2333        fn description(&self) -> &str {
2334            "counts executions"
2335        }
2336        async fn execute(
2337            &self,
2338            _ctx: Arc<dyn ToolContext>,
2339            _args: serde_json::Value,
2340        ) -> Result<serde_json::Value> {
2341            self.executions.fetch_add(1, Ordering::SeqCst);
2342            Ok(serde_json::json!({ "ran": true }))
2343        }
2344    }
2345
2346    /// Runs the tool through the callback gate with the supplied callbacks.
2347    async fn dispatch(
2348        before: Vec<BeforeToolCallback>,
2349        after: Vec<AfterToolCallback>,
2350        executions: Arc<AtomicUsize>,
2351    ) -> serde_json::Value {
2352        let tool: Arc<dyn Tool> = Arc::new(CountingTool { executions });
2353        dispatch_with(RunConfig::default(), &tool, "{}", before, after).await.unwrap().result
2354    }
2355
2356    /// Runs `tool` through the governed realtime dispatch under `config`.
2357    async fn dispatch_with(
2358        config: RunConfig,
2359        tool: &Arc<dyn Tool>,
2360        arguments: &str,
2361        before: Vec<BeforeToolCallback>,
2362        after: Vec<AfterToolCallback>,
2363    ) -> Result<ToolDispatch> {
2364        let policy = ToolResultPolicy {
2365            timeout: std::time::Duration::from_millis(50),
2366            screen: None,
2367            expose_error_messages: false,
2368            confirmation: adk_core::ToolConfirmationPolicy::Never,
2369        };
2370        dispatch_with_policy(config, tool, arguments, before, after, &policy).await
2371    }
2372
2373    /// Runs `tool` through the governed realtime dispatch under `config` and `policy`.
2374    async fn dispatch_with_policy(
2375        config: RunConfig,
2376        tool: &Arc<dyn Tool>,
2377        arguments: &str,
2378        before: Vec<BeforeToolCallback>,
2379        after: Vec<AfterToolCallback>,
2380        policy: &ToolResultPolicy,
2381    ) -> Result<ToolDispatch> {
2382        let ctx = Arc::new(CapableParent {
2383            content: Content::new("user"),
2384            config,
2385            session: TestSession,
2386            shared: Arc::new(SharedState::new()),
2387        }) as Arc<dyn InvocationContext>;
2388        let hooks =
2389            DispatchHooks { before_tool_callbacks: &before, after_tool_callbacks: &after, policy };
2390        dispatch_tool(&ctx, tool, "call-1", arguments, &hooks, None).await
2391    }
2392
2393    fn counting(executions: &Arc<AtomicUsize>) -> Arc<dyn Tool> {
2394        Arc::new(CountingTool { executions: Arc::clone(executions) })
2395    }
2396
2397    /// A tool whose delegate held a call: it surfaces the delegate's request through the
2398    /// context's actions, as `AgentTool` does when its agent holds a call.
2399    struct DelegatingTool;
2400
2401    #[async_trait]
2402    impl Tool for DelegatingTool {
2403        fn name(&self) -> &str {
2404            "reviewer"
2405        }
2406        fn description(&self) -> &str {
2407            "delegates"
2408        }
2409        async fn execute(
2410            &self,
2411            ctx: Arc<dyn ToolContext>,
2412            _args: serde_json::Value,
2413        ) -> Result<serde_json::Value> {
2414            let request =
2415                adk_core::ToolConfirmationRequest::new("write_file", serde_json::json!({ "p": 1 }))
2416                    .with_function_call_id("inner-1");
2417            ctx.set_actions(EventActions {
2418                tool_confirmation: Some(request),
2419                ..Default::default()
2420            });
2421            Ok(adk_core::confirmation_pending_response("the reviewer is waiting"))
2422        }
2423    }
2424
2425    /// ROADMAP "realtime runners ignore an `AgentTool` delegate's hold": on `main` the
2426    /// agent-tool call was treated as finished and the delegate's request was dropped.
2427    #[tokio::test]
2428    async fn a_delegates_hold_holds_the_agent_tool_call() {
2429        let tool: Arc<dyn Tool> = Arc::new(DelegatingTool);
2430        let config = RunConfig::builder()
2431            .tool_policy(Arc::new(adk_core::DeclarativePolicy::builder().allow("reviewer").build()))
2432            .build();
2433        let outcome = dispatch_with(config, &tool, "{}", vec![], vec![]).await.unwrap();
2434        let held = outcome.held.expect("the delegate's request holds this call");
2435        assert_eq!(held.tool_name, "write_file", "the request is the delegate's");
2436        assert_eq!(held.function_call_id.as_deref(), Some("call-1"), "under this call's ID");
2437        assert!(adk_core::is_confirmation_pending(&outcome.result), "{}", outcome.result);
2438        assert!(outcome.actions.tool_confirmation.is_none(), "the request is carried as the hold");
2439        assert!(!outcome.actions.escalate && !outcome.actions.skip_summarization);
2440    }
2441
2442    /// A held call resumes under its decision: the request it resumes is the decision's key.
2443    #[tokio::test]
2444    async fn a_resumed_call_runs_under_its_recorded_decision() {
2445        let executions = Arc::new(AtomicUsize::new(0));
2446        let tool = counting(&executions);
2447        let policy = adk_core::DeclarativePolicy::builder()
2448            .require_approval("counting", "needs a person")
2449            .build();
2450        let held = {
2451            let config = RunConfig::builder().tool_policy(Arc::new(policy.clone())).build();
2452            let outcome = dispatch_with(config, &tool, "{}", vec![], vec![]).await.unwrap();
2453            assert_eq!(executions.load(Ordering::SeqCst), 0);
2454            outcome.held.expect("held without a decision")
2455        };
2456        let config = RunConfig::builder()
2457            .tool_policy(Arc::new(policy))
2458            .tool_approval(held.fingerprint(), adk_core::ToolApproval::approve())
2459            .build();
2460        let ctx = Arc::new(CapableParent {
2461            content: Content::new("user"),
2462            config,
2463            session: TestSession,
2464            shared: Arc::new(SharedState::new()),
2465        }) as Arc<dyn InvocationContext>;
2466        let policy = ToolResultPolicy {
2467            timeout: std::time::Duration::from_millis(50),
2468            screen: None,
2469            expose_error_messages: false,
2470            confirmation: adk_core::ToolConfirmationPolicy::Never,
2471        };
2472        let hooks = DispatchHooks {
2473            before_tool_callbacks: &[],
2474            after_tool_callbacks: &[],
2475            policy: &policy,
2476        };
2477        let outcome = dispatch_tool(&ctx, &tool, "call-1", "{}", &hooks, Some(held)).await.unwrap();
2478        assert!(outcome.held.is_none(), "the decision resumed the call");
2479        assert_eq!(outcome.result, serde_json::json!({ "ran": true }));
2480        assert_eq!(executions.load(Ordering::SeqCst), 1);
2481    }
2482
2483    /// The request a held call carries names the acting agent, so its fingerprint does too
2484    /// (#1210).
2485    #[tokio::test]
2486    async fn a_held_call_names_the_acting_agent() {
2487        let executions = Arc::new(AtomicUsize::new(0));
2488        let tool = counting(&executions);
2489        let config = RunConfig::builder()
2490            .tool_policy(Arc::new(
2491                adk_core::DeclarativePolicy::builder()
2492                    .require_approval("counting", "needs a person")
2493                    .build(),
2494            ))
2495            .build();
2496        let outcome = dispatch_with(config, &tool, "{}", vec![], vec![]).await.unwrap();
2497        let held = outcome.held.expect("held without a decision");
2498        assert_eq!(
2499            held.acting.as_ref().map(|acting| acting.agent.id.as_str()),
2500            Some("urn:adk:agent:app/agent")
2501        );
2502        assert_eq!(
2503            adk_core::ToolConfirmationRequest::fingerprint_agent(&held.fingerprint()),
2504            Some("urn:adk:agent:app/agent")
2505        );
2506        assert_eq!(held.origin, Some(adk_core::ToolOrigin::of(tool.as_ref())));
2507    }
2508
2509    /// ROADMAP "No content guardrails on the model's own text or transcript events".
2510    #[cfg(feature = "guardrails")]
2511    #[tokio::test]
2512    async fn final_text_is_screened_by_the_output_guardrails() {
2513        use adk_guardrail::{GuardrailSet, PiiRedactor};
2514        let set = GuardrailSet::new().with(PiiRedactor::new());
2515        let text = screen_output(Some(&set), "Mail ana@example.com".to_string()).await.unwrap();
2516        assert_eq!(text, "Mail [EMAIL REDACTED]");
2517        let unchanged = screen_output(None, "Mail ana@example.com".to_string()).await.unwrap();
2518        assert_eq!(unchanged, "Mail ana@example.com");
2519    }
2520
2521    #[tokio::test]
2522    async fn malformed_arguments_are_refused_instead_of_running_with_an_empty_object() {
2523        let executions = Arc::new(AtomicUsize::new(0));
2524        let outcome = dispatch_with(
2525            RunConfig::default(),
2526            &counting(&executions),
2527            r#"{"amount": "#,
2528            vec![],
2529            vec![],
2530        )
2531        .await
2532        .unwrap();
2533
2534        assert_eq!(executions.load(Ordering::SeqCst), 0);
2535        let error = outcome.result["error"].as_str().unwrap_or_default();
2536        assert!(error.contains("not valid JSON"), "{error}");
2537    }
2538
2539    #[tokio::test]
2540    async fn the_run_policy_governs_realtime_tool_calls() {
2541        let executions = Arc::new(AtomicUsize::new(0));
2542        let deny_all = RunConfig::builder()
2543            .tool_policy(Arc::new(adk_core::DeclarativePolicy::builder().build()))
2544            .build();
2545        let outcome =
2546            dispatch_with(deny_all, &counting(&executions), "{}", vec![], vec![]).await.unwrap();
2547        assert_eq!(executions.load(Ordering::SeqCst), 0);
2548        assert!(outcome.result["error"].as_str().unwrap_or_default().contains("denied by policy"));
2549
2550        let approval = RunConfig::builder()
2551            .tool_policy(Arc::new(
2552                adk_core::DeclarativePolicy::builder()
2553                    .require_approval("*", "voice actions")
2554                    .build(),
2555            ))
2556            .build();
2557        let held =
2558            dispatch_with(approval, &counting(&executions), "{}", vec![], vec![]).await.unwrap();
2559        assert_eq!(executions.load(Ordering::SeqCst), 0);
2560        assert_eq!(held.held.map(|request| request.tool_name), Some("counting".to_string()));
2561    }
2562
2563    /// The agent's own confirmation policy holds a call no run-level rule holds, as
2564    /// `LlmAgent`'s `require_tool_confirmation` does.
2565    #[tokio::test]
2566    async fn the_agents_confirmation_policy_holds_the_call() {
2567        let executions = Arc::new(AtomicUsize::new(0));
2568        let policy = ToolResultPolicy {
2569            timeout: std::time::Duration::from_millis(50),
2570            screen: None,
2571            expose_error_messages: false,
2572            confirmation: adk_core::ToolConfirmationPolicy::Never.with_tool("counting"),
2573        };
2574
2575        let held = dispatch_with_policy(
2576            RunConfig::default(),
2577            &counting(&executions),
2578            "{}",
2579            vec![],
2580            vec![],
2581            &policy,
2582        )
2583        .await
2584        .unwrap();
2585
2586        assert_eq!(executions.load(Ordering::SeqCst), 0);
2587        assert_eq!(held.held.map(|request| request.tool_name), Some("counting".to_string()));
2588        assert_eq!(
2589            held.result,
2590            serde_json::json!({ "error": "Tool 'counting' requires confirmation" })
2591        );
2592    }
2593
2594    #[tokio::test]
2595    async fn a_frozen_run_refuses_the_tool_and_ends() {
2596        let executions = Arc::new(AtomicUsize::new(0));
2597        let control = adk_core::GovernanceControl::new();
2598        control.freeze("drill");
2599        let config = RunConfig::builder().governance(control).build();
2600
2601        let error = dispatch_with(config, &counting(&executions), "{}", vec![], vec![])
2602            .await
2603            .err()
2604            .expect("a frozen run must end");
2605
2606        assert_eq!(error.code, "governance.frozen");
2607        assert_eq!(executions.load(Ordering::SeqCst), 0);
2608    }
2609
2610    /// Sleeps well past the dispatch timeout.
2611    struct SlowTool;
2612
2613    #[async_trait]
2614    impl Tool for SlowTool {
2615        fn name(&self) -> &str {
2616            "slow"
2617        }
2618        fn description(&self) -> &str {
2619            "never finishes in time"
2620        }
2621        async fn execute(
2622            &self,
2623            _ctx: Arc<dyn ToolContext>,
2624            _args: serde_json::Value,
2625        ) -> Result<serde_json::Value> {
2626            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
2627            Ok(serde_json::json!({ "late": true }))
2628        }
2629    }
2630
2631    /// A tool that declares no effect is treated as non-idempotent, so a timeout may have
2632    /// taken effect and is answered as an unknown outcome, as `LlmAgent` answers it.
2633    #[tokio::test]
2634    async fn a_tool_that_outlives_its_timeout_is_answered_as_an_unknown_outcome() {
2635        let tool: Arc<dyn Tool> = Arc::new(SlowTool);
2636        let outcome =
2637            dispatch_with(RunConfig::default(), &tool, "{}", vec![], vec![]).await.unwrap();
2638        assert!(adk_core::is_outcome_unknown(&outcome.result), "{}", outcome.result);
2639        assert!(outcome.result["detail"].as_str().unwrap_or_default().contains("timed out"));
2640    }
2641
2642    /// A runner plugin that refuses every tool.
2643    #[derive(Debug)]
2644    struct RefuseTools;
2645
2646    #[async_trait]
2647    impl adk_core::InvocationHooks for RefuseTools {
2648        async fn before_tool(&self, _ctx: Arc<dyn CallbackContext>) -> Result<Option<Content>> {
2649            Ok(Some(Content::new("function").with_text("tools are paused")))
2650        }
2651    }
2652
2653    #[tokio::test]
2654    async fn runner_plugin_tool_hooks_reach_realtime_calls() {
2655        let executions = Arc::new(AtomicUsize::new(0));
2656        let config = RunConfig::builder().invocation_hook(Arc::new(RefuseTools)).build();
2657        let outcome =
2658            dispatch_with(config, &counting(&executions), "{}", vec![], vec![]).await.unwrap();
2659        assert_eq!(executions.load(Ordering::SeqCst), 0);
2660        assert_eq!(outcome.result, serde_json::json!({ "result": "tools are paused" }));
2661    }
2662
2663    #[tokio::test]
2664    async fn a_before_callback_error_prevents_execution() {
2665        let executions = Arc::new(AtomicUsize::new(0));
2666        let before: Vec<BeforeToolCallback> =
2667            vec![Box::new(|_ctx| Box::pin(async { Err(AdkError::tool("denied by policy")) }))];
2668
2669        let result = dispatch(before, vec![], Arc::clone(&executions)).await;
2670
2671        assert_eq!(executions.load(Ordering::SeqCst), 0, "a refused tool must not run: {result}");
2672        // A callback that fails is reported by its code, as the standard agent loop does; a
2673        // callback that refuses on purpose returns its reason as content instead.
2674        assert_eq!(
2675            result,
2676            serde_json::json!({
2677                "error": "tool 'counting' was not run: a before-tool callback failed with \
2678                          tool.internal (tool.legacy)"
2679            })
2680        );
2681    }
2682
2683    #[tokio::test]
2684    async fn a_before_callback_substitution_prevents_execution() {
2685        let executions = Arc::new(AtomicUsize::new(0));
2686        let before: Vec<BeforeToolCallback> = vec![Box::new(|_ctx| {
2687            Box::pin(async {
2688                Ok(Some(Content {
2689                    role: "function".to_string(),
2690                    parts: vec![Part::FunctionResponse {
2691                        function_response: adk_core::FunctionResponseData::new(
2692                            "counting",
2693                            serde_json::json!({ "cached": true }),
2694                        ),
2695                        id: None,
2696                        annotations: None,
2697                    }],
2698                }))
2699            })
2700        })];
2701
2702        let result = dispatch(before, vec![], Arc::clone(&executions)).await;
2703
2704        assert_eq!(
2705            executions.load(Ordering::SeqCst),
2706            0,
2707            "a substituted result must not run the tool"
2708        );
2709        assert_eq!(result, serde_json::json!({ "cached": true }));
2710    }
2711
2712    #[tokio::test]
2713    async fn a_permitting_callback_lets_the_tool_run() {
2714        let executions = Arc::new(AtomicUsize::new(0));
2715        let before: Vec<BeforeToolCallback> = vec![Box::new(|_ctx| Box::pin(async { Ok(None) }))];
2716
2717        let result = dispatch(before, vec![], Arc::clone(&executions)).await;
2718
2719        assert_eq!(executions.load(Ordering::SeqCst), 1);
2720        assert_eq!(result, serde_json::json!({ "ran": true }));
2721    }
2722
2723    #[tokio::test]
2724    async fn an_after_callback_error_withholds_the_result() {
2725        let executions = Arc::new(AtomicUsize::new(0));
2726        let after: Vec<AfterToolCallback> =
2727            vec![Box::new(|_ctx| Box::pin(async { Err(AdkError::tool("post-check failed")) }))];
2728
2729        let result = dispatch(vec![], after, Arc::clone(&executions)).await;
2730
2731        assert_eq!(executions.load(Ordering::SeqCst), 1, "the tool ran, as it should have");
2732        assert_eq!(result["status"], adk_core::RESULT_WITHHELD_STATUS, "{result}");
2733        let error = result["error"].as_str().unwrap_or_default();
2734        assert!(error.contains("tool.internal (tool.legacy)"), "{result}");
2735        assert!(!error.contains("post-check failed"), "the message stays local: {result}");
2736        assert!(!result.to_string().contains("ran\":true"), "the result is withheld: {result}");
2737    }
2738
2739    /// Fails with a message that quotes a credential.
2740    struct LeakyTool;
2741
2742    #[async_trait]
2743    impl Tool for LeakyTool {
2744        fn name(&self) -> &str {
2745            "orders"
2746        }
2747        fn description(&self) -> &str {
2748            "fails with a credential in its message"
2749        }
2750        async fn execute(
2751            &self,
2752            _ctx: Arc<dyn ToolContext>,
2753            _args: serde_json::Value,
2754        ) -> Result<serde_json::Value> {
2755            Err(AdkError::new(
2756                adk_core::ErrorComponent::Tool,
2757                adk_core::ErrorCategory::Unavailable,
2758                "tool.orders.unavailable",
2759                "connect postgres://admin:hunter2@db.internal/prod failed",
2760            ))
2761        }
2762    }
2763
2764    #[tokio::test]
2765    async fn tool_errors_reach_the_model_redacted_unless_exposed() {
2766        let tool: Arc<dyn Tool> = Arc::new(LeakyTool);
2767        let mut policy = ToolResultPolicy {
2768            timeout: std::time::Duration::from_millis(50),
2769            screen: None,
2770            expose_error_messages: false,
2771            confirmation: adk_core::ToolConfirmationPolicy::Never,
2772        };
2773        let hidden =
2774            dispatch_with_policy(RunConfig::default(), &tool, "{}", vec![], vec![], &policy)
2775                .await
2776                .unwrap()
2777                .result;
2778        assert_eq!(
2779            hidden,
2780            serde_json::json!({
2781                "error": "tool 'orders' failed: tool.unavailable (tool.orders.unavailable)"
2782            })
2783        );
2784
2785        policy.expose_error_messages = true;
2786        let shown =
2787            dispatch_with_policy(RunConfig::default(), &tool, "{}", vec![], vec![], &policy)
2788                .await
2789                .unwrap()
2790                .result;
2791        assert!(shown["error"].as_str().unwrap_or_default().contains("hunter2"), "{shown}");
2792    }
2793
2794    /// Replaces every result with a fixed value, or fails when `fail` is set.
2795    struct FixedScreen {
2796        fail: bool,
2797    }
2798
2799    #[async_trait]
2800    impl adk_core::ToolResultScreen for FixedScreen {
2801        async fn screen_result(
2802            &self,
2803            tool_name: &str,
2804            _args: &serde_json::Value,
2805            result: &serde_json::Value,
2806        ) -> std::result::Result<serde_json::Value, String> {
2807            if self.fail {
2808                return Err("the screening service is unavailable".to_string());
2809            }
2810            Ok(serde_json::json!({ "screened": tool_name, "had": result.clone() }))
2811        }
2812    }
2813
2814    #[tokio::test]
2815    async fn the_result_screen_sees_and_rewrites_every_result() {
2816        let executions = Arc::new(AtomicUsize::new(0));
2817        let policy = ToolResultPolicy {
2818            timeout: std::time::Duration::from_millis(50),
2819            screen: Some(Arc::new(FixedScreen { fail: false })),
2820            expose_error_messages: false,
2821            confirmation: adk_core::ToolConfirmationPolicy::Never,
2822        };
2823        let result = dispatch_with_policy(
2824            RunConfig::default(),
2825            &counting(&executions),
2826            "{}",
2827            vec![],
2828            vec![],
2829            &policy,
2830        )
2831        .await
2832        .unwrap()
2833        .result;
2834        assert_eq!(result, serde_json::json!({ "screened": "counting", "had": { "ran": true } }));
2835    }
2836
2837    #[tokio::test]
2838    async fn a_failing_screen_withholds_the_result() {
2839        let executions = Arc::new(AtomicUsize::new(0));
2840        let policy = ToolResultPolicy {
2841            timeout: std::time::Duration::from_millis(50),
2842            screen: Some(Arc::new(FixedScreen { fail: true })),
2843            expose_error_messages: false,
2844            confirmation: adk_core::ToolConfirmationPolicy::Never,
2845        };
2846        let result = dispatch_with_policy(
2847            RunConfig::default(),
2848            &counting(&executions),
2849            "{}",
2850            vec![],
2851            vec![],
2852            &policy,
2853        )
2854        .await
2855        .unwrap()
2856        .result;
2857        assert_eq!(executions.load(Ordering::SeqCst), 1);
2858        assert_eq!(result["status"], adk_core::RESULT_WITHHELD_STATUS, "{result}");
2859        assert!(!result.to_string().contains("\"ran\""), "{result}");
2860    }
2861
2862    #[tokio::test]
2863    async fn after_callbacks_are_skipped_when_a_before_callback_refuses() {
2864        let executions = Arc::new(AtomicUsize::new(0));
2865        let after_ran = Arc::new(AtomicUsize::new(0));
2866        let counter = Arc::clone(&after_ran);
2867
2868        let before: Vec<BeforeToolCallback> =
2869            vec![Box::new(|_ctx| Box::pin(async { Err(AdkError::tool("refused")) }))];
2870        let after: Vec<AfterToolCallback> = vec![Box::new(move |_ctx| {
2871            let counter = Arc::clone(&counter);
2872            Box::pin(async move {
2873                counter.fetch_add(1, Ordering::SeqCst);
2874                Ok(None)
2875            })
2876        })];
2877
2878        let result = dispatch(before, after, Arc::clone(&executions)).await;
2879
2880        assert_eq!(executions.load(Ordering::SeqCst), 0);
2881        assert_eq!(after_ran.load(Ordering::SeqCst), 0, "matching the standard loop's ordering");
2882        let error = result["error"].as_str().unwrap_or_default();
2883        assert!(error.contains("was not run") && error.contains("tool.legacy"), "{result}");
2884        assert!(!error.contains("refused"), "the callback's message stays local: {result}");
2885    }
2886
2887    // ── Context capabilities ──────────────────────────────────────────
2888
2889    struct TestState;
2890    impl State for TestState {
2891        fn get(&self, _key: &str) -> Option<serde_json::Value> {
2892            None
2893        }
2894        fn set(&mut self, _key: String, _value: serde_json::Value) {}
2895        fn all(&self) -> HashMap<String, serde_json::Value> {
2896            HashMap::new()
2897        }
2898    }
2899
2900    struct TestSession;
2901    impl adk_core::Session for TestSession {
2902        fn id(&self) -> &str {
2903            "session"
2904        }
2905        fn app_name(&self) -> &str {
2906            "app"
2907        }
2908        fn user_id(&self) -> &str {
2909            "user"
2910        }
2911        fn state(&self) -> &dyn State {
2912            &TestState
2913        }
2914        fn conversation_history(&self) -> Vec<Content> {
2915            Vec::new()
2916        }
2917    }
2918
2919    /// A parent context carrying the capabilities a tool should still see in realtime.
2920    struct CapableParent {
2921        content: Content,
2922        config: RunConfig,
2923        session: TestSession,
2924        shared: Arc<SharedState>,
2925    }
2926
2927    #[async_trait]
2928    impl ReadonlyContext for CapableParent {
2929        fn invocation_id(&self) -> &str {
2930            "inv"
2931        }
2932        fn agent_name(&self) -> &str {
2933            "agent"
2934        }
2935        fn user_id(&self) -> &str {
2936            "user"
2937        }
2938        fn app_name(&self) -> &str {
2939            "app"
2940        }
2941        fn session_id(&self) -> &str {
2942            "session"
2943        }
2944        fn branch(&self) -> &str {
2945            ""
2946        }
2947        fn user_content(&self) -> &Content {
2948            &self.content
2949        }
2950        fn is_authenticated(&self) -> bool {
2951            true
2952        }
2953    }
2954
2955    #[async_trait]
2956    impl CallbackContext for CapableParent {
2957        fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2958            None
2959        }
2960
2961        fn shared_state(&self) -> Option<Arc<SharedState>> {
2962            Some(Arc::clone(&self.shared))
2963        }
2964    }
2965
2966    #[async_trait]
2967    impl InvocationContext for CapableParent {
2968        fn agent(&self) -> Arc<dyn Agent> {
2969            unreachable!("not used by these tests")
2970        }
2971        fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
2972            None
2973        }
2974        fn session(&self) -> &dyn adk_core::Session {
2975            &self.session
2976        }
2977        fn run_config(&self) -> &RunConfig {
2978            &self.config
2979        }
2980        fn end_invocation(&self) {}
2981        fn ended(&self) -> bool {
2982            false
2983        }
2984        fn user_scopes(&self) -> Vec<String> {
2985            vec!["repo:write".to_string()]
2986        }
2987        async fn get_secret(&self, name: &str) -> Result<Option<String>> {
2988            Ok(Some(format!("secret-for-{name}")))
2989        }
2990    }
2991
2992    #[tokio::test]
2993    async fn the_realtime_tool_context_preserves_parent_capabilities() {
2994        let parent = Arc::new(CapableParent {
2995            content: Content::new("user"),
2996            config: RunConfig::default(),
2997            session: TestSession,
2998            shared: Arc::new(SharedState::new()),
2999        }) as Arc<dyn InvocationContext>;
3000
3001        let ctx = RealtimeToolContext::new(parent, "call-1".to_string());
3002
3003        assert_eq!(
3004            ctx.user_scopes(),
3005            vec!["repo:write".to_string()],
3006            "an empty scope list makes an authenticated caller look anonymous"
3007        );
3008        assert_eq!(ctx.get_secret("api_key").await.unwrap().as_deref(), Some("secret-for-api_key"));
3009        assert!(ctx.shared_state().is_some(), "shared state must reach realtime tools");
3010        assert!(ctx.is_authenticated(), "an authenticated caller must not look anonymous");
3011        assert_eq!(ctx.app_name(), "app", "identity still delegates");
3012    }
3013
3014    /// The status of every answer the realtime agent writes: whole function response parts.
3015    mod tool_status {
3016        use super::*;
3017        use adk_core::{ApprovalStore as _, ToolEffect};
3018
3019        /// The part the session records for `call-1`, with `annotations`.
3020        fn part(
3021            name: &str,
3022            response: serde_json::Value,
3023            annotations: Option<serde_json::Value>,
3024        ) -> Part {
3025            Part::FunctionResponse {
3026                function_response: adk_core::FunctionResponseData::new(name, response),
3027                id: Some("call-1".to_string()),
3028                annotations,
3029            }
3030        }
3031
3032        fn status(status: &str) -> Option<serde_json::Value> {
3033            Some(serde_json::json!({ adk_core::TOOL_RESULT_STATUS_KEY: status }))
3034        }
3035
3036        fn caused(status: &str, code: &str, category: &str) -> Option<serde_json::Value> {
3037            Some(serde_json::json!({
3038                adk_core::TOOL_RESULT_STATUS_KEY: status,
3039                adk_core::TOOL_RESULT_ERROR_CODE_KEY: code,
3040                adk_core::TOOL_RESULT_ERROR_CATEGORY_KEY: category,
3041            }))
3042        }
3043
3044        /// Sleeps past the dispatch timeout with `effect`; when `store` is set it first asks
3045        /// for a confirmation as an agent tool's delegate does.
3046        struct Hangs {
3047            effect: ToolEffect,
3048            store: Option<Arc<adk_core::InMemoryApprovalStore>>,
3049        }
3050
3051        fn delegated() -> adk_core::ToolConfirmationRequest {
3052            adk_core::ToolConfirmationRequest::new("write_file", serde_json::json!({ "p": 1 }))
3053                .with_function_call_id("inner-1")
3054        }
3055
3056        fn scope() -> adk_core::ApprovalScope {
3057            adk_core::ApprovalScope::new("app", "user", "session")
3058        }
3059
3060        #[async_trait]
3061        impl Tool for Hangs {
3062            fn name(&self) -> &str {
3063                "slow"
3064            }
3065            fn description(&self) -> &str {
3066                "never finishes in time"
3067            }
3068            fn effect(&self) -> ToolEffect {
3069                self.effect
3070            }
3071            async fn execute(
3072                &self,
3073                ctx: Arc<dyn ToolContext>,
3074                _args: serde_json::Value,
3075            ) -> Result<serde_json::Value> {
3076                if let Some(store) = &self.store {
3077                    store.record_pending(&scope(), &delegated()).await?;
3078                    ctx.set_actions(EventActions {
3079                        tool_confirmation: Some(delegated()),
3080                        ..Default::default()
3081                    });
3082                }
3083                tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
3084                Ok(serde_json::json!({ "late": true }))
3085            }
3086        }
3087
3088        /// #1006 labelled every realtime timeout `failed`, though a non-idempotent call that
3089        /// timed out may have taken effect.
3090        #[tokio::test(start_paused = true)]
3091        async fn a_timeout_is_an_unknown_outcome_only_for_a_non_idempotent_tool() {
3092            let message = "Tool 'slow' timed out after 50ms";
3093            for (effect, expected, response) in [
3094                (
3095                    ToolEffect::NonIdempotent,
3096                    "outcome_unknown",
3097                    adk_core::interrupted_call_response(message),
3098                ),
3099                (ToolEffect::Idempotent, "failed", serde_json::json!({ "error": message })),
3100            ] {
3101                let tool: Arc<dyn Tool> = Arc::new(Hangs { effect, store: None });
3102                let outcome =
3103                    dispatch_with(RunConfig::default(), &tool, "{}", vec![], vec![]).await.unwrap();
3104                assert_eq!(
3105                    outcome.part("slow", "call-1"),
3106                    part("slow", response, caused(expected, "tool.timeout", "timeout")),
3107                    "{effect:?}"
3108                );
3109            }
3110        }
3111
3112        /// #1006 left a superseded request pending, so a later approval could authorize an
3113        /// identical call.
3114        #[tokio::test(start_paused = true)]
3115        async fn an_unknown_outcome_supersedes_a_delegates_request_and_withdraws_it() {
3116            let store = Arc::new(adk_core::InMemoryApprovalStore::new());
3117            let tool: Arc<dyn Tool> =
3118                Arc::new(Hangs { effect: ToolEffect::NonIdempotent, store: Some(store.clone()) });
3119            let config = RunConfig::builder().approval_store(store.clone()).build();
3120
3121            let outcome = dispatch_with(config, &tool, "{}", vec![], vec![]).await.unwrap();
3122
3123            assert!(outcome.held.is_none(), "the call is not held");
3124            assert!(outcome.actions.tool_confirmation.is_none());
3125            assert_eq!(
3126                outcome.part("slow", "call-1"),
3127                part(
3128                    "slow",
3129                    adk_core::interrupted_call_response("Tool 'slow' timed out after 50ms"),
3130                    caused("outcome_unknown", "tool.timeout", "timeout"),
3131                )
3132            );
3133            assert!(store.pending(&scope()).await.unwrap().is_empty(), "the request is withdrawn");
3134        }
3135
3136        #[tokio::test]
3137        async fn refusals_holds_and_skipped_calls_carry_their_status() {
3138            let executions = Arc::new(AtomicUsize::new(0));
3139            let tool = counting(&executions);
3140
3141            let deny = RunConfig::builder()
3142                .tool_policy(Arc::new(
3143                    adk_core::DeclarativePolicy::builder().deny("counting", "closed").build(),
3144                ))
3145                .build();
3146            let outcome = dispatch_with(deny, &tool, "{}", vec![], vec![]).await.unwrap();
3147            assert_eq!(
3148                outcome.part("counting", "call-1"),
3149                part(
3150                    "counting",
3151                    serde_json::json!({ "error": "Tool 'counting' denied by policy: closed" }),
3152                    status("refused"),
3153                )
3154            );
3155
3156            let approval = RunConfig::builder()
3157                .tool_policy(Arc::new(
3158                    adk_core::DeclarativePolicy::builder()
3159                        .require_approval("counting", "voice actions")
3160                        .build(),
3161                ))
3162                .build();
3163            let outcome = dispatch_with(approval, &tool, "{}", vec![], vec![]).await.unwrap();
3164            assert_eq!(
3165                outcome.part("counting", "call-1"),
3166                part(
3167                    "counting",
3168                    serde_json::json!({
3169                        "error": "Tool 'counting' requires confirmation: voice actions"
3170                    }),
3171                    status("held"),
3172                )
3173            );
3174
3175            let outcome =
3176                dispatch_with(RunConfig::default(), &tool, "[1]", vec![], vec![]).await.unwrap();
3177            assert_eq!(
3178                outcome.part("counting", "call-1"),
3179                part("counting", outcome.result.clone(), status("not_run"))
3180            );
3181
3182            let before: Vec<BeforeToolCallback> = vec![Box::new(|_ctx| {
3183                Box::pin(async {
3184                    Err(AdkError::new(
3185                        adk_core::ErrorComponent::Agent,
3186                        adk_core::ErrorCategory::Unavailable,
3187                        "audit.down",
3188                        "audit sink down",
3189                    ))
3190                })
3191            })];
3192            let outcome =
3193                dispatch_with(RunConfig::default(), &tool, "{}", before, vec![]).await.unwrap();
3194            assert_eq!(
3195                outcome.part("counting", "call-1"),
3196                part(
3197                    "counting",
3198                    serde_json::json!({
3199                        "error": "tool 'counting' was not run: a before-tool callback failed \
3200                                  with agent.unavailable (audit.down)"
3201                    }),
3202                    caused("not_run", "audit.down", "unavailable"),
3203                )
3204            );
3205            assert_eq!(executions.load(Ordering::SeqCst), 0);
3206
3207            let outcome =
3208                dispatch_with(RunConfig::default(), &tool, "{}", vec![], vec![]).await.unwrap();
3209            assert_eq!(
3210                outcome.part("counting", "call-1"),
3211                part("counting", serde_json::json!({ "ran": true }), None),
3212                "a tool's own result carries no status"
3213            );
3214        }
3215
3216        /// Withholds every result.
3217        struct WithholdAll;
3218
3219        #[async_trait]
3220        impl adk_core::ToolResultScreen for WithholdAll {
3221            async fn screen_result(
3222                &self,
3223                _tool: &str,
3224                _args: &serde_json::Value,
3225                _result: &serde_json::Value,
3226            ) -> std::result::Result<serde_json::Value, String> {
3227                Err("screening is down".to_string())
3228            }
3229        }
3230
3231        #[tokio::test]
3232        async fn a_withheld_result_is_withheld_only_when_the_call_ran() {
3233            let executions = Arc::new(AtomicUsize::new(0));
3234            let tool = counting(&executions);
3235            let policy = ToolResultPolicy {
3236                timeout: std::time::Duration::from_millis(50),
3237                screen: Some(Arc::new(WithholdAll)),
3238                expose_error_messages: false,
3239                confirmation: adk_core::ToolConfirmationPolicy::Never,
3240            };
3241            let blocked = adk_core::result_blocked_response("counting", "screening is down");
3242
3243            let outcome =
3244                dispatch_with_policy(RunConfig::default(), &tool, "{}", vec![], vec![], &policy)
3245                    .await
3246                    .unwrap();
3247            assert_eq!(
3248                outcome.part("counting", "call-1"),
3249                part("counting", blocked.clone(), status("withheld"))
3250            );
3251
3252            let deny = RunConfig::builder()
3253                .tool_policy(Arc::new(adk_core::DeclarativePolicy::builder().build()))
3254                .build();
3255            let outcome =
3256                dispatch_with_policy(deny, &tool, "{}", vec![], vec![], &policy).await.unwrap();
3257            assert_eq!(
3258                outcome.part("counting", "call-1"),
3259                part("counting", blocked, status("refused"))
3260            );
3261        }
3262    }
3263}