Skip to main content

adk_realtime/
runner.rs

1//! RealtimeRunner for integrating realtime sessions with agents.
2//!
3//! This module provides the bridge between realtime audio sessions and
4//! the ADK agent framework, handling tool execution and event routing.
5
6use crate::config::{RealtimeConfig, SessionUpdateConfig, ToolDefinition};
7use crate::error::{RealtimeError, Result};
8use crate::events::{ServerEvent, ToolCall, ToolResponse};
9use crate::metering::{RealtimePricing, ResponseMeter};
10use crate::model::BoxedModel;
11use crate::session::ContextMutationOutcome;
12use async_trait::async_trait;
13use std::collections::HashMap;
14use std::sync::Arc;
15use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
16use tokio::sync::RwLock;
17
18/// How long a realtime tool may run before its call is answered with a timeout error.
19pub const DEFAULT_REALTIME_TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
20
21/// The agent a realtime runner governs and meters its tool calls under unless
22/// [`RealtimeRunnerBuilder::agent_name`] names another; `IntegratedRealtimeRunner` also
23/// authors its held-call events with it, where [`adk_core::held_tool_calls`] finds them.
24pub const DEFAULT_REALTIME_AGENT_NAME: &str = "realtime";
25
26/// [`ToolOrigin::source`](adk_core::ToolOrigin::source) of a native handler registered on a
27/// [`RealtimeRunner`] with [`RealtimeRunnerBuilder::tool`].
28///
29/// A governed call to the handler carries this source and a digest of the handler's
30/// [`ToolDefinition`] ([`ToolDefinition::handler_origin`]), so an approval of the call never
31/// authorizes a [`Tool`](adk_core::Tool) of the same name and stops applying when the
32/// handler's description or parameters change.
33pub const REALTIME_HANDLER_ORIGIN: &str = "realtime";
34
35/// Runs `screen` on `result`, returning the result to deliver — the
36/// [`result_blocked_response`](adk_core::result_blocked_response) that replaces a withheld one —
37/// and whether the screen withheld it, which sets the answer's
38/// [`ToolResultStatus`](adk_core::ToolResultStatus).
39pub(crate) async fn screen_result(
40    screen: &dyn adk_core::ToolResultScreen,
41    name: &str,
42    args: &serde_json::Value,
43    result: serde_json::Value,
44) -> (serde_json::Value, bool) {
45    match screen.screen_result(name, args, &result).await {
46        Ok(screened) => (screened, false),
47        Err(reason) => {
48            // The reason can describe the result, so it goes to the model, not the log.
49            tracing::warn!(tool.name = %name, "tool result withheld by its screen");
50            (adk_core::result_blocked_response(name, &reason), true)
51        }
52    }
53}
54
55/// Parses a provider's tool-call arguments.
56///
57/// Empty arguments are an empty object. Anything that is not a JSON object is refused,
58/// so a malformed call is answered with an error instead of running with `{}`.
59pub(crate) fn parse_tool_arguments(
60    arguments: &str,
61) -> std::result::Result<serde_json::Value, String> {
62    if arguments.trim().is_empty() {
63        return Ok(serde_json::Value::Object(Default::default()));
64    }
65    match serde_json::from_str::<serde_json::Value>(arguments) {
66        Ok(value @ serde_json::Value::Object(_)) => Ok(value),
67        Ok(_) => Err("its arguments are not a JSON object".to_string()),
68        Err(error) => Err(format!("its arguments are not valid JSON ({error})")),
69    }
70}
71
72/// The user a runner built without [`RealtimeRunnerBuilder::tool_governance`] governs its
73/// calls for.
74const DEFAULT_REALTIME_USER: &str = "anonymous";
75
76/// The run-wide governance a runner applies to every tool call it dispatches.
77#[derive(Clone)]
78pub(crate) struct ToolGovernance {
79    pub(crate) config: adk_core::RunConfig,
80    pub(crate) scope: adk_core::ApprovalScope,
81}
82
83/// Whether a call held for a decision can be decided later: the run records it in an
84/// approval store or submits it to an approval service.
85pub(crate) fn holds_reach_an_approver(config: &adk_core::RunConfig) -> bool {
86    config.approval_store.is_some() || config.approval_service.is_some()
87}
88
89/// The answer to a call that needs a person's approval when nothing can ask anyone for it:
90/// the call is refused, in words the model can speak to the user.
91pub(crate) fn no_approver_refusal(name: &str, reason: &str) -> String {
92    tracing::warn!(
93        tool.name = %name,
94        "tool call needs approval but the run has no approval store, approval service, or \
95         confirmation handler to decide it; refused. Configure one through tool_governance"
96    );
97    format!(
98        "{reason}. Nobody can approve it in this session, so it was not run. Tell the user it \
99         needs a person's approval and do not call it again."
100    )
101}
102
103/// Internal state machine tracking the resumability status of the RealtimeRunner.
104#[derive(Debug, Clone, Default, PartialEq)]
105pub enum RunnerState {
106    /// Runner is ready to accept transport resumption immediately.
107    #[default]
108    Idle,
109    /// Model is currently generating a response; tearing down the connection would corrupt context.
110    Generating,
111    /// A tool is currently executing; teardown would cause tool loss.
112    ExecutingTool,
113    /// A context mutation was queued while the runner was busy, and must be executed once Idle.
114    ///
115    /// **Provider Context:** This state is only utilized by providers that do *not* support
116    /// native mid-flight mutability (e.g., Gemini Live), requiring a physical transport teardown
117    /// and rebuild (Phantom Reconnect). Providers like OpenAI natively apply `session.update`
118    /// frames instantly and will never enter this queued state.
119    ///
120    /// **Queue Policy:** The runner keeps only one pending resumption. If a new session update
121    /// arrives while a resumption is already pending, the previous pending resumption is replaced.
122    /// This is intentional: pending session updates represent desired end state, not an ordered
123    /// command queue. The policy is last write wins.
124    PendingResumption {
125        /// The new configuration to apply on reconnection.
126        config: Box<crate::config::RealtimeConfig>,
127        /// An optional message to inject immediately after resumption.
128        bridge_message: Option<String>,
129        /// Number of failed reconnection attempts for this mutation.
130        attempts: u8,
131    },
132}
133
134/// Handler for tool/function calls from the realtime model.
135#[async_trait]
136pub trait ToolHandler: Send + Sync {
137    /// Execute a tool call and return the result.
138    async fn execute(&self, call: &ToolCall) -> Result<serde_json::Value>;
139}
140
141/// A simple function-based tool handler.
142pub struct FnToolHandler<F>
143where
144    F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
145{
146    handler: F,
147}
148
149impl<F> FnToolHandler<F>
150where
151    F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
152{
153    /// Create a new function-based tool handler.
154    pub fn new(handler: F) -> Self {
155        Self { handler }
156    }
157}
158
159#[async_trait]
160impl<F> ToolHandler for FnToolHandler<F>
161where
162    F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
163{
164    async fn execute(&self, call: &ToolCall) -> Result<serde_json::Value> {
165        (self.handler)(call)
166    }
167}
168
169/// Async function-based tool handler.
170#[allow(dead_code)]
171pub struct AsyncToolHandler<F, Fut>
172where
173    F: Fn(ToolCall) -> Fut + Send + Sync,
174    Fut: std::future::Future<Output = Result<serde_json::Value>> + Send,
175{
176    handler: F,
177}
178
179impl<F, Fut> AsyncToolHandler<F, Fut>
180where
181    F: Fn(ToolCall) -> Fut + Send + Sync,
182    Fut: std::future::Future<Output = Result<serde_json::Value>> + Send,
183{
184    /// Create a new async tool handler.
185    pub fn new(handler: F) -> Self {
186        Self { handler }
187    }
188}
189
190/// Event handler for processing realtime events.
191#[async_trait]
192pub trait EventHandler: Send + Sync {
193    /// Called when an audio delta is received (raw PCM bytes).
194    async fn on_audio(&self, _audio: &[u8], _item_id: &str) -> Result<()> {
195        Ok(())
196    }
197
198    /// Called when a text delta is received.
199    async fn on_text(&self, _text: &str, _item_id: &str) -> Result<()> {
200        Ok(())
201    }
202
203    /// Called when a transcript delta is received.
204    async fn on_transcript(&self, _transcript: &str, _item_id: &str) -> Result<()> {
205        Ok(())
206    }
207
208    /// Called when speech is detected.
209    async fn on_speech_started(&self, _audio_start_ms: u64) -> Result<()> {
210        Ok(())
211    }
212
213    /// Called when speech ends.
214    async fn on_speech_stopped(&self, _audio_end_ms: u64) -> Result<()> {
215        Ok(())
216    }
217
218    /// Called when a response completes.
219    async fn on_response_done(&self) -> Result<()> {
220        Ok(())
221    }
222
223    /// Called on any error.
224    /// Called when the provider transport ends and [`RealtimeRunner::run`] is returning.
225    ///
226    /// The runner does **not** reconnect automatically. Reconnection is deliberate: it
227    /// requires deciding what context to replay and, on Gemini, whether a resumption token
228    /// is still valid. Without this hook `run` returned `Ok(())` on transport loss, which a
229    /// caller could not tell apart from a graceful [`RealtimeRunner::close`].
230    ///
231    /// # Example
232    ///
233    /// ```rust,ignore
234    /// async fn on_disconnect(&self) -> adk_realtime::Result<()> {
235    ///     tracing::warn!("realtime transport ended; reconnecting");
236    ///     self.reconnect.notify_one();
237    ///     Ok(())
238    /// }
239    /// ```
240    async fn on_disconnect(&self) -> Result<()> {
241        Ok(())
242    }
243
244    async fn on_error(&self, _error: &RealtimeError) -> Result<()> {
245        Ok(())
246    }
247}
248
249/// Default no-op event handler.
250#[derive(Debug, Clone, Default)]
251pub struct NoOpEventHandler;
252
253#[async_trait]
254impl EventHandler for NoOpEventHandler {}
255
256/// A tool call the run loop still has to dispatch.
257#[derive(Debug, Clone)]
258struct PendingToolCall {
259    call_id: String,
260    name: String,
261    arguments: String,
262}
263
264/// Configuration for the RealtimeRunner.
265#[derive(Clone)]
266pub struct RunnerConfig {
267    /// Whether to automatically execute tool calls.
268    pub auto_execute_tools: bool,
269    /// Whether to automatically send tool responses.
270    pub auto_respond_tools: bool,
271    /// Maximum concurrent tool executions.
272    pub max_concurrent_tools: usize,
273}
274
275impl Default for RunnerConfig {
276    fn default() -> Self {
277        Self { auto_execute_tools: true, auto_respond_tools: true, max_concurrent_tools: 4 }
278    }
279}
280
281/// Builder for RealtimeRunner.
282pub struct RealtimeRunnerBuilder {
283    model: Option<BoxedModel>,
284    config: RealtimeConfig,
285    runner_config: RunnerConfig,
286    tools: HashMap<String, (ToolDefinition, Arc<dyn ToolHandler>)>,
287    /// The first name registered twice; `build` rejects it.
288    duplicate_tool: Option<String>,
289    event_handler: Option<Arc<dyn EventHandler>>,
290    governance: Option<ToolGovernance>,
291    control: Option<adk_core::GovernanceControl>,
292    confirmation: adk_core::ToolConfirmationPolicy,
293    tool_timeout: std::time::Duration,
294    tool_result_screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
295    expose_tool_error_messages: bool,
296    pricing: Option<RealtimePricing>,
297    agent_name: String,
298}
299
300impl Default for RealtimeRunnerBuilder {
301    fn default() -> Self {
302        Self::new()
303    }
304}
305
306impl RealtimeRunnerBuilder {
307    /// Create a new builder.
308    pub fn new() -> Self {
309        Self {
310            model: None,
311            config: RealtimeConfig::default(),
312            runner_config: RunnerConfig::default(),
313            tools: HashMap::new(),
314            duplicate_tool: None,
315            event_handler: None,
316            governance: None,
317            control: None,
318            confirmation: adk_core::ToolConfirmationPolicy::Never,
319            tool_timeout: DEFAULT_REALTIME_TOOL_TIMEOUT,
320            tool_result_screen: None,
321            expose_tool_error_messages: false,
322            pricing: None,
323            agent_name: DEFAULT_REALTIME_AGENT_NAME.to_string(),
324        }
325    }
326
327    /// Names the agent every tool call is governed and metered under: the gate's agent
328    /// name, the acting agent of each call's fingerprint and audit record, and the agent in
329    /// the spend key. Defaults to [`DEFAULT_REALTIME_AGENT_NAME`]. A surface that runs an
330    /// existing agent's tools over a realtime session sets that agent's name, so the
331    /// agent's tool policy recognises its own tools (spec 3.1 §7.17).
332    pub fn agent_name(mut self, name: impl Into<String>) -> Self {
333        self.agent_name = name.into();
334        self
335    }
336
337    /// Prices each response's reported usage, so the cost committed in the run's spend
338    /// ledger is the usage's price rather than the run's per-call estimate. Metering needs
339    /// [`tool_governance`](Self::tool_governance) with a `spend_ledger`.
340    ///
341    /// # Example
342    ///
343    /// ```rust,ignore
344    /// use adk_realtime::metering::RealtimePricing;
345    ///
346    /// let runner = RealtimeRunner::builder()
347    ///     .model(model)
348    ///     .tool_governance(config, scope)
349    ///     .realtime_pricing(RealtimePricing {
350    ///         input_audio_micro_usd_per_million: 32_000_000,
351    ///         output_audio_micro_usd_per_million: 64_000_000,
352    ///         ..RealtimePricing::default()
353    ///     })
354    ///     .build()?;
355    /// ```
356    pub fn realtime_pricing(mut self, pricing: RealtimePricing) -> Self {
357        self.pricing = Some(pricing);
358        self
359    }
360
361    /// Governs every tool call this runner dispatches with `config`, under `scope`.
362    ///
363    /// The config's `tool_policy`, `governance` kill switches, confirmation handler,
364    /// approvals, and approval store apply exactly as they do to an agent run, through
365    /// [`adk_core::authorize_tool_call`]. A call held for confirmation is answered with an
366    /// error and recorded in the approval store under `scope`. A frozen kill switch ends
367    /// [`run`](RealtimeRunner::run) with an error.
368    ///
369    /// Without it, every call still takes the governed path, under `RunConfig::default()`
370    /// for the user `anonymous` in app `realtime`: no tool policy, so a call runs unless the
371    /// runner's kill switch ([`RealtimeRunner::governance`]) is frozen or the call needs
372    /// confirmation ([`require_tool_confirmation`](Self::require_tool_confirmation)), which
373    /// nobody can then give, so the call is refused.
374    ///
375    /// # Example
376    ///
377    /// ```rust,ignore
378    /// use adk_core::{ApprovalScope, DeclarativePolicy, RunConfig};
379    ///
380    /// let runner = RealtimeRunner::builder()
381    ///     .model(model)
382    ///     .tool_governance(
383    ///         RunConfig::builder()
384    ///             .tool_policy(Arc::new(DeclarativePolicy::builder().allow("get_weather").build()))
385    ///             .build(),
386    ///         ApprovalScope::new("voice", "user-1", "call-42"),
387    ///     )
388    ///     .build()?;
389    /// ```
390    pub fn tool_governance(
391        mut self,
392        config: adk_core::RunConfig,
393        scope: adk_core::ApprovalScope,
394    ) -> Self {
395        self.governance = Some(ToolGovernance { config, scope });
396        self
397    }
398
399    /// Attaches `control` as this runner's kill switch, so one control freezes this runner
400    /// together with the others it is attached to, as `Runner::builder().governance(control)`
401    /// does. Without it the runner creates its own; either way
402    /// [`RealtimeRunner::governance`] returns it, and every tool call is checked against it
403    /// and against the controls of the [`tool_governance`](Self::tool_governance) config.
404    ///
405    /// # Example
406    ///
407    /// ```rust
408    /// use adk_core::GovernanceControl;
409    /// use adk_realtime::RealtimeRunner;
410    /// use adk_realtime::model::BoxedModel;
411    ///
412    /// fn build(model: BoxedModel, control: GovernanceControl) -> adk_realtime::Result<RealtimeRunner> {
413    ///     RealtimeRunner::builder().model(model).governance(control).build()
414    /// }
415    /// ```
416    pub fn governance(mut self, control: adk_core::GovernanceControl) -> Self {
417        self.control = Some(control);
418        self
419    }
420
421    /// Sets which tools need a person's approval before they run, as
422    /// `LlmAgentBuilder::tool_confirmation_policy` does. A call that needs one is decided by
423    /// the governance config's confirmation handler, approvals, or approval store; with none
424    /// of them it is refused rather than run.
425    pub fn tool_confirmation_policy(mut self, policy: adk_core::ToolConfirmationPolicy) -> Self {
426        self.confirmation = policy;
427        self
428    }
429
430    /// Requires a person's approval before `tool_name` runs. See
431    /// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
432    ///
433    /// # Example
434    ///
435    /// ```rust
436    /// use adk_realtime::config::ToolDefinition;
437    /// use adk_realtime::model::BoxedModel;
438    /// use adk_realtime::RealtimeRunner;
439    ///
440    /// fn build(model: BoxedModel) -> adk_realtime::Result<RealtimeRunner> {
441    ///     RealtimeRunner::builder()
442    ///         .model(model)
443    ///         .tool_fn(ToolDefinition::new("refund"), |_call| Ok(serde_json::json!({ "ok": true })))
444    ///         .require_tool_confirmation("refund")
445    ///         .build()
446    /// }
447    /// ```
448    pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
449        self.confirmation = self.confirmation.with_tool(tool_name);
450        self
451    }
452
453    /// Requires a person's approval before every tool call. See
454    /// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
455    pub fn require_tool_confirmation_for_all(mut self) -> Self {
456        self.confirmation = adk_core::ToolConfirmationPolicy::Always;
457        self
458    }
459
460    /// Sets how long a tool may run before its call is answered with a timeout error.
461    /// Defaults to [`DEFAULT_REALTIME_TOOL_TIMEOUT`].
462    pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
463        self.tool_timeout = timeout;
464        self
465    }
466
467    /// Screens every tool result before it is sent to the model.
468    ///
469    /// The screen sees each handler's result, or its error response, before
470    /// `function_call_output` is sent. A result the screen rewrites is sent rewritten; a result it
471    /// withholds, or that it cannot decide on (`Err`), is replaced by
472    /// [`result_blocked_response`](adk_core::result_blocked_response), so the runner fails
473    /// closed. `adk-guardrail`'s `ToolGuardrailSet` is a screen.
474    ///
475    /// # Example
476    ///
477    /// ```rust,ignore
478    /// use adk_guardrail::{PiiRedactor, ResultTextGuardrail, ToolGuardrailSet};
479    ///
480    /// let runner = RealtimeRunner::builder()
481    ///     .model(model)
482    ///     .tool_fn(ToolDefinition::new("lookup_order"), lookup_order)
483    ///     .tool_result_screen(Arc::new(
484    ///         ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new())),
485    ///     ))
486    ///     .build()?;
487    /// ```
488    pub fn tool_result_screen(mut self, screen: Arc<dyn adk_core::ToolResultScreen>) -> Self {
489        self.tool_result_screen = Some(screen);
490        self
491    }
492
493    /// Sends the full message of a handler's error to the model.
494    ///
495    /// By default a handler that fails is answered with `tool '<name>' failed` only, because
496    /// the message can quote credentials, internal hosts, or upstream bodies, and the output is
497    /// sent to the provider and can be spoken to the user. Timeouts and policy refusals keep
498    /// their message.
499    pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
500        self.expose_tool_error_messages = expose;
501        self
502    }
503
504    /// Set the realtime model.
505    pub fn model(mut self, model: BoxedModel) -> Self {
506        self.model = Some(model);
507        self
508    }
509
510    /// Set the session configuration.
511    pub fn config(mut self, config: RealtimeConfig) -> Self {
512        self.config = config;
513        self
514    }
515
516    /// Set the runner configuration.
517    pub fn runner_config(mut self, config: RunnerConfig) -> Self {
518        self.runner_config = config;
519        self
520    }
521
522    /// Set the system instruction.
523    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
524        self.config.instruction = Some(instruction.into());
525        self
526    }
527
528    /// Set the voice.
529    pub fn voice(mut self, voice: impl Into<String>) -> Self {
530        self.config.voice = Some(voice.into());
531        self
532    }
533
534    /// Register a tool with its handler.
535    ///
536    /// Each tool needs a name of its own: [`build`](Self::build) fails when two
537    /// share one.
538    pub fn tool(self, definition: ToolDefinition, handler: impl ToolHandler + 'static) -> Self {
539        self.tool_arc(definition, Arc::new(handler))
540    }
541
542    /// Register a tool with a sync function handler.
543    pub fn tool_fn<F>(self, definition: ToolDefinition, handler: F) -> Self
544    where
545        F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync + 'static,
546    {
547        self.tool(definition, FnToolHandler::new(handler))
548    }
549
550    /// Register a tool with an `Arc<dyn ToolHandler>` directly.
551    ///
552    /// This is useful when you already have a shared handler and want to avoid
553    /// an extra `Arc` wrapping that the `tool()` method would perform.
554    pub fn tool_arc(mut self, definition: ToolDefinition, handler: Arc<dyn ToolHandler>) -> Self {
555        let name = definition.name.clone();
556        if self.tools.insert(name.clone(), (definition, handler)).is_some() {
557            self.duplicate_tool.get_or_insert(name);
558        }
559        self
560    }
561
562    /// Set the event handler.
563    pub fn event_handler(mut self, handler: impl EventHandler + 'static) -> Self {
564        self.event_handler = Some(Arc::new(handler));
565        self
566    }
567
568    /// Set the event handler from an `Arc<dyn EventHandler>` directly.
569    ///
570    /// This is useful when you already have a shared handler and want to avoid
571    /// an extra `Arc` wrapping that the `event_handler()` method would perform.
572    pub fn event_handler_arc(mut self, handler: Arc<dyn EventHandler>) -> Self {
573        self.event_handler = Some(handler);
574        self
575    }
576
577    /// Build the runner (does not connect yet).
578    ///
579    /// # Errors
580    ///
581    /// Returns a config error when no model was set or when two tools were
582    /// registered under one name.
583    pub fn build(self) -> Result<RealtimeRunner> {
584        let model = self.model.ok_or_else(|| RealtimeError::config("Model is required"))?;
585        if let Some(name) = self.duplicate_tool {
586            return Err(RealtimeError::config(format!(
587                "two tools are registered as '{name}'; the model calls tools by name, so only \
588                 one could ever run. Rename one of them or register it once."
589            )));
590        }
591
592        // Add tool definitions to config
593        let mut config = self.config;
594        if !self.tools.is_empty() {
595            let tool_defs: Vec<ToolDefinition> =
596                self.tools.values().map(|(def, _)| def.clone()).collect();
597            config.tools = Some(tool_defs);
598        }
599
600        let max_concurrent_tools = self.runner_config.max_concurrent_tools.max(1);
601
602        // Every call takes the governed path; without a configuration of its own the runner
603        // governs under the defaults, as an agent under a default `Runner` is governed.
604        let mut governance = self.governance.unwrap_or_else(|| ToolGovernance {
605            config: adk_core::RunConfig::default(),
606            scope: adk_core::ApprovalScope::new(
607                DEFAULT_REALTIME_AGENT_NAME,
608                DEFAULT_REALTIME_USER,
609                format!("realtime-{}", uuid::Uuid::new_v4().simple()),
610            ),
611        });
612        let control = self.control.unwrap_or_default();
613        if !governance.config.governance.iter().any(|existing| existing.same_as(&control)) {
614            governance.config.governance.push(control.clone());
615        }
616
617        // Every response is metered in the run's spend ledger, as `LlmAgent` meters a call.
618        let meter = ResponseMeter::for_run(
619            &governance.config,
620            &governance.scope.app_name,
621            &self.agent_name,
622            model.model_id(),
623            self.pricing,
624        );
625
626        Ok(RealtimeRunner {
627            model,
628            config: Arc::new(RwLock::new(config)),
629            runner_config: self.runner_config,
630            tools: self.tools,
631            event_handler: self.event_handler.unwrap_or_else(|| Arc::new(NoOpEventHandler)),
632            session: Arc::new(RwLock::new(None)),
633            state: Arc::new(RwLock::new(RunnerState::Idle)),
634            pending_tool_response: AtomicBool::new(false),
635            tool_permits: Arc::new(tokio::sync::Semaphore::new(max_concurrent_tools)),
636            outstanding_tools: Arc::new(AtomicUsize::new(0)),
637            response_closed_awaiting_tools: Arc::new(AtomicBool::new(false)),
638            governance,
639            control,
640            confirmation: self.confirmation,
641            tool_timeout: self.tool_timeout,
642            tool_result_screen: self.tool_result_screen,
643            expose_tool_error_messages: self.expose_tool_error_messages,
644            meter,
645            agent_name: self.agent_name,
646        })
647    }
648}
649
650/// A runner that manages a realtime session with tool execution.
651///
652/// RealtimeRunner provides a high-level interface for:
653/// - Connecting to realtime providers
654/// - Automatically executing tool calls
655/// - Routing events to handlers
656/// - Managing the session lifecycle
657///
658/// # Example
659///
660/// ```rust,ignore
661/// use adk_realtime::{RealtimeRunner, RealtimeConfig, ToolDefinition};
662/// use adk_realtime::openai::OpenAIRealtimeModel;
663///
664/// #[tokio::main]
665/// async fn main() -> Result<()> {
666///     let model = OpenAIRealtimeModel::new(api_key, "gpt-realtime-2.1");
667///
668///     let runner = RealtimeRunner::builder()
669///         .model(Box::new(model))
670///         .instruction("You are a helpful voice assistant.")
671///         .voice("alloy")
672///         .tool_fn(
673///             ToolDefinition::new("get_weather")
674///                 .with_description("Get weather for a location"),
675///             |call| {
676///                 Ok(serde_json::json!({"temperature": 72, "condition": "sunny"}))
677///             }
678///         )
679///         .build()?;
680///
681///     runner.connect().await?;
682///     runner.run().await?;
683///
684///     Ok(())
685/// }
686/// ```
687pub struct RealtimeRunner {
688    model: BoxedModel,
689    config: Arc<RwLock<RealtimeConfig>>,
690    runner_config: RunnerConfig,
691    tools: HashMap<String, (ToolDefinition, Arc<dyn ToolHandler>)>,
692    event_handler: Arc<dyn EventHandler>,
693    session: Arc<RwLock<Option<Arc<dyn crate::session::RealtimeSession>>>>,
694    state: Arc<RwLock<RunnerState>>,
695    /// Set when tool output(s) have been sent for the in-flight response and a
696    /// single follow-up `create_response` is owed once that response finishes.
697    pending_tool_response: AtomicBool,
698    /// Bounds how many tool handlers run at once, from
699    /// [`RunnerConfig::max_concurrent_tools`].
700    tool_permits: Arc<tokio::sync::Semaphore>,
701    /// Tool calls dispatched for the current response and not yet finished.
702    outstanding_tools: Arc<AtomicUsize>,
703    /// Set when the dispatching response closed while tool calls were still running, so
704    /// the follow-up `create_response` is owed by whichever tool finishes last.
705    response_closed_awaiting_tools: Arc<AtomicBool>,
706    /// Policy, kill switches, and confirmation applied to every dispatched call.
707    governance: ToolGovernance,
708    /// The runner's own kill switch, also among `governance.config.governance`.
709    control: adk_core::GovernanceControl,
710    /// The tools that need a person's approval before they run.
711    confirmation: adk_core::ToolConfirmationPolicy,
712    /// How long one tool call may run.
713    tool_timeout: std::time::Duration,
714    /// Screens every tool result before it is sent to the model.
715    tool_result_screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
716    /// Whether handler error messages reach the model.
717    expose_tool_error_messages: bool,
718    /// Meters each response in the run's spend ledger, when the governance has one.
719    meter: Option<ResponseMeter>,
720    /// The agent every tool call is governed and metered under.
721    agent_name: String,
722}
723
724impl RealtimeRunner {
725    /// Helper to safely acquire a cloned Arc of the current session, dropping the lock.
726    async fn session_handle(&self) -> Result<Arc<dyn crate::session::RealtimeSession>> {
727        let guard = self.session.read().await;
728        guard.as_ref().cloned().ok_or_else(|| RealtimeError::connection("Not connected"))
729    }
730
731    /// Create a new builder.
732    pub fn builder() -> RealtimeRunnerBuilder {
733        RealtimeRunnerBuilder::new()
734    }
735
736    /// The runner's kill switch: the control passed to
737    /// [`RealtimeRunnerBuilder::governance`], or the one the runner created. While it is
738    /// frozen no tool call runs, and the dispatch, and so [`run`](Self::run), ends with the
739    /// `governance.frozen` error.
740    ///
741    /// # Example
742    ///
743    /// ```rust
744    /// use adk_realtime::RealtimeRunner;
745    ///
746    /// fn stop_all_tools(runner: &RealtimeRunner) {
747    ///     runner.governance().freeze("incident 4012");
748    /// }
749    /// ```
750    pub fn governance(&self) -> &adk_core::GovernanceControl {
751        &self.control
752    }
753
754    /// The run config every tool call is governed under: the config passed to
755    /// [`RealtimeRunnerBuilder::tool_governance`], or `RunConfig::default()`, with the
756    /// runner's kill switch among its `governance` controls.
757    pub fn run_config(&self) -> &adk_core::RunConfig {
758        &self.governance.config
759    }
760
761    /// Connect to the realtime provider.
762    pub async fn connect(&self) -> Result<()> {
763        let config = self.config.read().await.clone();
764        let session = self.model.connect(config).await?;
765        let mut guard = self.session.write().await;
766        *guard = Some(session.into());
767        Ok(())
768    }
769
770    /// Check if currently connected.
771    pub async fn is_connected(&self) -> bool {
772        let guard = self.session.read().await;
773        guard.as_ref().map(|s| s.is_connected()).unwrap_or(false)
774    }
775
776    /// Get the session ID if connected.
777    pub async fn session_id(&self) -> Option<String> {
778        let guard = self.session.read().await;
779        guard.as_ref().map(|s| s.session_id().to_string())
780    }
781
782    /// Send a client event directly to the session.
783    ///
784    /// This method intercepts internal control-plane events (like `UpdateSession`) to route
785    /// them through the provider-agnostic orchestration layer instead of forwarding raw JSON
786    /// to the underlying WebSocket transport. This guarantees that `adk-realtime` never leaks
787    /// invalid event payloads to providers (e.g., OpenAI or Gemini) and universally bridges
788    /// the Cognitive Handoff mechanics transparently.
789    pub async fn send_client_event(&self, event: crate::events::ClientEvent) -> Result<()> {
790        match event {
791            crate::events::ClientEvent::UpdateSession { instructions, tools } => {
792                let update_config = SessionUpdateConfig(crate::config::RealtimeConfig {
793                    instruction: instructions,
794                    tools,
795                    ..Default::default()
796                });
797                self.update_session(update_config).await
798            }
799            other => {
800                let session = self.session_handle().await?;
801                session.send_event(other).await
802            }
803        }
804    }
805
806    /// Internal helper to merge a `SessionUpdateConfig` delta into the canonical `RealtimeConfig` state.
807    ///
808    /// **Why this exists**: The `RealtimeRunner` must maintain an absolute, single source of truth
809    /// for its configuration (`self.config`). Orchestrators fire `SessionUpdateConfig`s as sparse
810    /// partial deltas (intents to hot-swap instructions or tools mid-flight). By accumulating
811    /// these sparse updates into the single `base` config, any subsequent "Phantom Reconnect"
812    /// (e.g., due to a Gemini domain shift or an unexpected network drop) natively inherits all
813    /// prior hot-swaps alongside the immutable transport parameters (like sample rates) defined at startup.
814    ///
815    /// Note: This is intentionally narrow and specifically scoped to merge only
816    /// hot-swappable cognitive fields (instruction, tools, voice, temperature, extra).
817    /// Transport-level attributes like sample rates and audio formats are not dynamically swappable.
818    fn merge_config(base: &mut RealtimeConfig, update: &SessionUpdateConfig) {
819        if let Some(instruction) = &update.0.instruction {
820            base.instruction = Some(instruction.clone());
821        }
822        if let Some(tools) = &update.0.tools {
823            base.tools = Some(tools.clone());
824        }
825        if let Some(voice) = &update.0.voice {
826            base.voice = Some(voice.clone());
827        }
828        if let Some(temp) = update.0.temperature {
829            base.temperature = Some(temp);
830        }
831        if let Some(extra) = &update.0.extra {
832            base.extra = Some(extra.clone());
833        }
834    }
835
836    /// Update the session configuration.
837    ///
838    /// Delegates to [`Self::update_session_with_bridge`] with no bridge message.
839    ///
840    /// # Example
841    ///
842    /// ```rust,ignore
843    /// use adk_realtime::config::{SessionUpdateConfig, RealtimeConfig};
844    ///
845    /// async fn example(runner: &adk_realtime::RealtimeRunner) {
846    ///     let update = SessionUpdateConfig(
847    ///         RealtimeConfig::default().with_instruction("You are now a pirate.")
848    ///     );
849    ///     runner.update_session(update).await.unwrap();
850    /// }
851    /// ```
852    pub async fn update_session(&self, config: SessionUpdateConfig) -> Result<()> {
853        self.update_session_with_bridge(config, None).await
854    }
855
856    /// Update the session configuration, optionally injecting a bridge message if
857    /// a transport resumption (Phantom Reconnect) occurs.
858    ///
859    /// The RealtimeRunner will attempt to mutate the session natively if the underlying
860    /// API supports it (e.g., OpenAI). If it does not (e.g., Gemini), the Runner will
861    /// queue a transport resumption, executing it only when the session
862    /// is in a resumable state (Idle) to prevent data corruption.
863    ///
864    /// The runner keeps only one pending resumption. If a new session update arrives while
865    /// a resumption is already pending, the previous pending resumption is replaced. This is
866    /// intentional: pending session updates represent desired end state, not an ordered command queue.
867    /// The policy is last write wins.
868    pub async fn update_session_with_bridge(
869        &self,
870        config: SessionUpdateConfig,
871        bridge_message: Option<String>,
872    ) -> Result<()> {
873        // 1. Merge the incoming delta into the runner's canonical, persisted configuration.
874        // This ensures that any future reconnects (e.g., due to network drops) naturally
875        // inherit this latest state.
876        let mut full_config = self.config.write().await;
877        Self::merge_config(&mut full_config, &config);
878
879        let cloned_config = full_config.clone();
880        drop(full_config); // Free the write lock early to avoid deadlocks.
881
882        // 2. Safely obtain a cloned handle of the active session.
883        let session = self.session_handle().await?;
884
885        // 3. Delegate the mutation attempt to the provider-specific adapter.
886        match session.mutate_context(cloned_config).await? {
887            // PATH A: Native Mutability (e.g., OpenAI)
888            // The provider natively updated the context over the active WebSocket.
889            ContextMutationOutcome::Applied => {
890                tracing::info!("Context mutated natively mid-flight.");
891
892                // Since the transport wasn't dropped, we can inject the bridge message
893                // immediately as a standard user message to update the model's short-term memory.
894                if let Some(msg) = bridge_message {
895                    let event = crate::events::ClientEvent::Message {
896                        role: "user".to_string(),
897                        parts: vec![adk_core::types::Part::Text { text: msg }],
898                    };
899                    session.send_event(event).await?;
900                }
901                Ok(())
902            }
903
904            // PATH B: Rigid Initialization (e.g., Gemini)
905            // The provider requires us to tear down the WebSocket and establish a new one (Phantom Reconnect).
906            ContextMutationOutcome::RequiresResumption(new_config) => {
907                drop(session); // CRITICAL: Drop the cloned handle before attempting state mutation.
908
909                // 4. Check the Runner's internal state machine to ensure it is safe to tear down the socket.
910                let mut state_guard = self.state.write().await;
911
912                if *state_guard == RunnerState::Idle {
913                    // Safe to reconnect: The model is neither generating audio nor executing a tool.
914                    drop(state_guard); // Free state lock before the heavy async network operation.
915                    tracing::info!("Runner is idle. Executing resumption immediately.");
916
917                    if let Err(e) =
918                        self.execute_resumption((*new_config).clone(), bridge_message.clone()).await
919                    {
920                        tracing::error!("Immediate resumption failed: {}. Queueing for retry.", e);
921                        // If the reconnect fails (e.g., transient network issue), we must not lose the mutation intent.
922                        // We push it back into the queue for the background loop to retry.
923                        let mut fallback_state = self.state.write().await;
924                        *fallback_state = RunnerState::PendingResumption {
925                            config: Box::new(*new_config),
926                            bridge_message,
927                            attempts: 1,
928                        };
929                        return Err(e);
930                    }
931                } else {
932                    // Unsafe to reconnect: Tearing down the socket now would corrupt the in-flight context.
933                    // We must queue the mutation. The event loop will execute it once it returns to Idle.
934                    if let RunnerState::PendingResumption { .. } = *state_guard {
935                        tracing::warn!(
936                            "Runner already had a pending resumption. Overwriting with last-write-wins policy."
937                        );
938                    } else {
939                        tracing::info!("Runner is busy ({:?}). Queueing resumption.", *state_guard);
940                    }
941
942                    // Queue the intent using a last-write-wins policy.
943                    *state_guard = RunnerState::PendingResumption {
944                        config: new_config,
945                        bridge_message,
946                        attempts: 0,
947                    };
948                }
949                Ok(())
950            }
951        }
952    }
953
954    /// Internal helper to execute a transport resumption (teardown and rebuild).
955    async fn execute_resumption(
956        &self,
957        new_config: crate::config::RealtimeConfig,
958        bridge_message: Option<String>,
959    ) -> Result<()> {
960        tracing::warn!("Executing transport resumption with new configuration.");
961
962        // 1. Extract the old session safely under the write lock.
963        let old_session = {
964            let mut write_guard = self.session.write().await;
965            write_guard.take()
966        };
967
968        // 2. Explicitly tear down the old WebSocket connection to release upstream resources.
969        // Do this WITHOUT holding the lock across `.await`.
970        if let Some(session) = old_session
971            && let Err(e) = session.close().await
972        {
973            tracing::warn!("Failed to cleanly close old session during resumption: {}", e);
974        }
975
976        // 3. Establish a brand new connection using the provider-agnostic factory interface.
977        // If the provider supports resumption natively (like Gemini), the `new_config`
978        // payload already contains the cached `resumeToken`.
979        let new_session = self.model.connect(new_config).await?;
980
981        // 4. Overwrite the active session pointer with the newly connected transport.
982        {
983            let mut write_guard = self.session.write().await;
984            *write_guard = Some(new_session.into());
985        }
986
987        // 5. If the orchestrator provided a bridge message (e.g. to explain the domain shift),
988        // safely inject it into the new connection's context window.
989        if let Some(msg) = bridge_message {
990            self.inject_bridge_message(msg).await?;
991        }
992
993        tracing::info!("Resumption complete. New transport established.");
994        Ok(())
995    }
996
997    /// Internal helper to safely inject a bridge message directly into the active session.
998    ///
999    /// This intentionally bypasses the `send_client_event` router to avoid `E0733`
1000    /// (un-Boxed async recursion) where `send_client_event` -> `update_session` ->
1001    /// `execute_resumption` -> `send_client_event` creates an infinite compiler loop.
1002    async fn inject_bridge_message(&self, msg: String) -> Result<()> {
1003        tracing::info!("Injecting bridge message post-resumption.");
1004        let event = crate::events::ClientEvent::Message {
1005            role: "user".to_string(),
1006            parts: vec![adk_core::types::Part::Text { text: msg }],
1007        };
1008        let session = self.session_handle().await?;
1009        session.send_event(event).await
1010    }
1011
1012    /// Send a typed raw-audio chunk to the session.
1013    ///
1014    /// This preserves the audio format at the provider boundary and lets the
1015    /// provider choose its native encoding path. Prefer this method when the
1016    /// caller already owns raw audio bytes.
1017    pub async fn send_audio_chunk(&self, audio: &crate::audio::AudioChunk) -> Result<()> {
1018        let session = self.session_handle().await?;
1019        session.send_audio(audio).await
1020    }
1021
1022    /// Send base64-encoded audio to the session.
1023    ///
1024    /// This compatibility entry point is useful when the caller already has a
1025    /// base64 payload. Raw-audio callers should use
1026    /// [`send_audio_chunk`](Self::send_audio_chunk) to avoid forcing an encoding
1027    /// decision at the provider-neutral runner boundary.
1028    pub async fn send_audio(&self, audio_base64: &str) -> Result<()> {
1029        let session = self.session_handle().await?;
1030        session.send_audio_base64(audio_base64).await
1031    }
1032
1033    /// Send text to the session.
1034    pub async fn send_text(&self, text: &str) -> Result<()> {
1035        let session = self.session_handle().await?;
1036        session.send_text(text).await
1037    }
1038
1039    /// Send a base64-encoded video/image frame (e.g. `image/jpeg`) for
1040    /// multimodal input, where the provider supports it (Gemini Live; OpenAI as
1041    /// an image-in-context item).
1042    pub async fn send_video_frame(&self, mime_type: &str, data_base64: &str) -> Result<()> {
1043        let session = self.session_handle().await?;
1044        session.send_video_frame(mime_type, data_base64).await
1045    }
1046
1047    /// Commit the audio buffer (for manual VAD mode).
1048    pub async fn commit_audio(&self) -> Result<()> {
1049        let session = self.session_handle().await?;
1050        session.commit_audio().await
1051    }
1052
1053    /// Trigger a response from the model.
1054    pub async fn create_response(&self) -> Result<()> {
1055        let session = self.session_handle().await?;
1056        session.create_response().await
1057    }
1058
1059    /// Interrupt the current response.
1060    pub async fn interrupt(&self) -> Result<()> {
1061        let session = self.session_handle().await?;
1062        session.interrupt().await
1063    }
1064
1065    /// Get the next raw event from the session.
1066    ///
1067    /// # Example
1068    ///
1069    /// ```rust,ignore
1070    /// use adk_realtime::events::ServerEvent;
1071    /// use tracing::{info, error};
1072    ///
1073    /// async fn process_events(runner: &adk_realtime::RealtimeRunner) {
1074    ///     while let Some(event) = runner.next_event().await {
1075    ///         match event {
1076    ///             Ok(ServerEvent::SpeechStarted { .. }) => info!("User is speaking"),
1077    ///             Ok(_) => info!("Received other event"),
1078    ///             Err(e) => error!("Error: {e}"),
1079    ///         }
1080    ///     }
1081    /// }
1082    /// ```
1083    /// Why the provider ended the stream, once [`Self::next_event`] has returned
1084    /// `None`.
1085    ///
1086    /// Callers that poll `next_event` never see the runner's `on_disconnect`
1087    /// dispatch, so without this a provider that deliberately closed an idle
1088    /// session is indistinguishable from a dropped socket — and both get
1089    /// recorded as the same generic stream failure.
1090    pub async fn disconnect_reason(&self) -> Option<crate::session::DisconnectReason> {
1091        self.session_handle().await.ok().and_then(|session| session.disconnect_reason())
1092    }
1093
1094    pub async fn next_event(&self) -> Option<Result<ServerEvent>> {
1095        let session = match self.session_handle().await {
1096            Ok(session) => session,
1097            Err(_) => {
1098                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1099                return None;
1100            }
1101        };
1102
1103        // Some sessions might yield inside next_event, but just in case, yield here too
1104        tokio::task::yield_now().await;
1105        let event = session.next_event().await?;
1106        if let Ok(event) = &event
1107            && let Err(error) = self.observe_event(event).await
1108        {
1109            return Some(Err(error));
1110        }
1111        Some(event)
1112    }
1113
1114    /// Meters `event` when it starts or ends a response.
1115    ///
1116    /// Returns the usage a `ResponseDone` reported, priced with
1117    /// [`realtime_pricing`](RealtimeRunnerBuilder::realtime_pricing).
1118    ///
1119    /// # Errors
1120    ///
1121    /// [`RealtimeError::SpendRefused`] when the run's spend ledger refuses the response's
1122    /// hold; the caller ends the session.
1123    pub(crate) async fn observe_event(
1124        &self,
1125        event: &ServerEvent,
1126    ) -> Result<Option<adk_core::UsageMetadata>> {
1127        let Some(meter) = &self.meter else {
1128            return Ok(None);
1129        };
1130        match event {
1131            ServerEvent::ResponseCreated { .. } => {
1132                meter.begin_response().await?;
1133                Ok(None)
1134            }
1135            ServerEvent::ResponseDone { response, .. } => meter.end_response(response).await,
1136            _ => Ok(None),
1137        }
1138    }
1139
1140    /// The agent every tool call is governed and metered under.
1141    #[cfg(feature = "integration")]
1142    pub(crate) fn agent_name(&self) -> &str {
1143        &self.agent_name
1144    }
1145
1146    /// The approval scope held calls are recorded under.
1147    #[cfg(feature = "integration")]
1148    pub(crate) fn approval_scope(&self) -> &adk_core::ApprovalScope {
1149        &self.governance.scope
1150    }
1151
1152    /// Counts a tool dispatch the caller runs outside [`run`](Self::run), so the follow-up
1153    /// response waits for it; pair with [`end_dispatch`](Self::end_dispatch).
1154    #[cfg(feature = "integration")]
1155    pub(crate) fn begin_dispatch(&self) {
1156        self.outstanding_tools.fetch_add(1, Ordering::AcqRel);
1157    }
1158
1159    /// Marks a dispatch counted by [`begin_dispatch`](Self::begin_dispatch) as finished.
1160    /// Returns `true` when the dispatching response closed meanwhile, so the caller owes
1161    /// the follow-up response ([`respond_after_tools`](Self::respond_after_tools)).
1162    #[cfg(feature = "integration")]
1163    pub(crate) fn end_dispatch(&self) -> bool {
1164        self.outstanding_tools.fetch_sub(1, Ordering::AcqRel) == 1
1165            && self.response_closed_awaiting_tools.swap(false, Ordering::AcqRel)
1166    }
1167
1168    /// Send a tool response to the session.
1169    ///
1170    /// # Example
1171    ///
1172    /// ```rust,ignore
1173    /// use adk_realtime::events::ToolResponse;
1174    /// use serde_json::json;
1175    ///
1176    /// async fn example(runner: &adk_realtime::RealtimeRunner) {
1177    ///     let response = ToolResponse {
1178    ///         call_id: "call_123".to_string(),
1179    ///         output: json!({"temperature": 72}),
1180    ///     };
1181    ///     runner.send_tool_response(response).await.unwrap();
1182    /// }
1183    /// ```
1184    pub async fn send_tool_response(&self, response: ToolResponse) -> Result<()> {
1185        let session = self.session_handle().await?;
1186        session.send_tool_response(response).await
1187    }
1188
1189    /// Execute a tool call against the registered handlers, sending the result
1190    /// back to the model when `auto_respond_tools` is enabled.
1191    ///
1192    /// This is the same dispatch the [`run`](Self::run) loop performs for a
1193    /// `response.function_call_arguments.done` event, exposed so that callers
1194    /// driving the session manually via [`next_event`](Self::next_event) — such
1195    /// as `IntegratedRealtimeRunner` (available with the `integration` feature) —
1196    /// can execute tools without re-implementing the lookup/respond logic.
1197    pub async fn dispatch_tool_call(
1198        &self,
1199        call_id: &str,
1200        name: &str,
1201        arguments: &str,
1202    ) -> Result<()> {
1203        self.execute_tool_call(call_id, name, arguments).await
1204    }
1205
1206    /// Sends a tool result the caller produced, honouring `auto_respond_tools`.
1207    ///
1208    /// Used by the integration layer, which runs ADK tools through its own policy pipeline and
1209    /// then needs the result delivered exactly as `execute_tool_call` would deliver it: the
1210    /// output is sent now, and the single follow-up `create_response` is deferred until the
1211    /// dispatching response closes, so several parallel calls produce one response.
1212    ///
1213    /// # Example
1214    ///
1215    /// ```rust,ignore
1216    /// let result = my_policy_pipeline.run(&call).await?;
1217    /// runner.send_tool_result(&call.call_id, result).await?;
1218    /// ```
1219    pub async fn send_tool_result(&self, call_id: &str, output: serde_json::Value) -> Result<()> {
1220        if !self.runner_config.auto_respond_tools {
1221            return Ok(());
1222        }
1223
1224        if let Ok(session) = self.session_handle().await {
1225            session.send_tool_output(ToolResponse { call_id: call_id.to_string(), output }).await?;
1226            self.pending_tool_response.store(true, Ordering::Release);
1227        }
1228        Ok(())
1229    }
1230
1231    /// Run the event loop, processing events until disconnected.
1232    pub async fn run(&self) -> Result<()> {
1233        use futures::stream::{FuturesUnordered, StreamExt};
1234
1235        // Tool handlers run as futures on this set rather than inline, so reading the next
1236        // provider event never waits for a tool. `max_concurrent_tools` bounds how many
1237        // are past their permit acquisition at once.
1238        let mut running_tools = FuturesUnordered::new();
1239
1240        loop {
1241            let session = self.session_handle().await?;
1242            let old_session_id = session.session_id().to_string();
1243
1244            // With no tools in flight there is nothing to drain, and polling an empty
1245            // `FuturesUnordered` in a `select!` would spin.
1246            let event = if running_tools.is_empty() {
1247                session.next_event().await
1248            } else {
1249                tokio::select! {
1250                    biased;
1251                    Some(finished) = running_tools.next() => {
1252                        let () = finished?;
1253                        continue;
1254                    }
1255                    event = session.next_event() => event,
1256                }
1257            };
1258
1259            match event {
1260                Some(Ok(event)) => {
1261                    if let Err(error) = self.observe_event(&event).await {
1262                        self.event_handler.on_error(&error).await?;
1263                        let _ = self.close().await;
1264                        return Err(error);
1265                    }
1266                    if let Some(call) = self.handle_event(event).await? {
1267                        self.outstanding_tools.fetch_add(1, Ordering::AcqRel);
1268                        running_tools.push(self.run_tool_call(call));
1269                    }
1270                }
1271                Some(Err(e)) => {
1272                    self.event_handler.on_error(&e).await?;
1273                    return Err(e);
1274                }
1275                None => {
1276                    // Session closed or swapped out. Check if a new session was installed (e.g., during reconnect).
1277                    let current_session_id = self.session_id().await;
1278                    if let Some(id) = current_session_id
1279                        && id != old_session_id
1280                    {
1281                        // A new session handle was installed concurrently. Continue polling.
1282                        continue;
1283                    }
1284                    // A real disconnect. Let dispatched tools finish so their output and
1285                    // the follow-up response are not dropped mid-flight.
1286                    while let Some(finished) = running_tools.next().await {
1287                        finished?;
1288                    }
1289                    // Surfaced distinctly: `run` returning `Ok(())` alone cannot be told
1290                    // apart from a graceful `close`.
1291                    self.event_handler.on_disconnect().await?;
1292                    break;
1293                }
1294            }
1295        }
1296        Ok(())
1297    }
1298
1299    /// Run one dispatched tool call under the configured concurrency bound.
1300    ///
1301    /// The permit is acquired inside the future so queueing a call never blocks the event
1302    /// loop; the bound applies to execution, not to admission.
1303    async fn run_tool_call(&self, call: PendingToolCall) -> Result<()> {
1304        let permit = Arc::clone(&self.tool_permits).acquire_owned().await;
1305        let result = self.execute_tool_call(&call.call_id, &call.name, &call.arguments).await;
1306        drop(permit);
1307
1308        // The follow-up response is owed once *every* dispatched tool is in and the
1309        // dispatching response has closed, whichever happens last. Before tools ran
1310        // concurrently, ordering was implicit: `ResponseDone` could not arrive until the
1311        // inline await returned. It can now, so the last tool to finish issues it.
1312        if self.outstanding_tools.fetch_sub(1, Ordering::AcqRel) == 1
1313            && self.response_closed_awaiting_tools.swap(false, Ordering::AcqRel)
1314        {
1315            self.respond_after_tools().await?;
1316        }
1317        result
1318    }
1319
1320    /// Process a single event.
1321    async fn handle_event(&self, event: ServerEvent) -> Result<Option<PendingToolCall>> {
1322        // Track state transitions before forwarding the event
1323        match &event {
1324            ServerEvent::ResponseCreated { .. } => {
1325                let mut state = self.state.write().await;
1326                if let RunnerState::Idle = *state {
1327                    *state = RunnerState::Generating;
1328                }
1329            }
1330            ServerEvent::FunctionCallDone { .. } => {
1331                let mut state = self.state.write().await;
1332                if let RunnerState::Generating | RunnerState::Idle = *state {
1333                    *state = RunnerState::ExecutingTool;
1334                }
1335            }
1336            _ => {}
1337        }
1338
1339        match event {
1340            ServerEvent::AudioDelta { delta, item_id, .. } => {
1341                self.event_handler.on_audio(&delta, &item_id).await?;
1342            }
1343            ServerEvent::TextDelta { delta, item_id, .. } => {
1344                self.event_handler.on_text(&delta, &item_id).await?;
1345            }
1346            ServerEvent::TranscriptDelta { delta, item_id, .. } => {
1347                self.event_handler.on_transcript(&delta, &item_id).await?;
1348            }
1349            ServerEvent::SpeechStarted { audio_start_ms, .. } => {
1350                self.event_handler.on_speech_started(audio_start_ms).await?;
1351            }
1352            ServerEvent::SpeechStopped { audio_end_ms, .. } => {
1353                self.event_handler.on_speech_stopped(audio_end_ms).await?;
1354            }
1355            ServerEvent::ResponseDone { .. } => {
1356                self.event_handler.on_response_done().await?;
1357                // If this response dispatched tool call(s), send the one owed
1358                // follow-up response now that it's closed.
1359                self.respond_after_tools().await?;
1360                self.check_resumption_queue().await?;
1361            }
1362            ServerEvent::FunctionCallDone { call_id, name, arguments, .. }
1363                if self.runner_config.auto_execute_tools =>
1364            {
1365                // Returned rather than awaited: the run loop dispatches it so event
1366                // intake — audio deltas included — continues while the tool runs.
1367                return Ok(Some(PendingToolCall { call_id, name, arguments }));
1368            }
1369            ServerEvent::SessionUpdated { session, .. } => {
1370                // Check if the generic session update contains a resumption token
1371                if let Some(token) = session.get("resumeToken").and_then(|t| t.as_str()) {
1372                    tracing::info!(
1373                        "Received Gemini sessionResumption token, saving for future reconnects."
1374                    );
1375                    let mut config = self.config.write().await;
1376                    let mut extra = config.extra.clone().unwrap_or_else(|| serde_json::json!({}));
1377                    extra["resumeToken"] = serde_json::Value::String(token.to_string());
1378                    config.extra = Some(extra);
1379                }
1380            }
1381            ServerEvent::Error { error, .. } => {
1382                let err = RealtimeError::server(error.code.unwrap_or_default(), error.message);
1383                self.event_handler.on_error(&err).await?;
1384            }
1385            _ => {
1386                // Ignore other events
1387            }
1388        }
1389        Ok(None)
1390    }
1391
1392    /// Safely transitions the runner back to Idle and executes any queued resumptions.
1393    async fn check_resumption_queue(&self) -> Result<()> {
1394        // 1. Acquire the state lock to inspect the queue.
1395        let mut state = self.state.write().await;
1396
1397        // 2. Extract the pending configuration and attempt count if one exists.
1398        let pending =
1399            if let RunnerState::PendingResumption { config, bridge_message, attempts } = &*state {
1400                Some((config.clone(), bridge_message.clone(), *attempts))
1401            } else {
1402                None
1403            };
1404
1405        if let Some((config, bridge_message, attempts)) = pending {
1406            tracing::info!(
1407                "Executing queued resumption after turn completion. (Attempt {})",
1408                attempts + 1
1409            );
1410
1411            // 3. Mark the state as Idle so the background loop is unblocked.
1412            *state = RunnerState::Idle;
1413
1414            // 4. Release the state lock *before* performing the heavy async socket connection.
1415            drop(state);
1416
1417            // 5. Attempt the actual transport teardown/rebuild.
1418            if let Err(e) = self.execute_resumption((*config).clone(), bridge_message.clone()).await
1419            {
1420                tracing::error!("Resumption failed: {}.", e);
1421
1422                // 6. If the reconnect fails (e.g., transient network error), re-acquire the lock
1423                // to safely handle the retry logic without crashing the event loop.
1424                let mut fallback_state = self.state.write().await;
1425
1426                // 7. Enforce a maximum retry budget to prevent infinite "hot-looping"
1427                if attempts + 1 >= 3 {
1428                    tracing::error!(
1429                        "Maximum resumption attempts reached (3). Dropping queued mutation to prevent infinite loop."
1430                    );
1431                    *fallback_state = RunnerState::Idle;
1432                } else {
1433                    tracing::info!("Restoring pending queue state for retry.");
1434                    *fallback_state = RunnerState::PendingResumption {
1435                        config,
1436                        bridge_message,
1437                        attempts: attempts + 1,
1438                    };
1439                }
1440
1441                // 8. Do not return Err(e) here, as that would permanently kill the `run()` loop.
1442                // Instead, report the error to the downstream handler and allow the event loop to continue spinning.
1443                let _ = self.event_handler.on_error(&e).await;
1444            }
1445        } else {
1446            // No resumptions were queued; simply mark as Idle.
1447            *state = RunnerState::Idle;
1448        }
1449        Ok(())
1450    }
1451
1452    /// Runs one call through the governed path: the
1453    /// [`tool_governance`](RealtimeRunnerBuilder::tool_governance) config, or the defaults,
1454    /// with the runner's kill switch and confirmation policy.
1455    ///
1456    /// # Errors
1457    ///
1458    /// Returns [`RealtimeError::ToolError`] when a kill switch is frozen or the
1459    /// confirmation handler or approval store fails; the run ends.
1460    pub(crate) async fn authorize_tool_call(
1461        &self,
1462        mut call: adk_core::GovernedCall,
1463    ) -> Result<adk_core::ToolAuthorization> {
1464        call.requires_confirmation |= self.confirmation.requires_confirmation(&call.tool_name);
1465        let governance = &self.governance;
1466        let gate = adk_core::ToolGate::new(
1467            &governance.config,
1468            &self.agent_name,
1469            &governance.scope.session_id,
1470            governance.scope.clone(),
1471        );
1472        adk_core::authorize_tool_call(&gate, call)
1473            .await
1474            .map_err(|error| RealtimeError::ToolError(error.to_string()))
1475    }
1476
1477    /// Withdraws `request`, a call's confirmation request that will not be waited on, so no
1478    /// decision on it authorizes an identical call ([`adk_core::withdraw_held_call`]).
1479    #[cfg(feature = "integration")]
1480    pub(crate) async fn withdraw_held_call(
1481        &self,
1482        request: &adk_core::ToolConfirmationRequest,
1483    ) -> Result<()> {
1484        let governance = &self.governance;
1485        let gate = adk_core::ToolGate::new(
1486            &governance.config,
1487            &self.agent_name,
1488            &governance.scope.session_id,
1489            governance.scope.clone(),
1490        );
1491        adk_core::withdraw_held_call(&gate, request)
1492            .await
1493            .map_err(|error| RealtimeError::ToolError(error.to_string()))
1494    }
1495
1496    /// How long one tool call may run.
1497    #[cfg(feature = "integration")]
1498    pub(crate) fn tool_timeout(&self) -> std::time::Duration {
1499        self.tool_timeout
1500    }
1501
1502    /// Whether tool error messages reach the model.
1503    #[cfg(feature = "integration")]
1504    pub(crate) fn exposes_tool_error_messages(&self) -> bool {
1505        self.expose_tool_error_messages
1506    }
1507
1508    /// Runs the configured result screen, if any, on `result`, returning the result to deliver
1509    /// and whether the screen withheld it.
1510    pub(crate) async fn screen_tool_result(
1511        &self,
1512        name: &str,
1513        args: &serde_json::Value,
1514        result: serde_json::Value,
1515    ) -> (serde_json::Value, bool) {
1516        match &self.tool_result_screen {
1517            Some(screen) => screen_result(screen.as_ref(), name, args, result).await,
1518            None => (result, false),
1519        }
1520    }
1521
1522    /// Whether tool error messages may be logged: the `record_payloads` of the config passed to
1523    /// [`RealtimeRunnerBuilder::tool_governance`]. Without one, only content-free fields are.
1524    pub(crate) fn records_payloads(&self) -> bool {
1525        self.governance.config.record_payloads
1526    }
1527
1528    /// Execute a tool call and optionally send the response.
1529    async fn execute_tool_call(&self, call_id: &str, name: &str, arguments: &str) -> Result<()> {
1530        let handler = self.tools.get(name).map(|(definition, h)| (definition, h.clone()));
1531
1532        let result = match (handler, parse_tool_arguments(arguments)) {
1533            (None, _) => serde_json::json!({ "error": format!("Unknown tool: {name}") }),
1534            (Some(_), Err(reason)) => {
1535                serde_json::json!({ "error": format!("Tool '{name}' was not run: {reason}") })
1536            }
1537            (Some((definition, handler)), Ok(args)) => {
1538                let screened_args = self.tool_result_screen.as_ref().map(|_| args.clone());
1539                // Native handlers declare no read-only flag, so the policy treats them as
1540                // having side effects.
1541                let mut call = adk_core::GovernedCall::new(name, call_id, args);
1542                call.origin = Some(definition.handler_origin());
1543                let result = match self.authorize_tool_call(call).await? {
1544                    adk_core::ToolAuthorization::Execute { args, .. } => {
1545                        let call = ToolCall {
1546                            call_id: call_id.to_string(),
1547                            name: name.to_string(),
1548                            arguments: args,
1549                        };
1550                        match tokio::time::timeout(self.tool_timeout, handler.execute(&call)).await
1551                        {
1552                            Ok(Ok(value)) => value,
1553                            Ok(Err(e)) => {
1554                                // A message can quote credentials or internal hosts.
1555                                if self.records_payloads() {
1556                                    tracing::warn!(
1557                                        tool.name = %name,
1558                                        error.kind = e.kind(),
1559                                        error.message = %e,
1560                                        "realtime tool handler failed"
1561                                    );
1562                                } else {
1563                                    tracing::warn!(
1564                                        tool.name = %name,
1565                                        error.kind = e.kind(),
1566                                        "realtime tool handler failed"
1567                                    );
1568                                }
1569                                if self.expose_tool_error_messages {
1570                                    serde_json::json!({ "error": e.to_string() })
1571                                } else {
1572                                    serde_json::json!({ "error": format!("tool '{name}' failed") })
1573                                }
1574                            }
1575                            Err(_) => serde_json::json!({
1576                                "error": format!(
1577                                    "Tool '{name}' timed out after {:?}",
1578                                    self.tool_timeout
1579                                )
1580                            }),
1581                        }
1582                    }
1583                    adk_core::ToolAuthorization::Refuse { reason, .. } => {
1584                        serde_json::json!({ "error": reason })
1585                    }
1586                    // A native handler's call is not held in the session, so it waits only
1587                    // where an approval store or service can take a decision on it.
1588                    adk_core::ToolAuthorization::Pending { reason, .. } => {
1589                        if holds_reach_an_approver(&self.governance.config) {
1590                            serde_json::json!({ "error": reason })
1591                        } else {
1592                            serde_json::json!({ "error": no_approver_refusal(name, &reason) })
1593                        }
1594                    }
1595                };
1596                match screened_args {
1597                    Some(args) => self.screen_tool_result(name, &args, result).await.0,
1598                    None => result,
1599                }
1600            }
1601        };
1602
1603        if self.runner_config.auto_respond_tools {
1604            let response = ToolResponse { call_id: call_id.to_string(), output: result };
1605
1606            if let Ok(session) = self.session_handle().await {
1607                // Send the output now, but defer the response trigger: several
1608                // parallel tool calls in one response must produce a *single*
1609                // `create_response`, issued once the dispatch response finishes
1610                // (see `respond_after_tools`). Firing one per output collides
1611                // with the still-active response on OpenAI.
1612                session.send_tool_output(response).await?;
1613                self.pending_tool_response.store(true, Ordering::Release);
1614            }
1615        }
1616
1617        Ok(())
1618    }
1619
1620    /// The system instruction the next connection will use.
1621    ///
1622    /// Exposed so callers and tests can confirm what context a session was actually created
1623    /// with, rather than inferring it from log lines.
1624    pub async fn instruction(&self) -> Option<String> {
1625        self.config.read().await.instruction.clone()
1626    }
1627
1628    /// Prepends a context block to the system instruction before connecting.
1629    ///
1630    /// The integration layer uses this to carry prior conversation history and recalled memory
1631    /// into the provider session. Call it before [`RealtimeRunner::connect`]: providers read
1632    /// the instruction at session creation, so a later change needs `update_session`.
1633    ///
1634    /// # Example
1635    ///
1636    /// ```rust,ignore
1637    /// runner.prepend_instruction_context("Previously discussed: the refund policy.").await;
1638    /// runner.connect().await?;
1639    /// ```
1640    pub async fn prepend_instruction_context(&self, block: &str) {
1641        if block.is_empty() {
1642            return;
1643        }
1644
1645        let mut config = self.config.write().await;
1646        config.instruction = Some(match config.instruction.take() {
1647            Some(existing) if !existing.is_empty() => format!("{block}\n\n{existing}"),
1648            _ => block.to_string(),
1649        });
1650    }
1651
1652    /// Trigger the single follow-up response owed after a tool-dispatching turn.
1653    ///
1654    /// Call this when a response finishes (`ResponseDone`). If tool output(s)
1655    /// were sent back during that response (`auto_respond_tools`), the model now
1656    /// needs one `create_response` to speak its answer — issued here, after the
1657    /// dispatch response is closed and every parallel tool output is in, rather
1658    /// than once per tool call. Gemini's `create_response` is a no-op, so this is
1659    /// safely uniform across providers. No-op when nothing is pending.
1660    pub async fn respond_after_tools(&self) -> Result<()> {
1661        // Tools run concurrently with event intake, so this can be reached before their
1662        // output is in. Defer to the last tool to finish rather than firing a response the
1663        // model cannot yet answer — or, worse, dropping it because
1664        // `pending_tool_response` is not set yet.
1665        if self.outstanding_tools.load(Ordering::Acquire) > 0 {
1666            self.response_closed_awaiting_tools.store(true, Ordering::Release);
1667            return Ok(());
1668        }
1669
1670        if self.pending_tool_response.swap(false, Ordering::AcqRel)
1671            && let Ok(session) = self.session_handle().await
1672        {
1673            session.create_response().await?;
1674        }
1675        Ok(())
1676    }
1677
1678    /// Close the session.
1679    pub async fn close(&self) -> Result<()> {
1680        if let Some(meter) = &self.meter {
1681            meter.abandon().await;
1682        }
1683        if let Ok(session) = self.session_handle().await {
1684            session.close().await?;
1685        }
1686        Ok(())
1687    }
1688}
1689
1690#[cfg(test)]
1691mod runner_tests {
1692    use super::*;
1693    use crate::audio::{AudioChunk, AudioFormat};
1694    use crate::events::{ClientEvent, ToolResponse};
1695    use crate::model::RealtimeModel;
1696    use crate::session::{BoxedSession, ContextMutationOutcome, RealtimeSession};
1697    use std::pin::Pin;
1698    use std::sync::atomic::AtomicUsize;
1699
1700    /// A model just good enough to satisfy the builder (never connects in tests).
1701    struct MockModel;
1702
1703    #[async_trait]
1704    impl RealtimeModel for MockModel {
1705        fn provider(&self) -> &str {
1706            "mock"
1707        }
1708        fn model_id(&self) -> &str {
1709            "mock"
1710        }
1711        fn supported_input_formats(&self) -> Vec<AudioFormat> {
1712            vec![]
1713        }
1714        fn supported_output_formats(&self) -> Vec<AudioFormat> {
1715            vec![]
1716        }
1717        fn available_voices(&self) -> Vec<&str> {
1718            vec![]
1719        }
1720        async fn connect(&self, _config: RealtimeConfig) -> Result<BoxedSession> {
1721            Err(RealtimeError::connection("mock model does not connect"))
1722        }
1723    }
1724
1725    /// Records which provider-session entry points the runner calls.
1726    #[derive(Default)]
1727    struct Counts {
1728        raw_audio: AtomicUsize,
1729        base64_audio: AtomicUsize,
1730        last_audio: parking_lot::Mutex<Option<AudioChunk>>,
1731        tool_output: AtomicUsize,
1732        tool_response: AtomicUsize,
1733        create_response: AtomicUsize,
1734        last_output: parking_lot::Mutex<Option<serde_json::Value>>,
1735    }
1736
1737    struct RecordingSession {
1738        counts: Arc<Counts>,
1739    }
1740
1741    #[async_trait]
1742    impl RealtimeSession for RecordingSession {
1743        fn session_id(&self) -> &str {
1744            "mock-session"
1745        }
1746        fn is_connected(&self) -> bool {
1747            true
1748        }
1749        async fn send_audio(&self, audio: &AudioChunk) -> Result<()> {
1750            self.counts.raw_audio.fetch_add(1, Ordering::SeqCst);
1751            *self.counts.last_audio.lock() = Some(audio.clone());
1752            Ok(())
1753        }
1754        async fn send_audio_base64(&self, _audio: &str) -> Result<()> {
1755            self.counts.base64_audio.fetch_add(1, Ordering::SeqCst);
1756            Ok(())
1757        }
1758        async fn send_text(&self, _text: &str) -> Result<()> {
1759            Ok(())
1760        }
1761        async fn send_tool_response(&self, _response: ToolResponse) -> Result<()> {
1762            self.counts.tool_response.fetch_add(1, Ordering::SeqCst);
1763            Ok(())
1764        }
1765        async fn send_tool_output(&self, response: ToolResponse) -> Result<()> {
1766            self.counts.tool_output.fetch_add(1, Ordering::SeqCst);
1767            *self.counts.last_output.lock() = Some(response.output);
1768            Ok(())
1769        }
1770        async fn commit_audio(&self) -> Result<()> {
1771            Ok(())
1772        }
1773        async fn clear_audio(&self) -> Result<()> {
1774            Ok(())
1775        }
1776        async fn create_response(&self) -> Result<()> {
1777            self.counts.create_response.fetch_add(1, Ordering::SeqCst);
1778            Ok(())
1779        }
1780        async fn interrupt(&self) -> Result<()> {
1781            Ok(())
1782        }
1783        async fn send_event(&self, _event: ClientEvent) -> Result<()> {
1784            Ok(())
1785        }
1786        async fn next_event(&self) -> Option<Result<ServerEvent>> {
1787            None
1788        }
1789        fn events(&self) -> Pin<Box<dyn futures::Stream<Item = Result<ServerEvent>> + Send + '_>> {
1790            Box::pin(futures::stream::empty())
1791        }
1792        async fn close(&self) -> Result<()> {
1793            Ok(())
1794        }
1795        async fn mutate_context(&self, _config: RealtimeConfig) -> Result<ContextMutationOutcome> {
1796            Ok(ContextMutationOutcome::Applied)
1797        }
1798    }
1799
1800    fn tool_def(name: &str) -> ToolDefinition {
1801        ToolDefinition::new(name)
1802    }
1803
1804    #[test]
1805    fn runner_builder_rejects_two_tools_with_one_name() {
1806        let builder = || {
1807            RealtimeRunner::builder()
1808                .model(Arc::new(MockModel) as BoxedModel)
1809                .tool_fn(tool_def("pay"), |_call| Ok(serde_json::json!({ "paid": 1 })))
1810        };
1811        let Err(err) = builder()
1812            .tool_fn(tool_def("pay"), |_call| Ok(serde_json::json!({ "paid": 2 })))
1813            .build()
1814        else {
1815            panic!("two tools named `pay` must fail the build");
1816        };
1817        assert!(matches!(err, RealtimeError::ConfigError(_)), "{err}");
1818        assert!(err.to_string().contains("'pay'"), "{err}");
1819        assert!(
1820            builder()
1821                .tool_fn(tool_def("refund"), |_call| Ok(serde_json::json!({})))
1822                .build()
1823                .is_ok()
1824        );
1825    }
1826
1827    #[test]
1828    fn agent_builder_rejects_two_tools_with_one_name() {
1829        struct Lookup;
1830
1831        #[async_trait]
1832        impl adk_core::Tool for Lookup {
1833            fn name(&self) -> &str {
1834                "lookup"
1835            }
1836            fn description(&self) -> &str {
1837                "looks things up"
1838            }
1839            async fn execute(
1840                &self,
1841                _ctx: Arc<dyn adk_core::ToolContext>,
1842                args: serde_json::Value,
1843            ) -> adk_core::Result<serde_json::Value> {
1844                Ok(args)
1845            }
1846        }
1847
1848        let Err(err) = crate::agent::RealtimeAgent::builder("voice")
1849            .model(Arc::new(MockModel) as BoxedModel)
1850            .tool(Arc::new(Lookup))
1851            .tool(Arc::new(Lookup))
1852            .build()
1853        else {
1854            panic!("two tools named `lookup` must fail the build");
1855        };
1856        assert_eq!(err.code, adk_core::DUPLICATE_TOOL_NAME_CODE);
1857        assert!(err.message.contains("'lookup'"), "{}", err.message);
1858    }
1859
1860    fn ok_tool() -> FnToolHandler<impl Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync> {
1861        FnToolHandler::new(|_call: &ToolCall| Ok(serde_json::json!({ "ok": true })))
1862    }
1863
1864    fn function_call(call_id: &str, name: &str) -> ServerEvent {
1865        ServerEvent::FunctionCallDone {
1866            event_id: "evt".into(),
1867            response_id: "resp".into(),
1868            item_id: "item".into(),
1869            output_index: 0,
1870            call_id: call_id.into(),
1871            name: name.into(),
1872            arguments: "{}".into(),
1873        }
1874    }
1875
1876    fn response_done() -> ServerEvent {
1877        ServerEvent::ResponseDone { event_id: "evt".into(), response: serde_json::json!({}) }
1878    }
1879
1880    async fn runner_with_session(counts: Arc<Counts>) -> RealtimeRunner {
1881        let runner =
1882            RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).build().unwrap();
1883        let session = Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>;
1884
1885        // The unit test owns the runner and installs the same session handle
1886        // that `connect` would publish after provider setup.
1887        *runner.session.write().await = Some(session);
1888        runner
1889    }
1890
1891    /// A runner whose `pay` tool counts executions, governed by `config`.
1892    async fn governed_runner(
1893        counts: Arc<Counts>,
1894        executions: Arc<AtomicUsize>,
1895        config: adk_core::RunConfig,
1896    ) -> RealtimeRunner {
1897        let runner = RealtimeRunner::builder()
1898            .model(Arc::new(MockModel) as BoxedModel)
1899            .tool_fn(tool_def("pay"), move |_call| {
1900                executions.fetch_add(1, Ordering::SeqCst);
1901                Ok(serde_json::json!({ "paid": true }))
1902            })
1903            .tool_governance(config, adk_core::ApprovalScope::new("voice", "user", "session"))
1904            .build()
1905            .unwrap();
1906        *runner.session.write().await =
1907            Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
1908        runner
1909    }
1910
1911    /// A runner whose `lookup` handler returns a customer record, or fails quoting a
1912    /// credential, configured by `configure`.
1913    async fn lookup_runner(
1914        counts: Arc<Counts>,
1915        fails: bool,
1916        configure: impl FnOnce(RealtimeRunnerBuilder) -> RealtimeRunnerBuilder,
1917    ) -> RealtimeRunner {
1918        let builder = RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).tool_fn(
1919            tool_def("lookup"),
1920            move |_call| {
1921                if fails {
1922                    Err(RealtimeError::ToolError(
1923                        "connect postgres://admin:hunter2@db.internal/prod failed".into(),
1924                    ))
1925                } else {
1926                    Ok(serde_json::json!({ "ssn": "123-45-6789" }))
1927                }
1928            },
1929        );
1930        let runner = configure(builder).build().unwrap();
1931        *runner.session.write().await =
1932            Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
1933        runner
1934    }
1935
1936    /// Withholds every result, or redacts its `ssn`.
1937    struct SsnScreen {
1938        fail: bool,
1939    }
1940
1941    #[async_trait]
1942    impl adk_core::ToolResultScreen for SsnScreen {
1943        async fn screen_result(
1944            &self,
1945            _tool_name: &str,
1946            _args: &serde_json::Value,
1947            result: &serde_json::Value,
1948        ) -> std::result::Result<serde_json::Value, String> {
1949            if self.fail {
1950                return Err("the screening service is unavailable".into());
1951            }
1952            let mut result = result.clone();
1953            if result.get("ssn").is_some() {
1954                result["ssn"] = serde_json::json!("[SSN REDACTED]");
1955            }
1956            Ok(result)
1957        }
1958    }
1959
1960    #[tokio::test]
1961    async fn handler_errors_reach_the_model_redacted_unless_exposed() {
1962        let counts = Arc::new(Counts::default());
1963        let runner = lookup_runner(Arc::clone(&counts), true, |b| b).await;
1964        runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
1965        let output = counts.last_output.lock().clone().unwrap();
1966        assert_eq!(output, serde_json::json!({ "error": "tool 'lookup' failed" }));
1967
1968        let runner =
1969            lookup_runner(Arc::clone(&counts), true, |b| b.expose_tool_error_messages(true)).await;
1970        runner.dispatch_tool_call("c2", "lookup", "{}").await.unwrap();
1971        let output = counts.last_output.lock().clone().unwrap();
1972        assert!(output["error"].as_str().unwrap_or_default().contains("hunter2"), "{output}");
1973    }
1974
1975    /// Records every event field the runner logs.
1976    #[derive(Clone, Default)]
1977    struct Logged(Arc<parking_lot::Mutex<Vec<String>>>);
1978
1979    struct LoggedValues<'a>(&'a mut Vec<String>);
1980
1981    impl tracing::field::Visit for LoggedValues<'_> {
1982        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
1983            self.0.push(format!("{}={value:?}", field.name()));
1984        }
1985    }
1986
1987    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Logged {
1988        fn on_event(
1989            &self,
1990            event: &tracing::Event<'_>,
1991            _ctx: tracing_subscriber::layer::Context<'_, S>,
1992        ) {
1993            event.record(&mut LoggedValues(&mut self.0.lock()));
1994        }
1995    }
1996
1997    #[tokio::test(flavor = "current_thread")]
1998    async fn handler_error_messages_are_logged_only_under_the_payload_rule() {
1999        use tracing_subscriber::layer::SubscriberExt;
2000
2001        for record_payloads in [false, true] {
2002            let logged = Logged::default();
2003            let _guard = tracing::subscriber::set_default(
2004                tracing_subscriber::registry().with(logged.clone()),
2005            );
2006            let counts = Arc::new(Counts::default());
2007            let config = adk_core::RunConfig { record_payloads, ..adk_core::RunConfig::default() };
2008            let runner = lookup_runner(Arc::clone(&counts), true, |b| {
2009                b.tool_governance(config, adk_core::ApprovalScope::new("voice", "user", "s"))
2010            })
2011            .await;
2012            runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
2013
2014            let values = logged.0.lock().clone();
2015            assert!(values.contains(&"error.kind=\"tool\"".to_string()), "{values:#?}");
2016            assert_eq!(
2017                values.iter().any(|value| value.contains("hunter2")),
2018                record_payloads,
2019                "the message is logged only when payloads are recorded: {values:#?}"
2020            );
2021        }
2022    }
2023
2024    #[tokio::test]
2025    async fn the_result_screen_runs_before_the_output_is_sent() {
2026        let counts = Arc::new(Counts::default());
2027        let runner = lookup_runner(Arc::clone(&counts), false, |b| {
2028            b.tool_result_screen(Arc::new(SsnScreen { fail: false }))
2029        })
2030        .await;
2031        runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
2032        let output = counts.last_output.lock().clone().unwrap();
2033        assert_eq!(output, serde_json::json!({ "ssn": "[SSN REDACTED]" }));
2034
2035        let runner = lookup_runner(Arc::clone(&counts), false, |b| {
2036            b.tool_result_screen(Arc::new(SsnScreen { fail: true }))
2037        })
2038        .await;
2039        runner.dispatch_tool_call("c2", "lookup", "{}").await.unwrap();
2040        let output = counts.last_output.lock().clone().unwrap();
2041        assert_eq!(output["status"], adk_core::RESULT_WITHHELD_STATUS, "{output}");
2042        assert!(!output.to_string().contains("123-45-6789"), "{output}");
2043    }
2044
2045    #[tokio::test]
2046    async fn malformed_tool_arguments_are_refused() {
2047        let counts = Arc::new(Counts::default());
2048        let executions = Arc::new(AtomicUsize::new(0));
2049        let runner = governed_runner(
2050            Arc::clone(&counts),
2051            Arc::clone(&executions),
2052            adk_core::RunConfig::default(),
2053        )
2054        .await;
2055
2056        runner.dispatch_tool_call("c1", "pay", r#"{"amount": 5"#).await.unwrap();
2057
2058        assert_eq!(executions.load(Ordering::SeqCst), 0, "a malformed call must not run");
2059        let output = counts.last_output.lock().clone().expect("the call is answered");
2060        assert!(output["error"].as_str().unwrap_or_default().contains("not valid JSON"));
2061    }
2062
2063    #[tokio::test]
2064    async fn the_runner_policy_and_kill_switch_govern_dispatched_calls() {
2065        let counts = Arc::new(Counts::default());
2066        let executions = Arc::new(AtomicUsize::new(0));
2067        let control = adk_core::GovernanceControl::new();
2068        let config = adk_core::RunConfig::builder()
2069            .tool_policy(Arc::new(adk_core::DeclarativePolicy::builder().allow("get_*").build()))
2070            .governance(control.clone())
2071            .build();
2072        let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
2073
2074        runner.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
2075        assert_eq!(executions.load(Ordering::SeqCst), 0);
2076        let output = counts.last_output.lock().clone().unwrap();
2077        assert!(output["error"].as_str().unwrap_or_default().contains("denied by policy"));
2078
2079        control.freeze("drill");
2080        let error = runner.dispatch_tool_call("c2", "pay", "{}").await.unwrap_err();
2081        assert!(error.to_string().contains("frozen"), "{error}");
2082        assert_eq!(executions.load(Ordering::SeqCst), 0);
2083    }
2084
2085    /// The review of #1005: a freeze while the confirmation handler decides ends the wait,
2086    /// and the dispatch ends with the freeze before the handler runs, as an agent's call is
2087    /// refused.
2088    #[tokio::test]
2089    async fn a_freeze_ends_the_wait_for_the_confirmation_handler() {
2090        #[derive(Debug)]
2091        struct NeverAnswers;
2092
2093        #[async_trait]
2094        impl adk_core::ToolConfirmationHandler for NeverAnswers {
2095            async fn decide(
2096                &self,
2097                _request: &adk_core::ToolConfirmationRequest,
2098            ) -> adk_core::Result<adk_core::ToolConfirmationDecision> {
2099                std::future::pending().await
2100            }
2101        }
2102
2103        let counts = Arc::new(Counts::default());
2104        let executions = Arc::new(AtomicUsize::new(0));
2105        let control = adk_core::GovernanceControl::new();
2106        let config = adk_core::RunConfig::builder()
2107            .tool_policy(Arc::new(
2108                adk_core::DeclarativePolicy::builder()
2109                    .require_approval("pay", "payments need a person")
2110                    .build(),
2111            ))
2112            .tool_confirmation_handler(Arc::new(NeverAnswers))
2113            .governance(control.clone())
2114            .build();
2115        let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
2116        tokio::spawn(async move {
2117            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2118            control.freeze("incident 4017");
2119        });
2120
2121        let error = tokio::time::timeout(
2122            std::time::Duration::from_secs(5),
2123            runner.dispatch_tool_call("c1", "pay", "{}"),
2124        )
2125        .await
2126        .expect("the freeze ends the wait")
2127        .unwrap_err();
2128        assert!(error.to_string().contains("incident 4017"), "{error}");
2129        assert_eq!(executions.load(Ordering::SeqCst), 0, "the handler never runs");
2130        assert_eq!(*counts.last_output.lock(), None, "nothing is sent for the refused call");
2131    }
2132
2133    /// A native handler's held call names the runner's agent and the `realtime` origin of
2134    /// the handler's definition, so an approval of it never covers the handler once
2135    /// redefined, nor another agent's identical call (#1210).
2136    #[tokio::test]
2137    async fn a_native_handlers_held_call_names_its_agent_and_handler_origin() {
2138        use adk_core::ApprovalStore;
2139        let counts = Arc::new(Counts::default());
2140        let executions = Arc::new(AtomicUsize::new(0));
2141        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
2142        let scope = adk_core::ApprovalScope::new("voice", "user", "session");
2143        let config = adk_core::RunConfig::builder()
2144            .tool_policy(Arc::new(
2145                adk_core::DeclarativePolicy::builder()
2146                    .require_approval("pay", "payments need a person")
2147                    .build(),
2148            ))
2149            .approval_store(store.clone())
2150            .build();
2151        let runner = |definition: ToolDefinition, agent: &str| {
2152            let executions = Arc::clone(&executions);
2153            RealtimeRunner::builder()
2154                .model(Arc::new(MockModel) as BoxedModel)
2155                .agent_name(agent)
2156                .tool_fn(definition, move |_call| {
2157                    executions.fetch_add(1, Ordering::SeqCst);
2158                    Ok(serde_json::json!({ "paid": true }))
2159                })
2160                .tool_governance(config.clone(), scope.clone())
2161                .build()
2162                .unwrap()
2163        };
2164        let install = |runner: RealtimeRunner| {
2165            let counts = Arc::clone(&counts);
2166            async move {
2167                *runner.session.write().await =
2168                    Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
2169                runner
2170            }
2171        };
2172        let pay = tool_def("pay").with_description("Pays an invoice");
2173        let reworded_pay = pay.clone().with_description("Pays anyone");
2174        let voice = install(runner(pay.clone(), "voice")).await;
2175
2176        voice.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
2177        let pending = store.pending(&scope).await.unwrap();
2178        let [held] = pending.as_slice() else { panic!("one held call: {pending:?}") };
2179        assert_eq!(held.request.origin, Some(pay.handler_origin()));
2180        assert_eq!(held.request.origin.as_ref().unwrap().source, REALTIME_HANDLER_ORIGIN);
2181        assert_eq!(
2182            held.request.acting.as_ref().map(|acting| acting.agent.id.as_str()),
2183            Some("urn:adk:agent:voice/voice")
2184        );
2185        assert_eq!(
2186            adk_core::ToolConfirmationRequest::fingerprint_agent(&held.fingerprint),
2187            Some("urn:adk:agent:voice/voice")
2188        );
2189
2190        // Redefined, the handler is not the one approved.
2191        store.decide(&scope, &held.fingerprint, adk_core::ToolApproval::approve()).await.unwrap();
2192        let reworded = install(runner(reworded_pay.clone(), "voice")).await;
2193        reworded.dispatch_tool_call("c2", "pay", "{}").await.unwrap();
2194        assert_eq!(executions.load(Ordering::SeqCst), 0, "a redefined handler needs approval");
2195
2196        // Another agent's identical call is not the one approved.
2197        let intern = install(runner(pay.clone(), "intern")).await;
2198        intern.dispatch_tool_call("c3", "pay", "{}").await.unwrap();
2199        assert_eq!(executions.load(Ordering::SeqCst), 0, "another agent needs its own approval");
2200
2201        // The handler as approved, by the agent it was approved for, runs once.
2202        voice.dispatch_tool_call("c4", "pay", "{}").await.unwrap();
2203        assert_eq!(executions.load(Ordering::SeqCst), 1);
2204        let mut waiting: Vec<_> = store
2205            .pending(&scope)
2206            .await
2207            .unwrap()
2208            .into_iter()
2209            .map(|entry| {
2210                let agent =
2211                    adk_core::ToolConfirmationRequest::fingerprint_agent(&entry.fingerprint)
2212                        .map(str::to_string);
2213                (agent, entry.request.origin)
2214            })
2215            .collect();
2216        waiting.sort_by(|a, b| a.0.cmp(&b.0));
2217        assert_eq!(
2218            waiting,
2219            [
2220                (Some("urn:adk:agent:voice/intern".to_string()), Some(pay.handler_origin())),
2221                (
2222                    Some("urn:adk:agent:voice/voice".to_string()),
2223                    Some(reworded_pay.handler_origin())
2224                ),
2225            ],
2226            "each unapproved call waits on its own"
2227        );
2228    }
2229
2230    #[tokio::test]
2231    async fn policy_rules_match_the_configured_voice_agent() {
2232        let counts = Arc::new(Counts::default());
2233        let executions = Arc::new(AtomicUsize::new(0));
2234        let principal = adk_core::AgentPrincipal::new(
2235            adk_core::AgentId::new("spiffe://acme.test/agent/voice").unwrap(),
2236        );
2237        let config = adk_core::RunConfig::builder()
2238            .tool_policy(Arc::new(
2239                adk_core::DeclarativePolicy::builder()
2240                    .rule(
2241                        adk_core::PolicyRule::allow("pay")
2242                            .for_agent("spiffe://acme.test/agent/voice"),
2243                    )
2244                    .build(),
2245            ))
2246            .agent_principal("realtime", principal)
2247            .build();
2248        let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
2249
2250        runner.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
2251        assert_eq!(executions.load(Ordering::SeqCst), 1, "the voice agent's rule allows it");
2252
2253        let unconfigured = adk_core::RunConfig::builder()
2254            .tool_policy(Arc::new(
2255                adk_core::DeclarativePolicy::builder()
2256                    .rule(
2257                        adk_core::PolicyRule::allow("pay")
2258                            .for_agent("spiffe://acme.test/agent/voice"),
2259                    )
2260                    .build(),
2261            ))
2262            .build();
2263        let runner =
2264            governed_runner(Arc::clone(&counts), Arc::clone(&executions), unconfigured).await;
2265        runner.dispatch_tool_call("c2", "pay", "{}").await.unwrap();
2266        assert_eq!(
2267            executions.load(Ordering::SeqCst),
2268            1,
2269            "the derived identity urn:adk:agent:voice/realtime is not the voice agent"
2270        );
2271    }
2272
2273    #[tokio::test]
2274    async fn send_audio_chunk_preserves_bytes_and_format_on_raw_path() {
2275        let counts = Arc::new(Counts::default());
2276        let runner = runner_with_session(Arc::clone(&counts)).await;
2277        let chunk = AudioChunk::pcm16_24khz(vec![1, 2, 3, 4]);
2278
2279        runner.send_audio_chunk(&chunk).await.unwrap();
2280
2281        assert_eq!(counts.raw_audio.load(Ordering::SeqCst), 1);
2282        assert_eq!(counts.base64_audio.load(Ordering::SeqCst), 0);
2283        let recorded = counts.last_audio.lock();
2284        let recorded = recorded.as_ref().unwrap();
2285        assert_eq!(recorded.data, chunk.data);
2286        assert_eq!(recorded.format, chunk.format);
2287    }
2288
2289    #[tokio::test]
2290    async fn send_audio_keeps_base64_compatibility_path() {
2291        let counts = Arc::new(Counts::default());
2292        let runner = runner_with_session(Arc::clone(&counts)).await;
2293
2294        runner.send_audio("AQIDBA==").await.unwrap();
2295
2296        assert_eq!(counts.raw_audio.load(Ordering::SeqCst), 0);
2297        assert_eq!(counts.base64_audio.load(Ordering::SeqCst), 1);
2298    }
2299
2300    /// Two parallel tool calls in one response must produce exactly one
2301    /// `create_response` — issued after the dispatch response finishes — not one
2302    /// per tool (which collides with the still-active response on OpenAI).
2303    #[tokio::test]
2304    async fn parallel_tool_calls_trigger_a_single_response() {
2305        let counts = Arc::new(Counts::default());
2306        let runner = RealtimeRunner::builder()
2307            .model(Arc::new(MockModel) as BoxedModel)
2308            .tool(tool_def("get_weather"), ok_tool())
2309            .tool(tool_def("get_time"), ok_tool())
2310            .build()
2311            .unwrap();
2312        *runner.session.write().await =
2313            Some(Arc::new(RecordingSession { counts: counts.clone() }) as Arc<dyn RealtimeSession>);
2314
2315        // One model response dispatching two tool calls, then ending. Driven through
2316        // `run`, because dispatch is the run loop's job now — `handle_event` returns the
2317        // call rather than awaiting it, so event intake is not blocked by a tool.
2318        let scripted = Arc::new(ScriptedSession::new(
2319            counts.clone(),
2320            vec![
2321                function_call("c1", "get_weather"),
2322                function_call("c2", "get_time"),
2323                response_done(),
2324            ],
2325        ));
2326        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2327        runner.run().await.unwrap();
2328
2329        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 2, "both outputs sent");
2330        assert_eq!(counts.create_response.load(Ordering::SeqCst), 1, "exactly one response");
2331        assert_eq!(
2332            counts.tool_response.load(Ordering::SeqCst),
2333            0,
2334            "auto path must use send_tool_output, not the output+create combo"
2335        );
2336
2337        // The follow-up (spoken-answer) response finishing creates nothing more.
2338        runner.handle_event(response_done()).await.unwrap();
2339        assert_eq!(counts.create_response.load(Ordering::SeqCst), 1, "no extra response");
2340    }
2341
2342    /// A response with no tool calls must not trigger an auto follow-up response.
2343    #[tokio::test]
2344    async fn plain_response_triggers_no_auto_response() {
2345        let counts = Arc::new(Counts::default());
2346        let runner =
2347            RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).build().unwrap();
2348        *runner.session.write().await =
2349            Some(Arc::new(RecordingSession { counts: counts.clone() }) as Arc<dyn RealtimeSession>);
2350
2351        runner.handle_event(response_done()).await.unwrap();
2352        assert_eq!(counts.create_response.load(Ordering::SeqCst), 0);
2353        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 0);
2354    }
2355
2356    // ── Bounded concurrent tool dispatch ──────────────────────────────────
2357    //
2358    // `RunnerConfig::max_concurrent_tools` defaulted to four and was read by nothing: no
2359    // semaphore, no scheduler. `FunctionCallDone` was awaited inline inside `handle_event`,
2360    // which the run loop awaited before reading the next event, so tool calls ran strictly
2361    // one at a time *and* stalled audio and every other event for the duration.
2362
2363    /// A session that replays a scripted event sequence, then reports disconnect.
2364    struct ScriptedSession {
2365        counts: Arc<Counts>,
2366        events: parking_lot::Mutex<std::collections::VecDeque<ServerEvent>>,
2367    }
2368
2369    impl ScriptedSession {
2370        fn new(counts: Arc<Counts>, events: Vec<ServerEvent>) -> Self {
2371            Self { counts, events: parking_lot::Mutex::new(events.into()) }
2372        }
2373    }
2374
2375    #[async_trait]
2376    impl RealtimeSession for ScriptedSession {
2377        fn session_id(&self) -> &str {
2378            "scripted-session"
2379        }
2380        fn is_connected(&self) -> bool {
2381            true
2382        }
2383        async fn send_audio(&self, _audio: &AudioChunk) -> Result<()> {
2384            Ok(())
2385        }
2386        async fn send_audio_base64(&self, _audio: &str) -> Result<()> {
2387            Ok(())
2388        }
2389        async fn send_text(&self, _text: &str) -> Result<()> {
2390            Ok(())
2391        }
2392        async fn send_tool_response(&self, _response: ToolResponse) -> Result<()> {
2393            self.counts.tool_response.fetch_add(1, Ordering::SeqCst);
2394            Ok(())
2395        }
2396        async fn send_tool_output(&self, _response: ToolResponse) -> Result<()> {
2397            self.counts.tool_output.fetch_add(1, Ordering::SeqCst);
2398            Ok(())
2399        }
2400        async fn commit_audio(&self) -> Result<()> {
2401            Ok(())
2402        }
2403        async fn clear_audio(&self) -> Result<()> {
2404            Ok(())
2405        }
2406        async fn create_response(&self) -> Result<()> {
2407            self.counts.create_response.fetch_add(1, Ordering::SeqCst);
2408            Ok(())
2409        }
2410        async fn interrupt(&self) -> Result<()> {
2411            Ok(())
2412        }
2413        async fn send_event(&self, _event: ClientEvent) -> Result<()> {
2414            Ok(())
2415        }
2416        async fn next_event(&self) -> Option<Result<ServerEvent>> {
2417            let event = self.events.lock().pop_front();
2418            event.map(Ok)
2419        }
2420        fn events(&self) -> Pin<Box<dyn futures::Stream<Item = Result<ServerEvent>> + Send + '_>> {
2421            Box::pin(futures::stream::empty())
2422        }
2423        async fn close(&self) -> Result<()> {
2424            Ok(())
2425        }
2426        async fn mutate_context(&self, _config: RealtimeConfig) -> Result<ContextMutationOutcome> {
2427            Ok(ContextMutationOutcome::Applied)
2428        }
2429    }
2430
2431    /// A tool that reports how many copies of itself run at once.
2432    struct ConcurrencyProbe {
2433        in_flight: Arc<AtomicUsize>,
2434        peak: Arc<AtomicUsize>,
2435        barrier: Option<Arc<tokio::sync::Barrier>>,
2436    }
2437
2438    #[async_trait]
2439    impl ToolHandler for ConcurrencyProbe {
2440        async fn execute(&self, _call: &ToolCall) -> Result<serde_json::Value> {
2441            let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
2442            self.peak.fetch_max(now, Ordering::SeqCst);
2443
2444            match &self.barrier {
2445                // Every participant must be running for this to return, so it can only
2446                // complete if the dispatcher truly overlaps them.
2447                Some(barrier) => {
2448                    barrier.wait().await;
2449                }
2450                None => {
2451                    tokio::task::yield_now().await;
2452                }
2453            }
2454
2455            self.in_flight.fetch_sub(1, Ordering::SeqCst);
2456            Ok(serde_json::json!({ "ok": true }))
2457        }
2458    }
2459
2460    fn audio_delta() -> ServerEvent {
2461        ServerEvent::AudioDelta {
2462            event_id: "evt".into(),
2463            response_id: "resp".into(),
2464            item_id: "item".into(),
2465            output_index: 0,
2466            content_index: 0,
2467            delta: vec![1, 2, 3],
2468        }
2469    }
2470
2471    #[tokio::test]
2472    async fn tool_calls_overlap_up_to_the_configured_bound() {
2473        let counts = Arc::new(Counts::default());
2474        let in_flight = Arc::new(AtomicUsize::new(0));
2475        let peak = Arc::new(AtomicUsize::new(0));
2476        // Only satisfiable if all three run at once, which serial dispatch cannot do.
2477        let barrier = Arc::new(tokio::sync::Barrier::new(3));
2478
2479        let probe = || ConcurrencyProbe {
2480            in_flight: Arc::clone(&in_flight),
2481            peak: Arc::clone(&peak),
2482            barrier: Some(Arc::clone(&barrier)),
2483        };
2484
2485        let runner = RealtimeRunner::builder()
2486            .model(Arc::new(MockModel) as BoxedModel)
2487            .runner_config(RunnerConfig {
2488                auto_execute_tools: true,
2489                auto_respond_tools: true,
2490                max_concurrent_tools: 3,
2491            })
2492            .tool(tool_def("a"), probe())
2493            .tool(tool_def("b"), probe())
2494            .tool(tool_def("c"), probe())
2495            .build()
2496            .unwrap();
2497
2498        let scripted = Arc::new(ScriptedSession::new(
2499            Arc::clone(&counts),
2500            vec![function_call("c1", "a"), function_call("c2", "b"), function_call("c3", "c")],
2501        ));
2502        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2503
2504        tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
2505            .await
2506            .expect("serial dispatch cannot satisfy a three-way barrier")
2507            .unwrap();
2508
2509        assert_eq!(peak.load(Ordering::SeqCst), 3, "all three tools must overlap");
2510        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 3, "every output is sent");
2511    }
2512
2513    #[tokio::test]
2514    async fn the_bound_caps_how_many_tools_overlap() {
2515        let counts = Arc::new(Counts::default());
2516        let in_flight = Arc::new(AtomicUsize::new(0));
2517        let peak = Arc::new(AtomicUsize::new(0));
2518
2519        let probe = || ConcurrencyProbe {
2520            in_flight: Arc::clone(&in_flight),
2521            peak: Arc::clone(&peak),
2522            barrier: None,
2523        };
2524
2525        let runner = RealtimeRunner::builder()
2526            .model(Arc::new(MockModel) as BoxedModel)
2527            .runner_config(RunnerConfig {
2528                auto_execute_tools: true,
2529                auto_respond_tools: true,
2530                max_concurrent_tools: 2,
2531            })
2532            .tool(tool_def("a"), probe())
2533            .tool(tool_def("b"), probe())
2534            .tool(tool_def("c"), probe())
2535            .tool(tool_def("d"), probe())
2536            .build()
2537            .unwrap();
2538
2539        let scripted = Arc::new(ScriptedSession::new(
2540            Arc::clone(&counts),
2541            vec![
2542                function_call("c1", "a"),
2543                function_call("c2", "b"),
2544                function_call("c3", "c"),
2545                function_call("c4", "d"),
2546            ],
2547        ));
2548        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2549
2550        runner.run().await.unwrap();
2551
2552        assert!(
2553            peak.load(Ordering::SeqCst) <= 2,
2554            "the bound was exceeded: peak {}",
2555            peak.load(Ordering::SeqCst)
2556        );
2557        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 4, "all four still complete");
2558    }
2559
2560    /// A tool that blocks until an audio event has been handled.
2561    struct WaitsForAudio {
2562        audio_seen: Arc<tokio::sync::Notify>,
2563    }
2564
2565    #[async_trait]
2566    impl ToolHandler for WaitsForAudio {
2567        async fn execute(&self, _call: &ToolCall) -> Result<serde_json::Value> {
2568            self.audio_seen.notified().await;
2569            Ok(serde_json::json!({ "ok": true }))
2570        }
2571    }
2572
2573    /// Signals the tool once audio is delivered.
2574    struct AudioSignaller {
2575        audio_seen: Arc<tokio::sync::Notify>,
2576        audio_events: Arc<AtomicUsize>,
2577    }
2578
2579    #[async_trait]
2580    impl EventHandler for AudioSignaller {
2581        async fn on_audio(&self, _audio: &[u8], _item_id: &str) -> Result<()> {
2582            self.audio_events.fetch_add(1, Ordering::SeqCst);
2583            self.audio_seen.notify_waiters();
2584            Ok(())
2585        }
2586    }
2587
2588    #[tokio::test]
2589    async fn audio_keeps_flowing_while_a_tool_runs() {
2590        let counts = Arc::new(Counts::default());
2591        let audio_seen = Arc::new(tokio::sync::Notify::new());
2592        let audio_events = Arc::new(AtomicUsize::new(0));
2593
2594        let runner = RealtimeRunner::builder()
2595            .model(Arc::new(MockModel) as BoxedModel)
2596            .tool(tool_def("slow"), WaitsForAudio { audio_seen: Arc::clone(&audio_seen) })
2597            .event_handler(AudioSignaller {
2598                audio_seen: Arc::clone(&audio_seen),
2599                audio_events: Arc::clone(&audio_events),
2600            })
2601            .build()
2602            .unwrap();
2603
2604        // The tool can only finish once the audio delta *after* it has been handled, so
2605        // this sequence completes only if event intake continues during tool execution.
2606        let scripted = Arc::new(ScriptedSession::new(
2607            Arc::clone(&counts),
2608            vec![function_call("c1", "slow"), audio_delta(), response_done()],
2609        ));
2610        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2611
2612        tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
2613            .await
2614            .expect("a tool awaiting a later event deadlocks when dispatch blocks intake")
2615            .unwrap();
2616
2617        assert_eq!(audio_events.load(Ordering::SeqCst), 1, "the audio delta was handled");
2618        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 1, "the tool still reported output");
2619    }
2620
2621    #[tokio::test]
2622    async fn the_follow_up_response_waits_for_tools_that_outlive_the_response() {
2623        let counts = Arc::new(Counts::default());
2624        let audio_seen = Arc::new(tokio::sync::Notify::new());
2625        let audio_events = Arc::new(AtomicUsize::new(0));
2626
2627        let runner = RealtimeRunner::builder()
2628            .model(Arc::new(MockModel) as BoxedModel)
2629            .tool(tool_def("slow"), WaitsForAudio { audio_seen: Arc::clone(&audio_seen) })
2630            .event_handler(AudioSignaller {
2631                audio_seen: Arc::clone(&audio_seen),
2632                audio_events: Arc::clone(&audio_events),
2633            })
2634            .build()
2635            .unwrap();
2636
2637        // `ResponseDone` arrives while the tool is still running — impossible before
2638        // dispatch was concurrent, and the case that would silently drop the follow-up
2639        // response, since `pending_tool_response` is only set once output is sent.
2640        let scripted = Arc::new(ScriptedSession::new(
2641            Arc::clone(&counts),
2642            vec![function_call("c1", "slow"), response_done(), audio_delta()],
2643        ));
2644        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2645
2646        tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
2647            .await
2648            .expect("run must finish")
2649            .unwrap();
2650
2651        assert_eq!(counts.tool_output.load(Ordering::SeqCst), 1, "the output was sent");
2652        assert_eq!(
2653            counts.create_response.load(Ordering::SeqCst),
2654            1,
2655            "exactly one follow-up response, issued after the last tool finished"
2656        );
2657    }
2658
2659    /// Records terminal disconnects.
2660    #[derive(Default)]
2661    struct DisconnectWatcher {
2662        disconnects: Arc<AtomicUsize>,
2663    }
2664
2665    #[async_trait]
2666    impl EventHandler for DisconnectWatcher {
2667        async fn on_disconnect(&self) -> Result<()> {
2668            self.disconnects.fetch_add(1, Ordering::SeqCst);
2669            Ok(())
2670        }
2671    }
2672
2673    #[tokio::test]
2674    async fn a_terminal_disconnect_is_surfaced_once() {
2675        let counts = Arc::new(Counts::default());
2676        let disconnects = Arc::new(AtomicUsize::new(0));
2677
2678        let runner = RealtimeRunner::builder()
2679            .model(Arc::new(MockModel) as BoxedModel)
2680            .event_handler(DisconnectWatcher { disconnects: Arc::clone(&disconnects) })
2681            .build()
2682            .unwrap();
2683
2684        let scripted = Arc::new(ScriptedSession::new(Arc::clone(&counts), vec![response_done()]));
2685        *runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
2686
2687        // `run` returns `Ok(())` on transport loss, which on its own is indistinguishable
2688        // from a graceful `close`.
2689        runner.run().await.unwrap();
2690
2691        assert_eq!(
2692            disconnects.load(Ordering::SeqCst),
2693            1,
2694            "transport loss must be reported exactly once"
2695        );
2696    }
2697}