Skip to main content

gemini_adk_rs/
runner.rs

1//! Runner — orchestrates agent execution across Gemini Live sessions.
2//!
3//! Handles the full lifecycle: connect → run agent → handle transfer → reconnect → repeat.
4//! Transfer is complex in Gemini Live because tools are fixed at setup — changing agents
5//! means changing sessions (unlike traditional ADK where tools change per-call).
6
7use std::sync::Arc;
8
9use crate::agent::Agent;
10use crate::agent_session::AgentSession;
11use crate::context::InvocationContext;
12use crate::error::AgentError;
13use crate::middleware::MiddlewareChain;
14use crate::plugin::{Plugin, PluginManager};
15use crate::router::AgentRegistry;
16use crate::state::State;
17
18/// Orchestrates agent execution across Gemini Live sessions.
19///
20/// Handles the full lifecycle: connect → run → transfer → reconnect → repeat.
21/// Transfer is complex in Gemini Live because tools are fixed at setup —
22/// changing agents means changing sessions.
23///
24/// # Example
25///
26/// ```ignore
27/// let runner = Runner::new(root_agent);
28///
29/// runner.run(|agent| async move {
30///     let config = SessionConfig::new(&api_key)
31///         .model(ModelId::LIVE_2_5_FLASH_NATIVE_AUDIO);
32///     // Add agent's tools to config
33///     let session = connect(config).await?;
34///     Ok(AgentSession::new(session))
35/// }).await?;
36/// ```
37pub struct Runner {
38    root_agent: Arc<dyn Agent>,
39    registry: AgentRegistry,
40    middleware: MiddlewareChain,
41    plugins: PluginManager,
42    state: State,
43}
44
45impl Runner {
46    /// Create a new Runner with a root agent.
47    ///
48    /// Automatically registers the root agent and all sub-agents recursively.
49    pub fn new(root_agent: impl Agent + 'static) -> Self {
50        let agent = Arc::new(root_agent);
51        let mut registry = AgentRegistry::new();
52        Self::register_tree(&mut registry, agent.clone());
53        Self {
54            root_agent: agent,
55            registry,
56            middleware: MiddlewareChain::new(),
57            plugins: PluginManager::new(),
58            state: State::new(),
59        }
60    }
61
62    /// Create a Runner from an already-Arc'd agent.
63    pub fn from_arc(root_agent: Arc<dyn Agent>) -> Self {
64        let mut registry = AgentRegistry::new();
65        Self::register_tree(&mut registry, root_agent.clone());
66        Self {
67            root_agent,
68            registry,
69            middleware: MiddlewareChain::new(),
70            plugins: PluginManager::new(),
71            state: State::new(),
72        }
73    }
74
75    /// Add middleware to the runner (applied to all agent invocations).
76    pub fn middleware(mut self, mw: impl crate::middleware::Middleware + 'static) -> Self {
77        self.middleware.add(Arc::new(mw));
78        self
79    }
80
81    /// Add a plugin to the runner.
82    pub fn plugin(mut self, plugin: impl Plugin + 'static) -> Self {
83        self.plugins.add(Arc::new(plugin));
84        self
85    }
86
87    /// Set initial state (available to all agents).
88    pub fn state(mut self, state: State) -> Self {
89        self.state = state;
90        self
91    }
92
93    /// Manually register an additional agent (useful for cross-tree transfers).
94    pub fn register(&mut self, agent: Arc<dyn Agent>) {
95        self.registry.register(agent);
96    }
97
98    /// Access the agent registry.
99    pub fn registry(&self) -> &AgentRegistry {
100        &self.registry
101    }
102
103    /// Access the root agent.
104    pub fn root_agent(&self) -> &dyn Agent {
105        self.root_agent.as_ref()
106    }
107
108    /// Run the agent lifecycle. Handles transfers automatically.
109    ///
110    /// `connect_fn` is a factory that creates a new AgentSession for a given agent.
111    /// This allows the Runner to reconnect with different configs on agent transfer
112    /// (different tools/instructions → different Gemini Live session).
113    ///
114    /// The Runner will:
115    /// 1. Call `connect_fn` with the current agent
116    /// 2. Run `agent.run_live()` on the resulting session
117    /// 3. If `TransferRequested` is returned, resolve the target agent,
118    ///    disconnect, preserve state, and loop back to step 1
119    /// 4. If the agent completes normally, return Ok(())
120    pub async fn run<F, Fut>(&self, connect_fn: F) -> Result<(), AgentError>
121    where
122        F: Fn(Arc<dyn Agent>) -> Fut + Send + Sync,
123        Fut: std::future::Future<Output = Result<AgentSession, AgentError>> + Send,
124    {
125        let mut current_agent = self.root_agent.clone();
126        let runner_state = self.state.clone();
127
128        // Telemetry
129        crate::telemetry::logging::log_agent_started(
130            current_agent.name(),
131            0, // runner doesn't have tools
132        );
133
134        loop {
135            // Connect with current agent's config
136            let agent_session = connect_fn(current_agent.clone()).await?;
137
138            // Merge runner state into session state
139            agent_session.state().merge(&runner_state);
140
141            // Create invocation context with runner's middleware
142            let mut ctx =
143                InvocationContext::with_middleware(agent_session.clone(), self.middleware.clone());
144
145            // Run before_run plugins
146            self.plugins.run_before_run(&ctx).await;
147
148            // Run the agent
149            match current_agent.run_live(&mut ctx).await {
150                Ok(()) => {
151                    // Run after_run plugins
152                    self.plugins.run_after_run(&ctx).await;
153                    // Agent completed normally — preserve state and return
154                    runner_state.merge(agent_session.state());
155                    break;
156                }
157                Err(AgentError::TransferRequested(target_name)) => {
158                    // Resolve target agent
159                    let target = self
160                        .registry
161                        .resolve(&target_name)
162                        .ok_or_else(|| AgentError::UnknownAgent(target_name.clone()))?;
163
164                    crate::telemetry::logging::log_agent_transfer(
165                        current_agent.name(),
166                        &target_name,
167                    );
168                    crate::telemetry::metrics::record_agent_transfer(
169                        current_agent.name(),
170                        &target_name,
171                    );
172
173                    // Preserve state across transfer
174                    runner_state.merge(agent_session.state());
175
176                    // Disconnect current session
177                    let _ = agent_session.disconnect().await;
178
179                    // Switch to target agent
180                    current_agent = target;
181                    continue;
182                }
183                Err(e) => {
184                    // Other error — preserve state and propagate
185                    runner_state.merge(agent_session.state());
186                    let _ = agent_session.disconnect().await;
187                    return Err(e);
188                }
189            }
190        }
191
192        Ok(())
193    }
194
195    /// Recursively register an agent and all its sub-agents.
196    fn register_tree(registry: &mut AgentRegistry, agent: Arc<dyn Agent>) {
197        registry.register(agent.clone());
198        for sub in agent.sub_agents() {
199            Self::register_tree(registry, sub);
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use crate::error::AgentError;
208    use crate::test_helpers::NoopAgent;
209    use async_trait::async_trait;
210    use gemini_genai_rs::session::{SessionHandle, SessionPhase, SessionState};
211    use std::sync::atomic::{AtomicU32, Ordering};
212    use tokio::sync::{broadcast, mpsc, watch};
213
214    // Mock agent that requests transfer
215    struct TransferAgent {
216        name: String,
217        target: String,
218    }
219
220    #[async_trait]
221    impl Agent for TransferAgent {
222        fn name(&self) -> &str {
223            &self.name
224        }
225        async fn run_live(&self, _ctx: &mut InvocationContext) -> Result<(), AgentError> {
226            Err(AgentError::TransferRequested(self.target.clone()))
227        }
228        fn sub_agents(&self) -> Vec<Arc<dyn Agent>> {
229            vec![]
230        }
231    }
232
233    // Mock agent that reads state
234    struct StateReaderAgent {
235        name: String,
236        key: String,
237        expected: String,
238    }
239
240    #[async_trait]
241    impl Agent for StateReaderAgent {
242        fn name(&self) -> &str {
243            &self.name
244        }
245        async fn run_live(&self, ctx: &mut InvocationContext) -> Result<(), AgentError> {
246            let val = ctx.state().get::<String>(&self.key);
247            assert_eq!(val.as_deref(), Some(self.expected.as_str()));
248            Ok(())
249        }
250    }
251
252    // Mock agent that fails
253    struct FailingAgent;
254
255    #[async_trait]
256    impl Agent for FailingAgent {
257        fn name(&self) -> &str {
258            "failing"
259        }
260        async fn run_live(&self, _ctx: &mut InvocationContext) -> Result<(), AgentError> {
261            Err(AgentError::Other("boom".to_string()))
262        }
263    }
264
265    fn mock_session_handle() -> SessionHandle {
266        let (cmd_tx, _cmd_rx) = mpsc::channel(16);
267        let (evt_tx, _) = broadcast::channel(16);
268        let (phase_tx, phase_rx) = watch::channel(SessionPhase::Active);
269        let state = Arc::new(SessionState::new(phase_tx));
270        SessionHandle::new(cmd_tx, evt_tx, state, phase_rx)
271    }
272
273    fn mock_agent_session() -> AgentSession {
274        AgentSession::new(mock_session_handle())
275    }
276
277    #[tokio::test]
278    async fn runner_runs_single_agent() {
279        let agent = NoopAgent {
280            name: "root".to_string(),
281        };
282        let runner = Runner::new(agent);
283
284        let result = runner
285            .run(|_agent| async { Ok(mock_agent_session()) })
286            .await;
287
288        assert!(result.is_ok());
289    }
290
291    #[tokio::test]
292    async fn runner_handles_transfer() {
293        // Root agent transfers to "target"
294        let target = Arc::new(NoopAgent {
295            name: "target".to_string(),
296        });
297        let root = TransferAgent {
298            name: "root".to_string(),
299            target: "target".to_string(),
300        };
301
302        let mut runner = Runner::new(root);
303        // Register the target agent manually since TransferAgent doesn't declare sub_agents
304        runner.register(target);
305
306        let connect_count = Arc::new(AtomicU32::new(0));
307        let count = connect_count.clone();
308
309        let result = runner
310            .run(move |_agent| {
311                let c = count.clone();
312                async move {
313                    c.fetch_add(1, Ordering::SeqCst);
314                    Ok(mock_agent_session())
315                }
316            })
317            .await;
318
319        assert!(result.is_ok());
320        // Should have connected twice: once for root, once for target
321        assert_eq!(connect_count.load(Ordering::SeqCst), 2);
322    }
323
324    #[tokio::test]
325    async fn runner_preserves_state_across_transfer() {
326        // Agent A sets state, transfers to B, B reads state
327        let agent_b = Arc::new(StateReaderAgent {
328            name: "agent_b".to_string(),
329            key: "greeting".to_string(),
330            expected: "hello from A".to_string(),
331        });
332
333        // Agent A: sets state, then transfers
334        struct SetAndTransferAgent;
335        #[async_trait]
336        impl Agent for SetAndTransferAgent {
337            fn name(&self) -> &str {
338                "agent_a"
339            }
340            async fn run_live(&self, ctx: &mut InvocationContext) -> Result<(), AgentError> {
341                let _ = ctx.state().set("greeting", "hello from A");
342                Err(AgentError::TransferRequested("agent_b".to_string()))
343            }
344        }
345
346        let mut runner = Runner::new(SetAndTransferAgent);
347        runner.register(agent_b);
348
349        let result = runner
350            .run(|_agent| async { Ok(mock_agent_session()) })
351            .await;
352
353        assert!(result.is_ok());
354    }
355
356    #[tokio::test]
357    async fn runner_fails_on_unknown_transfer_target() {
358        let root = TransferAgent {
359            name: "root".to_string(),
360            target: "nonexistent".to_string(),
361        };
362
363        let runner = Runner::new(root);
364
365        let result = runner
366            .run(|_agent| async { Ok(mock_agent_session()) })
367            .await;
368
369        match result {
370            Err(AgentError::UnknownAgent(name)) => assert_eq!(name, "nonexistent"),
371            other => panic!("expected UnknownAgent, got: {other:?}"),
372        }
373    }
374
375    #[tokio::test]
376    async fn runner_propagates_errors() {
377        let runner = Runner::new(FailingAgent);
378
379        let result = runner
380            .run(|_agent| async { Ok(mock_agent_session()) })
381            .await;
382
383        match result {
384            Err(AgentError::Other(msg)) => assert_eq!(msg, "boom"),
385            other => panic!("expected Other error, got: {other:?}"),
386        }
387    }
388
389    #[tokio::test]
390    async fn runner_with_initial_state() {
391        struct StateCheckAgent;
392        #[async_trait]
393        impl Agent for StateCheckAgent {
394            fn name(&self) -> &str {
395                "checker"
396            }
397            async fn run_live(&self, ctx: &mut InvocationContext) -> Result<(), AgentError> {
398                let val = ctx.state().get::<String>("initial_key");
399                assert_eq!(val.as_deref(), Some("initial_value"));
400                Ok(())
401            }
402        }
403
404        let initial_state = State::new();
405        let _ = initial_state.set("initial_key", "initial_value");
406
407        let runner = Runner::new(StateCheckAgent).state(initial_state);
408
409        let result = runner
410            .run(|_agent| async { Ok(mock_agent_session()) })
411            .await;
412
413        assert!(result.is_ok());
414    }
415
416    #[tokio::test]
417    async fn runner_auto_registers_sub_agents() {
418        struct ParentAgent;
419        #[async_trait]
420        impl Agent for ParentAgent {
421            fn name(&self) -> &str {
422                "parent"
423            }
424            async fn run_live(&self, _ctx: &mut InvocationContext) -> Result<(), AgentError> {
425                Ok(())
426            }
427            fn sub_agents(&self) -> Vec<Arc<dyn Agent>> {
428                vec![
429                    Arc::new(NoopAgent {
430                        name: "child_a".to_string(),
431                    }),
432                    Arc::new(NoopAgent {
433                        name: "child_b".to_string(),
434                    }),
435                ]
436            }
437        }
438
439        let runner = Runner::new(ParentAgent);
440        assert!(runner.registry().resolve("parent").is_some());
441        assert!(runner.registry().resolve("child_a").is_some());
442        assert!(runner.registry().resolve("child_b").is_some());
443    }
444}