Skip to main content

gadk_engine/runner/
live.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Live mode of the runner: [`Runner::run_live`], [`RunnerLiveSession`] and [`ClosedLiveSession`].
17
18use std::any::Any;
19use std::sync::Arc;
20
21use async_trait::async_trait;
22use futures::StreamExt;
23use gadk_agent::fiber::FiberStream;
24use gadk_agent::{
25    AgentError, EventStream, InvocationContext, LiveRequest, LiveRunConfig, LiveSession, RunConfig,
26    StreamingMode,
27};
28use gadk_model::LlmResponse;
29use gadk_session::{Event, Session};
30use tokio_util::sync::CancellationToken;
31
32use super::compaction::InvocationGuard;
33use super::{
34    ERR_USER_FUNCTION_CALL, RunOptions, Runner, RunnerInner, from_plugin, has_function_call,
35    stamp_timestamp, wrap,
36};
37
38impl Runner {
39    /// Starts a live (bidirectional streaming) run of the agent that should handle the session's
40    /// next turn. Returns the session to send input on and the event stream. Dropping the stream at
41    /// a yield runs the after-run callbacks first, on the still-live invocation context, and then
42    /// cancels the invocation; dropped inside an await, it cancels at once. The live session task
43    /// is detached rather than aborted, so a tool call already running finishes on its own (the
44    /// after-run callbacks do not wait for it).
45    ///
46    /// Must be called inside a Tokio runtime: the live flow spawns tasks. `opts` is accepted for
47    /// symmetry with [`Runner::run`] and not applied.
48    ///
49    /// The returned stream runs on the consumer's fiber ([`FiberStream::consumer`]); this
50    /// function's own work (session lookup, before-run callbacks, starting the live flow) runs in
51    /// the caller's future.
52    pub async fn run_live(
53        &self,
54        user_id: &str,
55        session_id: &str,
56        cfg: LiveRunConfig,
57        opts: RunOptions,
58    ) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
59        // Live runs read none of the run options.
60        let _ = opts;
61        let this = self.inner.clone();
62        let stored = this.get_or_create_session(user_id, session_id).await?;
63        let agent_to_run = this.find_agent_to_run(&*stored, None)?;
64        let Some(live) = agent_to_run.as_live() else {
65            return Err(AgentError::other(format!(
66                "agent {} does not support Live Run",
67                agent_to_run.name()
68            )));
69        };
70
71        // Live is always bidirectional streaming.
72        let run_cfg = RunConfig {
73            streaming_mode: StreamingMode::Bidi,
74            live: Some(cfg),
75            ..Default::default()
76        };
77        let token = CancellationToken::new();
78        // Live runs attach no compaction runtime.
79        let ictx = this.new_invocation_context(
80            &stored,
81            agent_to_run.clone(),
82            None,
83            &run_cfg,
84            &token,
85            false,
86            // `run_live` takes no caller context, so there is no plugin-inheritance mark.
87            this.with_plugin_manager(None),
88            // No invocation ID or branch.
89            String::new(),
90            String::new(),
91        );
92
93        // The before-run reply goes through on_event (and is stamped and persisted) as on
94        // Runner::run, and the run through the after-run callbacks.
95        if let Some(event) = this.run_before_run_callback(&ictx).await? {
96            let stream = FiberStream::consumer(early_exit_stream(
97                this.clone(),
98                ictx.clone(),
99                stored.clone(),
100                event,
101                token,
102            ))
103            .boxed();
104            return Ok((Arc::new(ClosedLiveSession), stream));
105        }
106
107        let (agent_sess, inner) = live.run_live(ictx.clone()).await?;
108        let stream = FiberStream::consumer(wrap_live_stream(
109            this.clone(),
110            ictx.clone(),
111            stored.clone(),
112            inner,
113            token,
114        ))
115        .boxed();
116        let session: Arc<dyn LiveSession> = Arc::new(RunnerLiveSession {
117            sess: agent_sess,
118            runner: this,
119            ctx: ictx,
120            stored,
121        });
122        Ok((session, stream))
123    }
124}
125
126/// The stream for a before-run early exit: yields the before-run reply, then runs the after-run
127/// callbacks (deferred: also when the consumer drops the stream at the yield).
128fn early_exit_stream(
129    this: Arc<RunnerInner>,
130    ctx: InvocationContext,
131    stored: Arc<dyn Session>,
132    event: Event,
133    token: CancellationToken,
134) -> EventStream {
135    let cancel_on_drop = token.drop_guard();
136    Box::pin(async_stream::stream! {
137        let mut guard = InvocationGuard::new(this, stored, ctx);
138        guard.cancel_on_drop(cancel_on_drop);
139        guard.no_compaction();
140        guard.defer_after_run();
141        guard.at_yield(true);
142        yield Ok(event);
143        guard.at_yield(false);
144        guard.finish().await;
145    })
146}
147
148/// Wraps the live flow's stream: plugin `on_event`, chronological buffering of tool calls and
149/// responses while a transcription is in progress, persistence of non-partial events without inline
150/// data, and the EOF flush of buffered events.
151///
152/// An [`InvocationGuard`] without compaction (live runs do not compact) owns the deferred after-run
153/// callbacks and the invocation token's cancel-on-drop: a consumer that drops the stream at a yield
154/// gets the after-run callbacks on its fiber before the token is cancelled; a drop inside an await
155/// cancels at once.
156fn wrap_live_stream(
157    this: Arc<RunnerInner>,
158    ctx: InvocationContext,
159    stored: Arc<dyn Session>,
160    mut inner: EventStream,
161    token: CancellationToken,
162) -> EventStream {
163    // Dropping the stream cancels the invocation, which stops the live flow. The drop guard is
164    // made here, not on first poll, so a stream dropped before it is ever polled cancels too.
165    let cancel_on_drop = token.drop_guard();
166    Box::pin(async_stream::stream! {
167        // Made at the first poll, inside the consumer's fiber, which its `Drop` re-enters.
168        let mut guard = InvocationGuard::new(this.clone(), stored.clone(), ctx.clone());
169        guard.cancel_on_drop(cancel_on_drop);
170        guard.no_compaction();
171        // The after-run callbacks run once when the stream ends, or (spawned) when the consumer
172        // drops it early.
173        guard.defer_after_run();
174        let mut buffered: Vec<Event> = Vec::new();
175        let mut is_transcribing = false;
176
177        while let Some(item) = inner.next().await {
178            let mut event = match item {
179                Ok(ev) => ev,
180                Err(e) => {
181                    guard.at_yield(true);
182                    yield Err(e);
183                    guard.at_yield(false);
184                    continue;
185                }
186            };
187            stamp_timestamp(&ctx, &mut event);
188
189            if !event.response.partial
190                && event.node_info.as_ref().is_some_and(|n| n.message_as_output)
191                && event.response.content.is_some()
192            {
193                event.output = None;
194            }
195
196            let record = event.actions.compaction.clone();
197            match this.plugin_manager.run_on_event(ctx.clone(), event.clone()).await {
198                Err(e) => {
199                    guard.at_yield(true);
200                    yield Err(e);
201                    guard.at_yield(false);
202                    continue;
203                }
204                Ok(modified) => event = from_plugin(event, modified, record),
205            }
206            // A plugin may have handed back an event without a timestamp.
207            stamp_timestamp(&ctx, &mut event);
208
209            let has_transcription = event.response.input_transcription.is_some()
210                || event.response.output_transcription.is_some();
211            if event.response.partial && has_transcription {
212                is_transcribing = true;
213            }
214
215            // Tool calls and responses that arrive mid-transcription wait for it, so the
216            // session records them after the transcription they interrupted.
217            if is_transcribing && is_tool_call_or_response(&event) {
218                buffered.push(event);
219                continue;
220            }
221
222            if !event.response.partial && has_transcription {
223                is_transcribing = false;
224                if let Err(e) = this.session_service.append_event(&*stored, &mut event).await {
225                    guard.at_yield(true);
226                    yield Err(wrap("failed to add event to session", e));
227                    guard.at_yield(false);
228                    continue;
229                }
230                guard.at_yield(true);
231                yield Ok(event);
232                guard.at_yield(false);
233                for mut buffered_event in std::mem::take(&mut buffered) {
234                    if let Err(e) = this
235                        .session_service
236                        .append_event(&*stored, &mut buffered_event)
237                        .await
238                    {
239                        guard.at_yield(true);
240                        yield Err(wrap("failed to add event to session", e));
241                        guard.at_yield(false);
242                        continue;
243                    }
244                    guard.at_yield(true);
245                    yield Ok(buffered_event);
246                    guard.at_yield(false);
247                }
248                continue;
249            }
250
251            if !event.response.partial
252                && !has_inline_data(&event)
253                && let Err(e) = this.session_service.append_event(&*stored, &mut event).await
254            {
255                guard.at_yield(true);
256                yield Err(wrap("failed to add event to session", e));
257                guard.at_yield(false);
258                continue;
259            }
260            guard.at_yield(true);
261            yield Ok(event);
262            guard.at_yield(false);
263        }
264
265        // EOF: flush what is still buffered. An append takes no context, so a cancelled invocation
266        // cannot cut the flush short. Reaching this point means the consumer is still reading: a
267        // dropped stream never resumes.
268        for mut buffered_event in std::mem::take(&mut buffered) {
269            if let Err(e) = this
270                .session_service
271                .append_event(&*stored, &mut buffered_event)
272                .await
273            {
274                guard.at_yield(true);
275                yield Err(wrap("failed to add event to session", e));
276                guard.at_yield(false);
277                continue;
278            }
279            guard.at_yield(true);
280            yield Ok(buffered_event);
281            guard.at_yield(false);
282        }
283
284        guard.finish().await;
285    })
286}
287
288/// Whether the event's content has a function call or a function response part.
289fn is_tool_call_or_response(event: &Event) -> bool {
290    event.response.content.as_ref().is_some_and(|c| {
291        c.parts
292            .iter()
293            .any(|p| p.function_call.is_some() || p.function_response.is_some())
294    })
295}
296
297/// Whether any part of the event's content carries inline data.
298fn has_inline_data(event: &Event) -> bool {
299    event
300        .response
301        .content
302        .as_ref()
303        .is_some_and(|c| c.parts.iter().any(|p| p.inline_data.is_some()))
304}
305
306/// Forwards to the agent's live session and persists the user's non-function-response content.
307pub(crate) struct RunnerLiveSession {
308    sess: Arc<dyn LiveSession>,
309    runner: Arc<RunnerInner>,
310    ctx: InvocationContext,
311    stored: Arc<dyn Session>,
312}
313
314#[async_trait]
315impl LiveSession for RunnerLiveSession {
316    /// Forwards the request unchanged; a request carrying a function call is refused.
317    async fn send(&self, req: LiveRequest) -> Result<(), AgentError> {
318        // Refused before anything is forwarded or stored.
319        if has_function_call(req.content.as_ref()) {
320            return Err(AgentError::other(ERR_USER_FUNCTION_CALL));
321        }
322        let content = req.content.clone();
323        self.sess.send(req).await?;
324
325        if let Some(content) = content
326            && !content.parts.is_empty()
327            && !content.parts.iter().any(|p| p.function_response.is_some())
328        {
329            let mut event = Event::new(self.ctx.platform(), self.ctx.invocation_id());
330            event.author = "user".to_string();
331            event.response = LlmResponse {
332                content: Some(content),
333                ..Default::default()
334            };
335            self.runner
336                .session_service
337                .append_event(&*self.stored, &mut event)
338                .await
339                .map_err(|e| wrap("failed to add user event to session", e))?;
340        }
341        Ok(())
342    }
343
344    async fn close(&self) -> Result<(), AgentError> {
345        self.sess.close().await
346    }
347
348    fn as_any(&self) -> &dyn Any {
349        self
350    }
351}
352
353/// The session returned by a before-run early exit.
354pub(crate) struct ClosedLiveSession;
355
356#[async_trait]
357impl LiveSession for ClosedLiveSession {
358    async fn send(&self, _req: LiveRequest) -> Result<(), AgentError> {
359        Err(AgentError::other("session is closed"))
360    }
361
362    async fn close(&self) -> Result<(), AgentError> {
363        Ok(())
364    }
365
366    fn as_any(&self) -> &dyn Any {
367        self
368    }
369}
370
371#[cfg(test)]
372#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
373mod tests {
374    use std::sync::atomic::{AtomicBool, Ordering};
375
376    use gadk_agent::{AgentConfig, Plugin};
377    use gadk_genai::Content;
378    use gadk_platform::Platform;
379    use gadk_session::InMemorySessionService;
380
381    use super::*;
382    use crate::runner::{PluginConfig, RunnerConfig};
383
384    /// R12: an agent without live support fails before any plugin runs.
385    #[tokio::test]
386    async fn run_live_rejects_agent_without_live_support_before_plugins() {
387        let before_run = Arc::new(AtomicBool::new(false));
388        let flag = before_run.clone();
389        let plugin = Plugin::new(gadk_agent::PluginConfig {
390            name: "p".into(),
391            before_run_callback: Some(Arc::new(move |_ctx| {
392                flag.store(true, Ordering::SeqCst);
393                Box::pin(async { Ok::<Option<Content>, AgentError>(None) })
394            })),
395            ..Default::default()
396        });
397        let agent = gadk_agent::agent::new(AgentConfig {
398            name: "plain".into(),
399            ..Default::default()
400        })
401        .unwrap();
402        let runner = Runner::new(RunnerConfig {
403            app_name: "app".into(),
404            agent,
405            session_service: Arc::new(InMemorySessionService::new()),
406            artifact_service: None,
407            memory_service: None,
408            plugin_config: PluginConfig {
409                plugins: vec![plugin],
410                ..Default::default()
411            },
412            auto_create_session: true,
413            platform: Platform::default(),
414            compaction: None,
415        })
416        .unwrap();
417        let err = runner
418            .run_live("u", "s", LiveRunConfig::default(), RunOptions::default())
419            .await
420            .err()
421            .expect("run_live must fail");
422        assert_eq!(err.to_string(), "agent plain does not support Live Run");
423        assert!(
424            !before_run.load(Ordering::SeqCst),
425            "no plugin may run first"
426        );
427    }
428
429    #[tokio::test]
430    async fn closed_live_session_rejects_send() {
431        let err = ClosedLiveSession
432            .send(LiveRequest::default())
433            .await
434            .expect_err("send must fail");
435        assert_eq!(err.to_string(), "session is closed");
436        ClosedLiveSession.close().await.unwrap();
437    }
438
439    /// Records the invocation's cancellation token and yields nothing.
440    struct TokenCapture(Arc<parking_lot::Mutex<Option<CancellationToken>>>);
441
442    #[async_trait]
443    impl gadk_agent::LiveAgent for TokenCapture {
444        async fn run_live(
445            &self,
446            ctx: InvocationContext,
447        ) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
448            *self.0.lock() = Some(ctx.cancellation_token().clone());
449            Ok((
450                Arc::new(ClosedLiveSession),
451                futures::stream::pending().boxed(),
452            ))
453        }
454    }
455
456    /// Dropping the returned stream cancels the invocation, even if it was never polled.
457    #[tokio::test]
458    async fn dropping_unpolled_stream_cancels_invocation() {
459        let captured = Arc::new(parking_lot::Mutex::new(None));
460        let agent = gadk_agent::new_with_state(
461            AgentConfig {
462                name: "live".into(),
463                ..Default::default()
464            },
465            gadk_agent::AgentState {
466                agent_type: gadk_agent::AgentType::CustomAgent,
467                config: None,
468                on_before_agent_callback_event: None,
469                live: Some(Arc::new(TokenCapture(captured.clone()))),
470            },
471        )
472        .unwrap();
473        let runner = Runner::new(RunnerConfig {
474            app_name: "app".into(),
475            agent,
476            session_service: Arc::new(InMemorySessionService::new()),
477            artifact_service: None,
478            memory_service: None,
479            plugin_config: PluginConfig::default(),
480            auto_create_session: true,
481            platform: Platform::default(),
482            compaction: None,
483        })
484        .unwrap();
485        let (_sess, stream) = runner
486            .run_live("u", "s", LiveRunConfig::default(), RunOptions::default())
487            .await
488            .unwrap();
489        let token = captured.lock().clone().expect("run_live was called");
490        assert!(!token.is_cancelled());
491        drop(stream);
492        assert!(token.is_cancelled(), "dropping the stream must cancel");
493    }
494}