gadk-engine 0.5.8

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The live (bidi) flow, `run_live`. The
//! session task preprocesses the request, connects, and runs the connect/reconnect loop; each
//! connection has a reader task and a sender task feeding one consumer loop.

use std::collections::{HashMap, VecDeque};
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use futures::StreamExt;
use gadk_agent::fiber::{self, LIVE_SESSION_CREATOR};
use gadk_agent::{
    AgentError, EventStream, InvocationContext, LiveRequest, LiveRunConfig, LiveSession, Tool,
};
use gadk_genai::{LiveConnectConfig, SessionResumptionConfig};
use gadk_model::{
    Backend, LiveConnError, LiveConnection, Llm, LlmRequest, LlmResponse, ModelError,
    RealtimeInput, is_gemini_3x_live,
};
use gadk_session::Event;
use tokio::sync::mpsc;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;

use crate::llm::flow::{Flow, find_long_running_function_call_ids};
use crate::llm::functions::handle_function_calls_live;
use crate::llm::live::reconnect::{live_reconnect_gave_up_error, wait_before_reconnect};
use crate::llm::live::session::LiveSessionImpl;
use crate::tool::utils::function_calls;

/// Error text when the model has no live connection support.
pub(crate) const ERR_MODEL_DOES_NOT_SUPPORT_LIVE: &str = "model does not support live connection";
/// Error text when the run config has no live settings.
pub(crate) const ERR_LIVE_RUN_CONFIG_NOT_FOUND: &str = "live run config not found";
/// The function whose response ends the live flow (injected by SequentialAgent::run_live).
const TASK_COMPLETED: &str = "task_completed";
/// Grace period before ending on task_completed.
const TASK_COMPLETED_GRACE: Duration = Duration::from_millis(100);
/// Upper bound on closing a connection during cleanup (a wedged write cannot stall teardown).
const CLOSE_TIMEOUT: Duration = Duration::from_secs(1);

/// What a connection's reader and sender report to the consumer loop (events and errors).
/// `Event` is boxed (clippy::large_enum_variant), as runner/mod.rs `Processed::Event(Box<Event>)` does.
enum ConnMsg {
    Event(Box<Event>),
    /// The failure and when it was produced.
    Error(LiveConnError, Instant),
}

/// How the consumer loop for one connection ended.
enum Outcome {
    /// The session is over (error reported, closed, cancelled, or task_completed).
    Stop,
    /// A resumable error: dial again.
    Reconnect,
}

/// "failed to connect live session: <cause>" for the first dial.
#[derive(Debug)]
struct LiveConnectFailed(ModelError);

impl fmt::Display for LiveConnectFailed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to connect live session: {}", self.0)
    }
}

impl Error for LiveConnectFailed {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.0)
    }
}

fn conn_err(err: LiveConnError) -> AgentError {
    AgentError::Other(Box::new(err))
}

/// Closes the session, and once the session task ends no streaming tool outlives
/// the flow. A drop guard rather than trailing code, so it also runs if the task is dropped
/// unfinished (a runtime shutting down). A tool task still running on another worker can
/// register a streaming tool after the drain; `done` is cancelled before the drain so that
/// `start_live_streaming`, which checks it after registering, cancels such a late tool.
/// Equivalent to `LiveSession::close`, which is async only for the trait.
struct Teardown(Arc<LiveSessionImpl>);

impl Drop for Teardown {
    fn drop(&mut self) {
        self.0.done().cancel();
        self.0.cancel_every_streaming_tool();
        self.0.probe().teardowns.fetch_add(1, Ordering::SeqCst);
    }
}

/// Starts the live flow. Returns at once; the work runs on a spawned session task, so this
/// must be called inside a tokio runtime. Dropping the returned stream cancels the session.
pub(crate) fn run_live(
    flow: Arc<Flow>,
    ctx: InvocationContext,
) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
    // The model must be a live-capable model before anything else.
    let Some(model) = flow.model.clone() else {
        return Err(AgentError::other(ERR_MODEL_DOES_NOT_SUPPORT_LIVE));
    };
    let Some(live_cfg) = ctx.run_config().live.clone() else {
        return Err(AgentError::other(ERR_LIVE_RUN_CONFIG_NOT_FOUND));
    };

    let sess = LiveSessionImpl::new();
    let guard = sess.probe().task_guard();
    let task_sess = sess.clone();
    // The session work runs on a new task: a fresh fiber
    // started by this spawn site, child of the caller's.
    let task = tokio::spawn(fiber::spawn_child(LIVE_SESSION_CREATOR).scope(async move {
        let _guard = guard;
        // Declared after `_guard`, so it runs first; see `Teardown`.
        let _teardown = Teardown(task_sess.clone());
        session_task(flow, model, ctx, live_cfg, task_sess).await;
    }));
    let stream = sess.event_stream(Some(task));
    let sess: Arc<dyn LiveSession> = sess;
    Ok((sess, stream))
}

/// The session task: preprocesses the request, connects, and runs the connect/reconnect loop.
async fn session_task(
    flow: Arc<Flow>,
    model: Arc<dyn Llm>,
    ctx: InvocationContext,
    live_cfg: LiveRunConfig,
    sess: Arc<LiveSessionImpl>,
) {
    let mut req = LlmRequest {
        model: model.name().to_owned(),
        ..Default::default()
    };
    {
        let mut pre = flow.preprocess(&ctx, &mut req);
        while let Some(item) = pre.next().await {
            match item {
                Err(e) => {
                    sess.push_error(e).await;
                    return;
                }
                Ok(ev) => {
                    if !sess.push_event(ev).await {
                        return;
                    }
                }
            }
        }
    }

    // Exactly these fields are copied from the run config.
    let gen_cfg = req.config.clone().unwrap_or_default();
    let mut connect_cfg = LiveConnectConfig {
        response_modalities: live_cfg.response_modalities.clone(),
        speech_config: live_cfg.speech_config.clone(),
        system_instruction: gen_cfg.system_instruction,
        tools: gen_cfg.tools,
        session_resumption: live_cfg.session_resumption.clone(),
        input_audio_transcription: live_cfg.input_audio_transcription.clone(),
        output_audio_transcription: live_cfg.output_audio_transcription.clone(),
        realtime_input_config: live_cfg.realtime_input_config.clone(),
        ..Default::default()
    };
    // Affective dialog and proactivity stay unset for the models
    // `is_gemini_3x_live` matches (affective dialog is not supported on them; proactive audio is
    // always on or not supported). Live Translate is excluded by it and still gets both.
    if !is_gemini_3x_live(model.name()) {
        if live_cfg.enable_affective_dialog {
            connect_cfg.enable_affective_dialog = Some(true);
        }
        connect_cfg.proactivity = live_cfg.proactivity.clone();
    }

    let policy = flow.live_reconnect.clone().unwrap_or_default();
    let ctx_token = ctx.cancellation_token().clone();
    // reconnect_attempts counts consecutive reconnects since a connection last worked (content,
    // or outliving healthy_uptime) and drives the backoff; short_lived counts only connections
    // that died inside healthy_uptime and never resets.
    let mut reconnect_attempts = 0usize;
    let mut short_lived = 0usize;
    let mut current_backoff = policy.initial_backoff;
    let mut last_conn_was_brief = false;
    let mut last_err: Option<Box<dyn Error + Send + Sync>> = None;
    // False only for the very first dial: a first-ever connect failure is fatal, a failed redial
    // is charged to the budget.
    let mut is_reconnect = false;

    loop {
        if is_reconnect {
            reconnect_attempts += 1;
            if last_conn_was_brief {
                short_lived += 1;
            }
            if reconnect_attempts > policy.max_attempts {
                // Resumable errors are swallowed while retrying, so without this the caller's
                // stream just goes quiet.
                sess.push_error(live_reconnect_gave_up_error(
                    format!(
                        "{} consecutive attempts delivered no content",
                        policy.max_attempts
                    ),
                    last_err.take(),
                ))
                .await;
                return;
            }
            if short_lived > policy.max_total {
                sess.push_error(live_reconnect_gave_up_error(
                    format!(
                        "{} short-lived connections in one invocation",
                        policy.max_total
                    ),
                    last_err.take(),
                ))
                .await;
                return;
            }
            let sleep = policy.jittered(current_backoff);
            current_backoff = policy.next_backoff(current_backoff);
            tracing::warn!(
                attempt = reconnect_attempts,
                max_attempts = policy.max_attempts,
                short_lived,
                delay = ?sleep,
                "live session: reconnect attempt"
            );
            if !wait_before_reconnect(&ctx_token, &sess, sleep).await {
                // Cancellation reports itself; close() is a clean teardown.
                if ctx_token.is_cancelled() {
                    sess.push_error(AgentError::Cancelled).await;
                }
                return;
            }
        }

        let handle = ctx.live_session_resumption_handle();
        if !handle.is_empty() {
            let sr = connect_cfg
                .session_resumption
                .get_or_insert_with(SessionResumptionConfig::default);
            sr.handle = handle;
            if model.google_variant() == Some(Backend::VertexAi) {
                sr.transparent = true;
            }
        }
        if let Some(sr) = &connect_cfg.session_resumption {
            tracing::debug!(handle = %sr.handle, "connecting with live session handle");
        }

        // The connection's cancellation token.
        let conn_token = ctx_token.child_token();
        let connected = tokio::select! {
            r = model.connect_live(connect_cfg.clone()) => r,
            _ = sess.done().cancelled() => return,
            _ = ctx_token.cancelled() => {
                sess.push_error(AgentError::Cancelled).await;
                return;
            }
        };
        let conn: Arc<dyn LiveConnection> = match connected {
            Ok(c) => Arc::from(c),
            Err(err) => {
                conn_token.cancel();
                tracing::warn!(error = %err, "failed to connect live session");
                if is_reconnect {
                    last_err = Some(Box::new(err));
                    last_conn_was_brief = true;
                    continue;
                }
                sess.push_error(AgentError::Other(Box::new(LiveConnectFailed(err))))
                    .await;
                return;
            }
        };
        let connected_at = Instant::now();

        // Send the preprocessed contents as history, if any.
        if !req.contents.is_empty()
            && let Err(e) = conn.send_history(&req.contents).await
        {
            tracing::warn!(error = %e, "failed to send history");
            // Close the connection before reporting.
            conn_token.cancel();
            let _ = tokio::time::timeout(CLOSE_TIMEOUT, conn.close()).await;
            sess.push_error(conn_err(e)).await;
            return;
        }

        // A function response awaiting delivery to the model, queued on the
        // session's input channel so the sender task is the connection's only writer (a write
        // from this loop could overtake user input queued there). While one is pending, the
        // events that arrive are held in order; errors are handled at once.
        let mut pending_send: Option<LiveRequest> = None;
        let mut held: VecDeque<Box<Event>> = VecDeque::new();

        let (tx, mut rx) = mpsc::channel::<ConnMsg>(1);
        let mut tasks = JoinSet::new();
        tasks.spawn(reader(
            conn.clone(),
            conn_token.clone(),
            tx.clone(),
            ctx.clone(),
            sess.clone(),
            live_cfg.save_live_blob,
        ));
        tasks.spawn(sender(
            conn.clone(),
            conn_token.clone(),
            tx,
            ctx.clone(),
            sess.clone(),
        ));

        let outcome = 'consume: loop {
            let held_ev = if pending_send.is_none() {
                held.pop_front()
            } else {
                None
            };
            let msg = match held_ev {
                Some(ev) => Some(ConnMsg::Event(ev)),
                None => tokio::select! {
                    queued = queue_pending(&sess, pending_send.clone()) => {
                        if !queued {
                            break 'consume Outcome::Stop;
                        }
                        pending_send = None;
                        continue 'consume;
                    }
                    m = rx.recv() => m,
                    _ = sess.done().cancelled() => break 'consume Outcome::Stop,
                    _ = ctx_token.cancelled() => {
                        sess.push_error(AgentError::Cancelled).await;
                        break 'consume Outcome::Stop;
                    }
                },
            };
            match msg {
                Some(ConnMsg::Event(ev)) if pending_send.is_some() => held.push_back(ev),
                Some(ConnMsg::Event(ev)) => {
                    let mut ev = *ev;
                    let has_calls = !function_calls(ev.response.content.as_ref()).is_empty();
                    let mut tools: HashMap<String, Arc<dyn Tool>> = HashMap::new();
                    if has_calls {
                        for t in flow.tools.read().iter() {
                            tools.insert(t.name().to_owned(), t.clone());
                        }
                        ev.long_running_tool_ids = find_long_running_function_call_ids(
                            ev.response.content.as_ref(),
                            &tools,
                        );
                    }
                    let has_content = ev.response.content.is_some();
                    let interrupted = ev.response.interrupted;
                    let turn_complete = ev.response.turn_complete;
                    let call_ev = has_calls.then(|| ev.clone());
                    if !sess.push_event(ev).await {
                        break 'consume Outcome::Stop;
                    }
                    // Content proves the connection is serving: the consecutive budget starts
                    // over (short_lived does not).
                    if has_content {
                        reconnect_attempts = 0;
                        current_backoff = policy.initial_backoff;
                    }
                    // flush_caches is snapshot-then-drain, so it must have one caller at a time:
                    // this consumer loop is the only one.
                    if live_cfg.save_live_blob {
                        let flush_model = interrupted || turn_complete;
                        let flush_user = turn_complete;
                        if flush_user || flush_model {
                            match sess
                                .audio()
                                .flush_caches(&ctx, flush_user, flush_model)
                                .await
                            {
                                Err(e) => {
                                    sess.push_error(e).await;
                                    break 'consume Outcome::Stop;
                                }
                                Ok(flushed) => {
                                    for fev in flushed {
                                        if !sess.push_event(fev).await {
                                            break 'consume Outcome::Stop;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if let Some(call_ev) = call_ev {
                        // Once the session is closed, start no tool: a streaming tool registered
                        // now could miss close()'s cancellation. Every later push would be
                        // refused anyway.
                        if sess.done().is_cancelled() {
                            break 'consume Outcome::Stop;
                        }
                        let live: Arc<dyn LiveSession> = sess.clone();
                        match handle_function_calls_live(&ctx, &flow, &tools, &call_ev, live).await
                        {
                            Err(e) => {
                                sess.push_error(e).await;
                                break 'consume Outcome::Stop;
                            }
                            Ok(None) => {}
                            Ok(Some(resp_ev)) => {
                                let content = resp_ev.response.content.clone();
                                if !sess.push_event(resp_ev).await {
                                    break 'consume Outcome::Stop;
                                }
                                let task_completed = content.as_ref().is_some_and(|c| {
                                    c.parts.iter().any(|p| {
                                        p.function_response
                                            .as_ref()
                                            .is_some_and(|fr| fr.name == TASK_COMPLETED)
                                    })
                                });
                                if task_completed {
                                    tokio::time::sleep(TASK_COMPLETED_GRACE).await;
                                    break 'consume Outcome::Stop;
                                }
                                // Queue the function response for the sender task, the
                                // connection's only writer.
                                if let Some(c) = content {
                                    pending_send = Some(LiveRequest {
                                        content: Some(c),
                                        realtime_input: None,
                                    });
                                }
                            }
                        }
                    }
                }
                Some(ConnMsg::Error(err, at)) => {
                    if err.is_resumable() {
                        tracing::warn!(error = %err, "live connection error, attempting to resume");
                        // Score the connection's life from where the error was produced, not
                        // from here (this loop also runs tools and blocks on the caller).
                        last_conn_was_brief =
                            at.saturating_duration_since(connected_at) < policy.healthy_uptime;
                        if !last_conn_was_brief {
                            // Served as long as a healthy connection: routine cycling spends
                            // neither budget and clears the consecutive one.
                            reconnect_attempts = 0;
                            current_backoff = policy.initial_backoff;
                        }
                        last_err = Some(Box::new(err));
                        break 'consume Outcome::Reconnect;
                    }
                    sess.push_error(conn_err(err)).await;
                    break 'consume Outcome::Stop;
                }
                // Both tasks gone without a report: only after the connection was torn down.
                None => break 'consume Outcome::Stop,
            }
        };

        // Cleanup before ending or reconnecting.
        conn_token.cancel();
        let _ = tokio::time::timeout(CLOSE_TIMEOUT, conn.close()).await;
        tasks.shutdown().await;

        match outcome {
            Outcome::Stop => return,
            Outcome::Reconnect => is_reconnect = true,
        }
    }
}

/// Queues `req` on the session's input channel for the sender task;
/// never completes without a request, so a select branch over it stays idle. `false` once the
/// session is done.
async fn queue_pending(sess: &LiveSessionImpl, req: Option<LiveRequest>) -> bool {
    match req {
        Some(req) => sess.queue_input(req).await,
        None => std::future::pending().await,
    }
}

/// Whether `r` carries nothing worth an event,
/// as the response built from the Live API's setupComplete does. adk-python's live flow skips
/// the same responses.
pub(crate) fn is_empty_live_response(r: &LlmResponse) -> bool {
    r.content.is_none()
        && r.error_code.is_empty()
        && !r.interrupted
        && !r.turn_complete
        && r.input_transcription.is_none()
        && r.output_transcription.is_none()
        && r.usage_metadata.is_none()
        && r.session_resumption_handle.is_empty()
        && r.grounding_metadata.is_none()
}

/// Reports `err` to the consumer, stamped now; gives up when the connection is torn down.
async fn report(token: &CancellationToken, tx: &mpsc::Sender<ConnMsg>, err: LiveConnError) {
    let at = Instant::now();
    tokio::select! {
        _ = token.cancelled() => {}
        _ = tx.send(ConnMsg::Error(err, at)) => {}
    }
}

/// The reader task: reads responses from the model connection.
async fn reader(
    conn: Arc<dyn LiveConnection>,
    token: CancellationToken,
    tx: mpsc::Sender<ConnMsg>,
    ctx: InvocationContext,
    sess: Arc<LiveSessionImpl>,
    save_live_blob: bool,
) {
    let _guard = sess.probe().task_guard();
    loop {
        let res = tokio::select! {
            _ = token.cancelled() => return,
            r = conn.recv() => r,
        };
        let resp = match res {
            Ok(Some(r)) => r,
            // The stream ended without a close frame: end of stream.
            Ok(None) => {
                report(&token, &tx, LiveConnError::eof()).await;
                return;
            }
            Err(e) => {
                report(&token, &tx, e).await;
                return;
            }
        };
        if !resp.session_resumption_handle.is_empty() {
            tracing::debug!(handle = %resp.session_resumption_handle, "received session resumption handle");
            ctx.set_live_session_resumption_handle(&resp.session_resumption_handle);
        }
        if save_live_blob && let Some(content) = &resp.content {
            for part in &content.parts {
                if let Some(blob) = &part.inline_data {
                    sess.audio()
                        .cache_output(ctx.platform(), &blob.data, &blob.mime_type);
                }
            }
        }
        if is_empty_live_response(&resp) {
            continue;
        }
        // Author and response only (no branch).
        let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
        ev.author = ctx.agent().name().to_owned();
        ev.response = resp;
        tokio::select! {
            _ = token.cancelled() => return,
            r = tx.send(ConnMsg::Event(Box::new(ev))) => if r.is_err() { return; },
        }
    }
}

/// The sender task: sends requests to the model connection.
///
/// `next_input` acknowledges a request when it takes it, so a caller that abandons its
/// `LiveSession::send` future after the request was queued (for example a streaming tool whose
/// token was cancelled mid-send) still has it delivered by whichever connection's sender takes it.
/// A taken request is lost only if its write fails.
async fn sender(
    conn: Arc<dyn LiveConnection>,
    token: CancellationToken,
    tx: mpsc::Sender<ConnMsg>,
    ctx: InvocationContext,
    sess: Arc<LiveSessionImpl>,
) {
    let _guard = sess.probe().task_guard();
    while let Some(req) = sess.next_input(&token).await {
        if let Some(content) = req.content {
            let sent = tokio::select! {
                _ = token.cancelled() => return,
                r = conn.send_content(content) => r,
            };
            if let Err(e) = sent {
                report(&token, &tx, e).await;
                return;
            }
        }
        if let Some(input) = req.realtime_input {
            // Input audio is always cached.
            if let RealtimeInput::Blob(blob) = &input {
                sess.audio()
                    .cache_input(ctx.platform(), &blob.data, &blob.mime_type);
            }
            let sent = tokio::select! {
                _ = token.cancelled() => return,
                r = conn.send_realtime(input) => r,
            };
            if let Err(e) = sent {
                report(&token, &tx, e).await;
                return;
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use std::any::Any;
    use std::sync::{Mutex, OnceLock};

    use futures::stream::BoxStream;
    use gadk_agent::{Context, StreamingTool, ToolError};
    use serde_json::Value;
    use tokio::sync::oneshot;

    use super::*;
    use crate::llm::flow::RequestProcessor;
    use crate::llm::live::test_server::{
        FakeConn, FakeLiveServer, assert_no_run_live_leak, live_config_processor, live_ctx,
        probe_of, serve,
    };

    const NEVER_CALL: &str =
        r#"{"toolCall":{"functionCalls":[{"id":"never_1","name":"never_yields","args":{}}]}}"#;

    /// A streaming tool that never yields. Its first `as_streaming` (made by the tool-call task,
    /// right before `start_live_streaming` registers it, with no await in between) reports that
    /// the tool is starting, then blocks its worker until the event stream has been dropped
    /// (`done` cancelled): the tool registers after the session was closed. The session task is
    /// not aborted (Go's goroutine finishes the call), so it is its teardown that must cancel it.
    struct NeverYields {
        dropped: OnceLock<CancellationToken>,
        entered: Mutex<Option<oneshot::Sender<()>>>,
    }

    impl Tool for NeverYields {
        fn name(&self) -> &str {
            "never_yields"
        }
        fn description(&self) -> &str {
            "never yields"
        }
        fn as_streaming(&self) -> Option<&dyn StreamingTool> {
            if let Some(tx) = self.entered.lock().unwrap().take() {
                let _ = tx.send(());
                let deadline = Instant::now() + Duration::from_secs(10);
                while Instant::now() < deadline {
                    if self.dropped.get().is_some_and(|d| d.is_cancelled()) {
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(1));
                }
            }
            Some(self)
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    impl StreamingTool for NeverYields {
        fn run_stream(
            &self,
            _ctx: Context,
            _args: Value,
        ) -> BoxStream<'static, Result<String, ToolError>> {
            Box::pin(futures::stream::pending())
        }
    }

    /// R9 on the drop path: dropping the event stream while a streaming tool is starting must
    /// not leave the tool's task running, even for a direct `run_live` caller whose invocation is
    /// never cancelled.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn dropping_the_stream_while_a_streaming_tool_starts_does_not_leak_it() {
        let server = FakeLiveServer::start(serve(|_n: usize, mut conn: FakeConn| async move {
            assert!(conn.write_text(NEVER_CALL).await, "writing toolCall failed");
            conn.block_until_client_closes().await;
        }))
        .await;
        let (entered_tx, mut entered_rx) = oneshot::channel();
        let tool = Arc::new(NeverYields {
            dropped: OnceLock::new(),
            entered: Mutex::new(Some(entered_tx)),
        });
        let flow = Arc::new(Flow {
            model: Some(server.model().await),
            request_processors: vec![live_config_processor as RequestProcessor],
            tools: parking_lot::RwLock::new(vec![tool.clone() as Arc<dyn Tool>]),
            ..Default::default()
        });
        // The invocation is deliberately never cancelled (no `cancel_on_drop` safety net).
        let (ctx, _cancel) = live_ctx();
        let (sess, mut stream) = run_live(flow, ctx).unwrap();
        let probe = probe_of(&sess);
        let done = sess
            .as_any()
            .downcast_ref::<LiveSessionImpl>()
            .unwrap()
            .done()
            .clone();
        tool.dropped.set(done).unwrap();

        // Consume events (pushes are rendezvous) until the tool is starting.
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                tokio::select! {
                    _ = &mut entered_rx => return,
                    item = stream.next() => assert!(item.is_some(), "stream ended before the tool call"),
                }
            }
        })
        .await
        .expect("the streaming tool never started");
        drop(stream);

        assert_no_run_live_leak(&probe).await;
        assert_eq!(probe.teardowns.load(Ordering::SeqCst), 1);
        assert_eq!(
            sess.as_any()
                .downcast_ref::<LiveSessionImpl>()
                .unwrap()
                .active_streaming_tool_count("never_yields"),
            0,
            "the late registration is cancelled, then unregistered by its task"
        );
    }
}