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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
//! # Integration Module
//!
//! This module provides the `IntegratedRealtimeRunner` — a composition layer that
//! wraps the existing `RealtimeRunner` and connects it to ADK services (sessions,
//! memory, plugins) without modifying `RealtimeRunner` internals.
//!
//! ## Components
//!
//! - [`tool_bridge`] — `ToolBridgeAdapter` bridges `adk_core::Tool` → `ToolHandler`
//! - [`transcript`] — `TranscriptAggregator` collects deltas into complete turns
//! - [`context`] — `RealtimeToolContext` implementation for tool execution
//! - [`builder`] — `IntegratedRealtimeRunnerBuilder` for constructing the runner
pub mod builder;
pub mod context;
pub mod tool_bridge;
pub mod transcript;
// Re-exports for convenience
pub use builder::IntegratedRealtimeRunnerBuilder;
pub use context::{DefaultToolContextFactory, RealtimeToolContext, ToolContextFactory};
pub use tool_bridge::ToolBridgeAdapter;
pub use transcript::TranscriptAggregator;
use serde_json::Value;
// ─── Shared Data Types ───────────────────────────────────────────────────────
/// Identifies the ADK session scope for all service interactions.
///
/// Every interaction with session, memory, and plugin services requires
/// a consistent identity triple to locate the correct session state.
#[derive(Debug, Clone)]
pub struct SessionIdentity {
/// The application name (scopes sessions and memory).
pub app_name: String,
/// The user identifier.
pub user_id: String,
/// The unique session identifier.
pub session_id: String,
}
/// Events emitted by the [`TranscriptAggregator`]
/// when a turn completes.
#[derive(Debug, Clone)]
pub enum AggregatedEvent {
/// A complete assistant response turn.
TurnComplete {
/// Full concatenated text output.
text: String,
/// Full concatenated audio transcript.
audio_transcript: String,
/// Tool calls executed during this turn.
tool_calls: Vec<CompletedToolCall>,
/// Provider item ID for this response.
item_id: String,
/// Whether this turn was interrupted by user speech.
interrupted: bool,
},
/// A complete user utterance (from speech recognition).
UserUtteranceComplete {
/// Full user transcript.
transcript: String,
},
}
/// A tool call that was executed during a turn.
#[derive(Debug, Clone)]
pub struct CompletedToolCall {
/// Unique call ID from the provider.
pub call_id: String,
/// Tool function name.
pub name: String,
/// Arguments passed to the tool.
pub arguments: Value,
/// Result returned by the tool.
pub result: Value,
}
/// Configuration options specific to the integration layer.
///
/// Controls which ADK service interactions are performed automatically
/// during the realtime session lifecycle.
#[derive(Debug, Clone)]
pub struct IntegrationConfig {
/// Whether to persist transcripts to session on each turn.
pub persist_transcripts: bool,
/// Whether to store turns in memory for future retrieval.
pub store_to_memory: bool,
/// Whether to inject memory context at session start.
pub inject_memory_context: bool,
/// Maximum memory entries to inject into system instruction.
pub max_memory_injection: usize,
/// Maximum prior conversation turns carried into the provider session.
///
/// Bounded because the instruction is sent at session creation and counts against the
/// model's context. Zero disables history injection while leaving memory injection alone.
pub max_history_injection: usize,
}
impl Default for IntegrationConfig {
fn default() -> Self {
Self {
persist_transcripts: true,
store_to_memory: true,
inject_memory_context: true,
max_memory_injection: 10,
max_history_injection: 20,
}
}
}
// ─── IntegratedRealtimeRunner ────────────────────────────────────────────────
use std::sync::Arc;
use std::collections::HashMap;
use adk_core::Content;
use adk_memory::MemoryService;
use adk_plugin::EnhancedPluginManager;
use adk_session::SessionService;
use tokio::sync::RwLock;
use crate::config::SessionUpdateConfig;
use crate::error::Result;
use crate::events::ServerEvent;
use crate::runner::RealtimeRunner;
/// The main orchestrator that wraps [`RealtimeRunner`] and intercepts its event loop
/// to connect it with ADK services (sessions, memory, plugins).
///
/// `IntegratedRealtimeRunner` provides transparent integration with ADK services:
/// - **Session persistence**: Completed turns are automatically saved to the session.
/// - **Memory storage**: Turns are stored for future RAG retrieval.
/// - **Plugin hooks**: Tool calls pass through `before_tool_call`/`after_tool_call` hooks.
/// - **Transcript aggregation**: Streaming deltas are assembled into complete turns.
///
/// Use [`IntegratedRealtimeRunnerBuilder`] to
/// construct an instance.
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::integration::IntegratedRealtimeRunner;
///
/// let runner = IntegratedRealtimeRunner::builder()
/// .model(model)
/// .identity("my-app", "user-1", "session-1")
/// .session_service(session_svc)
/// .build()?;
/// ```
pub struct IntegratedRealtimeRunner {
/// The underlying realtime runner handling transport and tool execution.
pub(crate) runner: Arc<RealtimeRunner>,
/// Optional session service for transcript persistence.
pub(crate) session_service: Option<Arc<dyn SessionService>>,
/// Optional memory service for RAG storage and retrieval.
pub(crate) memory_service: Option<Arc<dyn MemoryService>>,
/// Optional plugin manager for lifecycle hooks.
#[allow(dead_code)] // Used by task 6.5
pub(crate) plugin_manager: Option<Arc<EnhancedPluginManager>>,
/// Aggregator that assembles streaming deltas into complete turns.
pub(crate) aggregator: RwLock<TranscriptAggregator>,
/// Session identity triple (app_name, user_id, session_id).
pub(crate) identity: SessionIdentity,
/// Integration-layer configuration.
pub(crate) config: IntegrationConfig,
/// The ADK tools by name, so the live path can run them through the policy pipeline.
///
/// The builder wrapped each one in a `ToolBridgeAdapter` for the inner runner and then
/// dropped the originals, which is why the active path could only reach the adapter — and
/// the adapter applies no confirmation, callbacks, or plugins.
pub(crate) adk_tools: HashMap<String, Arc<dyn adk_core::Tool>>,
}
/// Renders the most recent `limit` turns as bounded `role: text` lines.
///
/// The instruction is sent once at session creation and counts against the model's context, so
/// this keeps the newest turns, drops anything without text, and truncates long turns rather
/// than carrying a transcript of unbounded size.
fn summarize_turns(turns: &[Content], limit: usize) -> Vec<String> {
/// Longest rendered form of a single turn.
const MAX_TURN_CHARS: usize = 400;
if limit == 0 {
return Vec::new();
}
turns
.iter()
.rev()
.take(limit)
.filter_map(|turn| {
let text: String = turn.parts.iter().filter_map(|part| part.text()).collect();
if text.trim().is_empty() {
return None;
}
let mut end = text.len().min(MAX_TURN_CHARS);
while end < text.len() && !text.is_char_boundary(end) {
end -= 1;
}
let rendered = if end < text.len() { format!("{}…", &text[..end]) } else { text };
Some(format!("{}: {rendered}", turn.role))
})
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect()
}
impl IntegratedRealtimeRunner {
/// Creates a new [`IntegratedRealtimeRunnerBuilder`].
pub fn builder() -> builder::IntegratedRealtimeRunnerBuilder {
builder::IntegratedRealtimeRunnerBuilder::new()
}
/// Connect to the realtime provider.
///
/// Before connecting, loads session history and injects memory context
/// if the respective services are configured. Session/memory failures
/// are non-fatal — the connection proceeds regardless.
///
/// # Errors
///
/// Returns an error only if the underlying [`RealtimeRunner::connect`] fails
/// (transport-level error). Session and memory service failures are logged
/// and swallowed.
///
/// # Example
///
/// ```rust,ignore
/// let runner = IntegratedRealtimeRunner::builder()
/// .model(model)
/// .identity("my-app", "user-1", "session-1")
/// .session_service(session_svc)
/// .memory_service(memory_svc)
/// .build()?;
///
/// runner.connect().await?;
/// ```
pub async fn connect(&self) -> Result<()> {
// Context is collected first, then injected into the provider config as one block.
// Previously the session was fetched into `_session` and dropped, and the memory
// branch logged "injecting memory entries" next to a comment saying injection was a
// future enhancement — so a resumed session began with neither, while the log said
// otherwise.
let mut context_sections: Vec<String> = Vec::new();
// 1. Prior conversation history.
if let Some(ref session_service) = self.session_service {
let get_req = adk_session::GetRequest {
app_name: self.identity.app_name.clone(),
user_id: self.identity.user_id.clone(),
session_id: self.identity.session_id.clone(),
num_recent_events: None,
after: None,
};
match session_service.get(get_req).await {
Ok(session) => {
let history: Vec<Content> = session
.events()
.all()
.into_iter()
.filter_map(|event| event.llm_response.content)
.collect();
let carried = summarize_turns(&history, self.config.max_history_injection);
tracing::debug!(
session_id = %self.identity.session_id,
turns.available = history.len(),
turns.carried = carried.len(),
"loaded prior session history"
);
if !carried.is_empty() {
context_sections
.push(format!("Earlier in this conversation:\n{}", carried.join("\n")));
}
}
Err(e) => {
tracing::warn!(
session_id = %self.identity.session_id,
error = %e,
"session load failed (non-fatal)"
);
}
}
}
// 2. Recalled memory.
if self.config.inject_memory_context
&& let Some(ref memory_service) = self.memory_service
{
match memory_service
.search(adk_memory::SearchRequest {
query: "session context".to_string(),
user_id: self.identity.user_id.clone(),
app_name: self.identity.app_name.clone(),
limit: Some(self.config.max_memory_injection),
min_score: None,
project_id: None,
})
.await
{
Ok(response) => {
let recalled = summarize_turns(
&response
.memories
.iter()
.map(|entry| entry.content.clone())
.collect::<Vec<Content>>(),
self.config.max_memory_injection,
);
tracing::debug!(
count = recalled.len(),
"carrying memory entries into the session instruction"
);
if !recalled.is_empty() {
context_sections
.push(format!("Relevant recalled context:\n{}", recalled.join("\n")));
}
}
Err(e) => {
tracing::warn!(
error = %e,
"memory query failed (non-fatal)"
);
}
}
}
if !context_sections.is_empty() {
self.runner.prepend_instruction_context(&context_sections.join("\n\n")).await;
}
// 3. Connect the underlying runner — this is the only error that propagates
self.runner.connect().await
}
/// Send audio to the realtime session.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// runner.send_audio(base64_encoded_pcm).await?;
/// ```
pub async fn send_audio(&self, audio_base64: &str) -> Result<()> {
self.runner.send_audio(audio_base64).await
}
/// Send text to the realtime session.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// runner.send_text("Hello, how are you?").await?;
/// ```
pub async fn send_text(&self, text: &str) -> Result<()> {
self.runner.send_text(text).await
}
/// Send a base64-encoded video/image frame (e.g. `image/jpeg`) for
/// multimodal input. Delegates to the underlying [`RealtimeRunner`].
pub async fn send_video_frame(&self, mime_type: &str, data_base64: &str) -> Result<()> {
self.runner.send_video_frame(mime_type, data_base64).await
}
/// Trigger a response from the model.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// runner.create_response().await?;
/// ```
pub async fn create_response(&self) -> Result<()> {
self.runner.create_response().await
}
/// Interrupt the current response.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// runner.interrupt().await?;
/// ```
pub async fn interrupt(&self) -> Result<()> {
self.runner.interrupt().await
}
/// Update the session configuration.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::config::{SessionUpdateConfig, RealtimeConfig};
///
/// let update = SessionUpdateConfig(
/// RealtimeConfig::default().with_instruction("You are now a pirate.")
/// );
/// runner.update_session(update).await?;
/// ```
/// The system instruction the provider session was created with.
///
/// Includes any prior-history and recalled-memory context carried in by
/// [`IntegratedRealtimeRunner::connect`].
pub async fn instruction(&self) -> Option<String> {
self.runner.instruction().await
}
pub async fn update_session(&self, config: SessionUpdateConfig) -> Result<()> {
self.runner.update_session(config).await
}
/// Close the realtime session.
///
/// Delegates to the underlying [`RealtimeRunner`].
///
/// # Example
///
/// ```rust,ignore
/// runner.close().await?;
/// ```
pub async fn close(&self) -> Result<()> {
self.runner.close().await
}
/// Process the next event from the realtime session with full integration.
///
/// Feeds each [`ServerEvent`] to the [`TranscriptAggregator`] for turn assembly.
/// When a turn completes, persists the aggregated event to session/memory.
/// The raw event is always forwarded to the caller.
///
/// Returns `None` when the session is closed or no more events are available.
///
/// # Example
///
/// ```rust,ignore
/// while let Some(event) = runner.next_event().await {
/// match event? {
/// ServerEvent::AudioDelta { delta, .. } => { /* forward to browser */ }
/// ServerEvent::TranscriptDelta { delta, .. } => { /* show in UI */ }
/// _ => {}
/// }
/// }
/// ```
pub async fn next_event(&self) -> Option<Result<ServerEvent>> {
let event = self.runner.next_event().await?;
if let Ok(server_event) = &event {
// Feed to transcript aggregator
let aggregated = self.aggregator.write().await.process(server_event);
if let Some(agg_event) = aggregated {
self.handle_aggregated_event(agg_event).await;
}
// Auto-execute tool calls. Unlike `RealtimeRunner::run`, the pull-based
// `next_event` path does not dispatch tools on its own, so we do it here:
// bridged ADK tools and native handlers registered on the builder run,
// and (with `auto_respond_tools`) the result is sent back to the model.
if let ServerEvent::FunctionCallDone { call_id, name, arguments, .. } = server_event
&& let Err(e) = self.dispatch_with_policy(call_id, name, arguments).await
{
tracing::warn!(
tool = %name,
call_id = %call_id,
error = %e,
"tool dispatch failed (non-fatal)"
);
}
// When the dispatch response finishes, send the single owed follow-up
// response so the model speaks its answer using the tool results. This
// mirrors what `RealtimeRunner::run` does in `handle_event`; the
// pull-based path must do it explicitly.
if let ServerEvent::ResponseDone { .. } = server_event
&& let Err(e) = self.runner.respond_after_tools().await
{
tracing::warn!(error = %e, "post-tool response trigger failed (non-fatal)");
}
}
Some(event)
}
/// Handle a completed aggregated event (turn or user utterance).
///
/// - `TurnComplete`: builds an assistant `Event`, persists to session, stores to memory,
/// calls plugin `on_event`
/// - `UserUtteranceComplete`: builds a user `Event`, persists to session
///
/// All service errors are logged and swallowed (non-fatal).
async fn handle_aggregated_event(&self, event: AggregatedEvent) {
match &event {
AggregatedEvent::TurnComplete { text, audio_transcript, .. } => {
tracing::debug!(text_len = text.len(), "turn complete");
// 1. Build adk_core::Event for the assistant turn
let transcript_text =
if text.is_empty() { audio_transcript.as_str() } else { text.as_str() };
let content = adk_core::Content::new("model").with_text(transcript_text);
let mut adk_event = adk_core::Event::new("realtime");
adk_event.author = "model".to_string();
adk_event.set_content(content.clone());
// 2. Persist to session
if self.config.persist_transcripts
&& let Some(ref session_service) = self.session_service
&& let Err(e) = session_service
.append_event(&self.identity.session_id, adk_event.clone())
.await
{
tracing::warn!(error = %e, "session persist failed (non-fatal)");
}
// 3. Store to memory
if self.config.store_to_memory
&& let Some(ref memory_service) = self.memory_service
{
let entry = adk_memory::MemoryEntry {
content,
author: "assistant".to_string(),
timestamp: chrono::Utc::now(),
};
if let Err(e) = memory_service
.add_session(
&self.identity.app_name,
&self.identity.user_id,
&self.identity.session_id,
vec![entry],
)
.await
{
tracing::warn!(error = %e, "memory persist failed (non-fatal)");
}
}
// 4. Plugin on_event hook
// EnhancedPluginManager::run_on_event requires an InvocationContext
// which is not available in the realtime runner context.
// We log the event notification for observability; full plugin
// integration requires a future InvocationContext adapter.
if self.plugin_manager.is_some() {
tracing::debug!(
event_id = %adk_event.id,
"plugin on_event: skipped (no InvocationContext in realtime)"
);
}
}
AggregatedEvent::UserUtteranceComplete { transcript } => {
tracing::debug!(transcript_len = transcript.len(), "user utterance complete");
// Build user event and persist to session
let content = adk_core::Content::new("user").with_text(transcript);
let mut adk_event = adk_core::Event::new("realtime");
adk_event.author = "user".to_string();
adk_event.set_content(content);
if self.config.persist_transcripts
&& let Some(ref session_service) = self.session_service
&& let Err(e) =
session_service.append_event(&self.identity.session_id, adk_event).await
{
tracing::warn!(error = %e, "session persist failed (non-fatal)");
}
}
}
}
/// Execute a tool with plugin lifecycle hooks.
///
/// When an [`EnhancedPluginManager`] is configured:
/// 1. Runs `before_tool_call` pipeline — may short-circuit with a synthetic result
/// 2. Executes the tool on `Continue`
/// 3. Runs `after_tool_call` pipeline with the result
///
/// When no [`EnhancedPluginManager`] is configured, executes the tool directly.
///
/// Records the completed tool call in the [`TranscriptAggregator`] regardless of path,
/// and emits an [`adk_core::Event`] with the function call and result.
///
/// # Arguments
///
/// * `tool` - The ADK tool to execute.
/// * `call` - The tool call metadata (call_id, name, arguments).
///
/// # Errors
///
/// Returns an error only if the result construction fails. Plugin hook errors
/// are non-fatal: logged and swallowed, with execution falling through to
/// direct tool invocation.
#[allow(dead_code)] // Will be wired in event loop handling
/// Dispatches one provider tool call, preferring the policy pipeline.
///
/// An ADK tool registered on this builder runs through `execute_tool_with_plugins`, which
/// applies the configured plugin pipeline, records the call for the transcript, and
/// persists the tool event. Previously the live path called
/// `RealtimeRunner::dispatch_tool_call`, which invokes the `ToolBridgeAdapter` directly —
/// the adapter creates a context and calls `Tool::execute` with no plugins, callbacks, or
/// confirmation, so a tool governed in the standard agent loop ran ungoverned here.
///
/// A name that is not a registered ADK tool is a native handler, and falls through to the
/// runner's own dispatch. That bypass is now explicit rather than the default.
async fn dispatch_with_policy(&self, call_id: &str, name: &str, arguments: &str) -> Result<()> {
let Some(tool) = self.adk_tools.get(name).cloned() else {
tracing::debug!(
tool = %name,
"no ADK tool by this name; dispatching as a native handler"
);
return self.runner.dispatch_tool_call(call_id, name, arguments).await;
};
let call = crate::events::ToolCall {
call_id: call_id.to_string(),
name: name.to_string(),
arguments: serde_json::from_str(arguments)
.unwrap_or(serde_json::Value::Object(Default::default())),
};
let result = self.execute_tool_with_plugins(&tool, &call).await?;
self.runner.send_tool_result(call_id, result).await
}
/// Runs one tool through the policy pipeline, for conformance tests.
///
/// Exposed so the governed path can be asserted directly rather than only through a live
/// provider session, which is why this defect had no coverage.
#[doc(hidden)]
pub async fn execute_tool_with_plugins_for_test(
&self,
tool: &Arc<dyn adk_core::Tool>,
call: &crate::events::ToolCall,
) -> Result<Value> {
self.execute_tool_with_plugins(tool, call).await
}
pub(crate) async fn execute_tool_with_plugins(
&self,
tool: &Arc<dyn adk_core::Tool>,
call: &crate::events::ToolCall,
) -> Result<Value> {
let ctx = self.create_tool_context(&call.call_id);
let result = if let Some(ref pm) = self.plugin_manager {
// Run before_tool_call pipeline
match pm
.run_before_tool_call(
tool.clone(),
call.arguments.clone(),
ctx.clone() as Arc<dyn adk_core::CallbackContext>,
)
.await
{
Ok(adk_plugin::BeforeToolCallResult::ShortCircuit(value)) => {
tracing::debug!(tool = tool.name(), "plugin short-circuited tool execution");
value
}
Ok(adk_plugin::BeforeToolCallResult::Continue(args)) => {
// Execute tool with potentially modified args
let tool_result = tool
.execute(ctx.clone() as Arc<dyn adk_core::ToolContext>, args)
.await
.unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }));
// Run after_tool_call pipeline
match pm
.run_after_tool_call(
tool.clone(),
&call.arguments,
tool_result.clone(),
ctx as Arc<dyn adk_core::CallbackContext>,
)
.await
{
Ok(adk_plugin::AfterToolCallResult::Continue(v)) => v,
Err(e) => {
tracing::warn!(error = %e, "after_tool_call plugin error (non-fatal)");
tool_result
}
}
}
Err(e) => {
// Fail closed. A before-tool plugin is where authorization, redaction, and
// policy live, so executing the tool when that pipeline fails turns a
// broken guard into no guard. The model receives the error instead.
tracing::error!(
tool = tool.name(),
error = %e,
"before_tool_call plugin failed; refusing the tool"
);
serde_json::json!({
"error": format!(
"tool {} was refused: its before-tool plugin pipeline failed ({e}). \
Execution is refused rather than proceeding without policy.",
tool.name()
)
})
}
}
} else {
// No plugin manager — execute directly
tool.execute(ctx as Arc<dyn adk_core::ToolContext>, call.arguments.clone())
.await
.unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }))
};
// Record completed tool call in aggregator
self.aggregator.write().await.record_tool_call(CompletedToolCall {
call_id: call.call_id.clone(),
name: call.name.clone(),
arguments: call.arguments.clone(),
result: result.clone(),
});
// Emit adk_core::Event with function call and result
let mut content = adk_core::Content::new("tool");
content.parts.push(adk_core::Part::FunctionCall {
name: call.name.clone(),
args: call.arguments.clone(),
id: Some(call.call_id.clone()),
thought_signature: None,
});
content.parts.push(adk_core::Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::new(&call.name, result.clone()),
id: Some(call.call_id.clone()),
annotations: None,
});
if let Some(ref session_service) = self.session_service {
let mut adk_event = adk_core::Event::new(&call.call_id);
adk_event.author = "tool".to_string();
adk_event.set_content(content);
if let Err(e) = session_service.append_event(&self.identity.session_id, adk_event).await
{
tracing::warn!(error = %e, "tool event session persist failed (non-fatal)");
}
}
Ok(result)
}
/// Create a [`RealtimeToolContext`](context::RealtimeToolContext) for the given
/// function call ID.
///
/// Returns an `Arc<RealtimeToolContext>` which implements both [`ToolContext`]
/// and [`CallbackContext`], allowing it to be passed to plugin hooks and tool
/// execution alike.
#[allow(dead_code)] // Used by execute_tool_with_plugins
fn create_tool_context(&self, function_call_id: &str) -> Arc<context::RealtimeToolContext> {
Arc::new(context::RealtimeToolContext::new(
self.identity.app_name.clone(),
self.identity.user_id.clone(),
self.identity.session_id.clone(),
function_call_id.to_string(),
self.memory_service.clone(),
))
}
}
// ─── Session Persistence Tests ───────────────────────────────────────────────
#[cfg(test)]
mod session_persistence_tests {
use super::*;
use crate::audio::AudioFormat;
use crate::config::RealtimeConfig;
use crate::model::BoxedModel;
use crate::session::BoxedSession;
use adk_session::{CreateRequest, GetRequest, InMemorySessionService};
use async_trait::async_trait;
use proptest::prelude::*;
use std::collections::HashMap;
// ─── Mock RealtimeModel ──────────────────────────────────────────────────
struct MockRealtimeModel;
#[async_trait]
impl crate::model::RealtimeModel for MockRealtimeModel {
fn provider(&self) -> &str {
"mock"
}
fn model_id(&self) -> &str {
"mock-model-v1"
}
fn supports_realtime(&self) -> bool {
true
}
fn supported_input_formats(&self) -> Vec<AudioFormat> {
vec![AudioFormat::pcm16_24khz()]
}
fn supported_output_formats(&self) -> Vec<AudioFormat> {
vec![AudioFormat::pcm16_24khz()]
}
fn available_voices(&self) -> Vec<&str> {
vec!["default"]
}
async fn connect(&self, _config: RealtimeConfig) -> crate::error::Result<BoxedSession> {
Err(crate::error::RealtimeError::connection("mock transport: no connection available"))
}
}
fn mock_model() -> BoxedModel {
Arc::new(MockRealtimeModel) as BoxedModel
}
// ─── Helpers ─────────────────────────────────────────────────────────────
/// Build an IntegratedRealtimeRunner with the given session service.
fn build_runner_with_session_service(
session_service: Arc<dyn SessionService>,
session_id: &str,
) -> IntegratedRealtimeRunner {
builder::IntegratedRealtimeRunnerBuilder::new()
.model(mock_model())
.identity("test-app", "test-user", session_id)
.session_service(session_service)
.integration_config(IntegrationConfig {
persist_transcripts: true,
store_to_memory: false,
inject_memory_context: false,
max_history_injection: 20,
max_memory_injection: 0,
})
.build()
.expect("builder should succeed with mock model + identity")
}
/// Create a session in the service so append_event can find it.
async fn create_test_session(service: &InMemorySessionService, session_id: &str) {
service
.create(CreateRequest {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: Some(session_id.to_string()),
state: HashMap::new(),
})
.await
.expect("session creation should succeed");
}
/// Retrieve all events from the session.
async fn get_session_events(
service: &InMemorySessionService,
session_id: &str,
) -> Vec<adk_core::Event> {
let session = service
.get(GetRequest {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: session_id.to_string(),
num_recent_events: None,
after: None,
})
.await
.expect("session retrieval should succeed");
session.events().all()
}
// ─── Property Test: Session Append Ordering ──────────────────────────────
/// **Feature: realtime-adk-integration, Property 3: Session Append Ordering**
/// *For any* conversation with user utterances followed by assistant responses,
/// events appended to `SessionService` SHALL maintain causal ordering:
/// user events precede the assistant responses they triggered.
/// **Validates: Requirements 2.1, 2.2, 7.2, 7.3**
#[test]
fn prop_session_append_ordering() {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
proptest!(ProptestConfig::with_cases(100), |(
user_transcript in "[a-zA-Z0-9 ]{1,50}",
assistant_text in "[a-zA-Z0-9 ]{1,50}",
num_exchanges in 1usize..5,
)| {
rt.block_on(async {
let session_service = Arc::new(InMemorySessionService::new());
let session_id = format!("prop-session-{}", uuid::Uuid::new_v4());
create_test_session(&session_service, &session_id).await;
let runner = build_runner_with_session_service(
session_service.clone(),
&session_id,
);
// Simulate multiple user→assistant exchanges
for _ in 0..num_exchanges {
// 1. User utterance completes first
runner
.handle_aggregated_event(AggregatedEvent::UserUtteranceComplete {
transcript: user_transcript.clone(),
})
.await;
// 2. Assistant turn completes in response
runner
.handle_aggregated_event(AggregatedEvent::TurnComplete {
text: assistant_text.clone(),
audio_transcript: String::new(),
tool_calls: vec![],
item_id: format!("item-{}", uuid::Uuid::new_v4()),
interrupted: false,
})
.await;
}
// Verify: retrieve all events from session
let events = get_session_events(&session_service, &session_id).await;
// Should have 2 * num_exchanges events (user + assistant per exchange)
prop_assert_eq!(
events.len(),
num_exchanges * 2,
"expected {} events, got {}",
num_exchanges * 2,
events.len()
);
// Verify ordering: even indices are user, odd indices are assistant
for i in 0..num_exchanges {
let user_event = &events[i * 2];
let assistant_event = &events[i * 2 + 1];
prop_assert_eq!(
&user_event.author,
"user",
"event at index {} should be from 'user', got '{}'",
i * 2,
user_event.author
);
prop_assert_eq!(
&assistant_event.author,
"model",
"event at index {} should be from 'model', got '{}'",
i * 2 + 1,
assistant_event.author
);
// Verify causal ordering: user event timestamp <= assistant event timestamp
prop_assert!(
user_event.timestamp <= assistant_event.timestamp,
"user event timestamp ({}) should be <= assistant event timestamp ({})",
user_event.timestamp,
assistant_event.timestamp
);
}
Ok(())
})?;
});
}
// ─── Unit Test: full event flow ──────────────────────────────────────────
/// Integration test verifying the full event flow:
/// connect → user utterance → assistant response → verify session state.
#[tokio::test]
async fn test_full_event_flow_with_in_memory_session_service() {
let session_service = Arc::new(InMemorySessionService::new());
let session_id = "integration-test-session";
// Create session first
create_test_session(&session_service, session_id).await;
// Build runner
let runner = build_runner_with_session_service(session_service.clone(), session_id);
// Simulate user utterance
runner
.handle_aggregated_event(AggregatedEvent::UserUtteranceComplete {
transcript: "Hello, what is the weather today?".to_string(),
})
.await;
// Simulate assistant response (as would be produced by TranscriptAggregator
// after processing ResponseCreated → TextDelta* → ResponseDone)
runner
.handle_aggregated_event(AggregatedEvent::TurnComplete {
text: "The weather is sunny and 72°F today.".to_string(),
audio_transcript: String::new(),
tool_calls: vec![],
item_id: "item-001".to_string(),
interrupted: false,
})
.await;
// Verify session contains both events in correct order
let events = get_session_events(&session_service, session_id).await;
assert_eq!(events.len(), 2, "session should have 2 events");
// First event: user utterance
assert_eq!(events[0].author, "user");
let user_content = events[0].content();
assert!(user_content.is_some(), "user event should have content");
let user_text = user_content
.unwrap()
.parts
.iter()
.filter_map(|p| match p {
adk_core::Part::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("");
assert_eq!(user_text, "Hello, what is the weather today?");
// Second event: assistant response
assert_eq!(events[1].author, "model");
let assistant_content = events[1].content();
assert!(assistant_content.is_some(), "assistant event should have content");
let assistant_text = assistant_content
.unwrap()
.parts
.iter()
.filter_map(|p| match p {
adk_core::Part::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("");
assert_eq!(assistant_text, "The weather is sunny and 72°F today.");
// Verify causal ordering
assert!(
events[0].timestamp <= events[1].timestamp,
"user event should be timestamped before or at same time as assistant event"
);
}
/// Test that multiple exchanges maintain ordering.
#[tokio::test]
async fn test_multiple_exchanges_maintain_ordering() {
let session_service = Arc::new(InMemorySessionService::new());
let session_id = "multi-exchange-session";
create_test_session(&session_service, session_id).await;
let runner = build_runner_with_session_service(session_service.clone(), session_id);
// Exchange 1
runner
.handle_aggregated_event(AggregatedEvent::UserUtteranceComplete {
transcript: "First question".to_string(),
})
.await;
runner
.handle_aggregated_event(AggregatedEvent::TurnComplete {
text: "First answer".to_string(),
audio_transcript: String::new(),
tool_calls: vec![],
item_id: "item-1".to_string(),
interrupted: false,
})
.await;
// Exchange 2
runner
.handle_aggregated_event(AggregatedEvent::UserUtteranceComplete {
transcript: "Second question".to_string(),
})
.await;
runner
.handle_aggregated_event(AggregatedEvent::TurnComplete {
text: "Second answer".to_string(),
audio_transcript: String::new(),
tool_calls: vec![],
item_id: "item-2".to_string(),
interrupted: false,
})
.await;
let events = get_session_events(&session_service, session_id).await;
assert_eq!(events.len(), 4);
// Verify full ordering
assert_eq!(events[0].author, "user");
assert_eq!(events[1].author, "model");
assert_eq!(events[2].author, "user");
assert_eq!(events[3].author, "model");
// Verify monotonically increasing timestamps
for i in 1..events.len() {
assert!(
events[i - 1].timestamp <= events[i].timestamp,
"events should have monotonically non-decreasing timestamps"
);
}
}
// ─── Plugin Short-Circuit Test Helpers ───────────────────────────────────
/// A tool that tracks whether its `execute` method was called.
struct TrackedTool {
executed: Arc<std::sync::atomic::AtomicBool>,
tool_name: String,
}
#[async_trait]
impl adk_core::Tool for TrackedTool {
fn name(&self) -> &str {
&self.tool_name
}
fn description(&self) -> &str {
"A tool that tracks whether execute was called"
}
async fn execute(
&self,
_ctx: Arc<dyn adk_core::ToolContext>,
_args: serde_json::Value,
) -> adk_core::Result<serde_json::Value> {
self.executed.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(serde_json::json!({"executed": true}))
}
}
/// A plugin that always returns `ShortCircuit` from `before_tool_call`.
struct ShortCircuitPlugin {
short_circuit_value: serde_json::Value,
}
#[async_trait]
impl adk_plugin::EnhancedPlugin for ShortCircuitPlugin {
fn name(&self) -> &str {
"short-circuit-plugin"
}
fn priority(&self) -> i32 {
10
}
async fn before_tool_call(
&self,
_tool: Arc<dyn adk_core::Tool>,
_args: serde_json::Value,
_ctx: Arc<dyn adk_core::CallbackContext>,
_plugin_ctx: &adk_plugin::PluginContext,
) -> adk_core::Result<adk_plugin::BeforeToolCallResult> {
Ok(adk_plugin::BeforeToolCallResult::ShortCircuit(self.short_circuit_value.clone()))
}
}
/// Build an `IntegratedRealtimeRunner` with a plugin manager configured.
fn build_runner_with_plugin(
plugin_manager: Arc<adk_plugin::EnhancedPluginManager>,
) -> IntegratedRealtimeRunner {
let model = mock_model();
let runner = crate::runner::RealtimeRunner::builder()
.model(model)
.build()
.expect("mock runner build should succeed");
IntegratedRealtimeRunner {
runner: Arc::new(runner),
session_service: None,
memory_service: None,
plugin_manager: Some(plugin_manager),
aggregator: tokio::sync::RwLock::new(TranscriptAggregator::new()),
identity: SessionIdentity {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: "test-session".to_string(),
},
config: IntegrationConfig::default(),
adk_tools: HashMap::new(),
}
}
// ─── Property Test: Plugin Short-Circuit ─────────────────────────────────
// **Feature: realtime-adk-integration, Property 4: Plugin Short-Circuit**
// *For any* `before_tool_call` hook returning `ShortCircuit(v)`, verify the tool's
// `execute` is never called and `v` is used as the response.
// **Validates: Requirements 4.1, 4.3**
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn prop_plugin_short_circuit_skips_tool_execution(
short_circuit_json in prop_oneof![
Just(serde_json::json!({"cached": "response"})),
Just(serde_json::json!({"result": 42})),
Just(serde_json::json!("simple_string")),
Just(serde_json::json!(null)),
Just(serde_json::json!([1, 2, 3])),
Just(serde_json::json!({"nested": {"key": "value"}, "list": [true, false]})),
(0i64..1000).prop_map(|n| serde_json::json!({"number": n})),
"[a-z]{1,20}".prop_map(|s| serde_json::json!({"text": s})),
],
tool_name in "[a-z_]{3,15}",
call_id in "[a-z0-9]{5,15}",
args in prop_oneof![
Just(serde_json::json!({})),
Just(serde_json::json!({"query": "hello"})),
Just(serde_json::json!({"x": 1, "y": 2})),
],
) {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
// 1. Create a tracked tool that records whether execute was called
let executed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let tool: Arc<dyn adk_core::Tool> = Arc::new(TrackedTool {
executed: executed.clone(),
tool_name: tool_name.clone(),
});
// 2. Create a plugin that returns ShortCircuit with the given value
let plugin: Arc<dyn adk_plugin::EnhancedPlugin> = Arc::new(ShortCircuitPlugin {
short_circuit_value: short_circuit_json.clone(),
});
let pm = Arc::new(adk_plugin::EnhancedPluginManager::new(vec![plugin]));
// 3. Build the IntegratedRealtimeRunner with the plugin manager
let runner = build_runner_with_plugin(pm);
// 4. Create a ToolCall
let tool_call = crate::events::ToolCall {
call_id,
name: tool_name,
arguments: args,
};
// 5. Execute tool with plugins
let result = runner.execute_tool_with_plugins(&tool, &tool_call).await;
// 6. Verify the tool's execute was NOT called
prop_assert!(
!executed.load(std::sync::atomic::Ordering::SeqCst),
"Tool execute() should NOT be called when plugin short-circuits"
);
// 7. Verify the returned value matches the short-circuit value
let result_value = result.expect("execute_tool_with_plugins should not error");
prop_assert_eq!(
&result_value,
&short_circuit_json,
"Returned value should match the short-circuit value"
);
Ok(())
})?;
}
}
// ─── Integration Test: Plugin Short-Circuit Records Tool Call & Persists Event ─
/// Integration test verifying that when a plugin short-circuits tool execution:
/// 1. The tool's `execute` method is NOT invoked
/// 2. The short-circuit value is returned as the tool result
/// 3. The tool call is recorded in the `TranscriptAggregator`
/// 4. The session event is persisted with the short-circuit result
///
/// **Validates: Requirements 4.1, 4.3**
#[tokio::test]
async fn test_plugin_short_circuit_records_tool_call_and_persists_event() {
use std::sync::atomic::{AtomicBool, Ordering};
let session_service = Arc::new(InMemorySessionService::new());
let session_id = "short-circuit-persist-session";
// 1. Create session so append_event can find it
create_test_session(&session_service, session_id).await;
// 2. Create a tracked tool that records whether execute was called
let executed = Arc::new(AtomicBool::new(false));
let tool: Arc<dyn adk_core::Tool> = Arc::new(TrackedTool {
executed: executed.clone(),
tool_name: "weather_lookup".to_string(),
});
// 3. Create a plugin that returns ShortCircuit with a specific cached value
let short_circuit_value = serde_json::json!({
"cached": true,
"temperature": 72,
"condition": "sunny"
});
let plugin: Arc<dyn adk_plugin::EnhancedPlugin> =
Arc::new(ShortCircuitPlugin { short_circuit_value: short_circuit_value.clone() });
let pm = Arc::new(adk_plugin::EnhancedPluginManager::new(vec![plugin]));
// 4. Build runner with both session service and plugin manager
let model = mock_model();
let runner_inner = crate::runner::RealtimeRunner::builder()
.model(model)
.build()
.expect("mock runner build should succeed");
let runner = IntegratedRealtimeRunner {
runner: Arc::new(runner_inner),
session_service: Some(session_service.clone()),
memory_service: None,
plugin_manager: Some(pm),
aggregator: tokio::sync::RwLock::new(TranscriptAggregator::new()),
identity: SessionIdentity {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: session_id.to_string(),
},
config: IntegrationConfig {
persist_transcripts: true,
store_to_memory: false,
inject_memory_context: false,
max_history_injection: 20,
max_memory_injection: 0,
},
adk_tools: HashMap::new(),
};
// 5. Start a turn in the aggregator so record_tool_call has somewhere to attach
{
let mut agg = runner.aggregator.write().await;
agg.process(&crate::events::ServerEvent::ResponseCreated {
event_id: "evt_created".to_string(),
response: serde_json::json!({}),
});
}
// 6. Create a ToolCall and execute with plugins
let tool_call = crate::events::ToolCall {
call_id: "call-abc-123".to_string(),
name: "weather_lookup".to_string(),
arguments: serde_json::json!({"city": "Seattle"}),
};
let result = runner.execute_tool_with_plugins(&tool, &tool_call).await;
// ─── Assertion 1: tool's execute was NOT called ──────────────────────
assert!(
!executed.load(Ordering::SeqCst),
"Tool execute() should NOT be called when plugin short-circuits"
);
// ─── Assertion 2: returned value matches the short-circuit value ─────
let result_value = result.expect("execute_tool_with_plugins should not error");
assert_eq!(
result_value, short_circuit_value,
"Returned value should match the short-circuit value"
);
// ─── Assertion 3: tool call recorded in the aggregator ───────────────
// Finalize the turn to extract tool calls (recorded during execute_tool_with_plugins)
let aggregated = {
let mut agg = runner.aggregator.write().await;
agg.process(&crate::events::ServerEvent::ResponseDone {
event_id: "evt_done".to_string(),
response: serde_json::json!({}),
})
};
let aggregated_event = aggregated.expect("ResponseDone should finalize the turn");
match aggregated_event {
AggregatedEvent::TurnComplete { tool_calls, .. } => {
assert_eq!(tool_calls.len(), 1, "Should have exactly 1 tool call recorded");
let recorded = &tool_calls[0];
assert_eq!(recorded.call_id, "call-abc-123");
assert_eq!(recorded.name, "weather_lookup");
assert_eq!(recorded.arguments, serde_json::json!({"city": "Seattle"}));
assert_eq!(
recorded.result, short_circuit_value,
"Recorded tool call result should be the short-circuit value"
);
}
_ => panic!("Expected TurnComplete event from aggregator"),
}
// ─── Assertion 4: session event persisted with tool call details ─────
let events = get_session_events(&session_service, session_id).await;
assert_eq!(events.len(), 1, "Session should have exactly 1 event (the tool call event)");
let persisted_event = &events[0];
assert_eq!(persisted_event.author, "tool");
// Verify the event content contains both FunctionCall and FunctionResponse parts
let content = persisted_event.content().expect("persisted event should have content");
let has_function_call = content.parts.iter().any(|p| {
matches!(p, adk_core::Part::FunctionCall { name, id, .. }
if name == "weather_lookup" && id.as_deref() == Some("call-abc-123"))
});
assert!(
has_function_call,
"Persisted event should contain a FunctionCall part with correct name and id"
);
let has_function_response = content.parts.iter().any(|p| match p {
adk_core::Part::FunctionResponse { function_response, id, .. } => {
id.as_deref() == Some("call-abc-123")
&& function_response.response == short_circuit_value
}
_ => false,
});
assert!(
has_function_response,
"Persisted event should contain a FunctionResponse part with the short-circuit value"
);
}
}
#[cfg(test)]
mod graceful_degradation_tests {
use super::*;
use crate::audio::AudioFormat;
use crate::config::RealtimeConfig;
use crate::events::ServerEvent;
use crate::model::RealtimeModel;
use crate::session::BoxedSession;
use adk_core::AdkError;
use adk_memory::{MemoryEntry, MemoryService, SearchRequest, SearchResponse};
use adk_session::{
CreateRequest, DeleteRequest, GetRequest, ListRequest, Session, SessionService,
};
use async_trait::async_trait;
use proptest::prelude::*;
use serde_json::json;
use tokio::sync::RwLock;
// ─── Mock RealtimeModel ──────────────────────────────────────────────────
struct MockRealtimeModel;
#[async_trait]
impl RealtimeModel for MockRealtimeModel {
fn provider(&self) -> &str {
"mock"
}
fn model_id(&self) -> &str {
"mock-model"
}
fn supported_input_formats(&self) -> Vec<AudioFormat> {
vec![]
}
fn supported_output_formats(&self) -> Vec<AudioFormat> {
vec![]
}
fn available_voices(&self) -> Vec<&str> {
vec![]
}
async fn connect(&self, _config: RealtimeConfig) -> crate::error::Result<BoxedSession> {
Err(crate::error::RealtimeError::config("mock model cannot connect"))
}
}
// ─── Failing Mock Services ───────────────────────────────────────────────
/// A `SessionService` that always returns errors on all operations.
struct FailingSessionService;
#[async_trait]
impl SessionService for FailingSessionService {
async fn create(&self, _req: CreateRequest) -> adk_core::Result<Box<dyn Session>> {
Err(AdkError::session("simulated session create failure"))
}
async fn get(&self, _req: GetRequest) -> adk_core::Result<Box<dyn Session>> {
Err(AdkError::session("simulated session get failure"))
}
async fn list(&self, _req: ListRequest) -> adk_core::Result<Vec<Box<dyn Session>>> {
Err(AdkError::session("simulated session list failure"))
}
async fn delete(&self, _req: DeleteRequest) -> adk_core::Result<()> {
Err(AdkError::session("simulated session delete failure"))
}
async fn append_event(
&self,
_session_id: &str,
_event: adk_core::Event,
) -> adk_core::Result<()> {
Err(AdkError::session("simulated session append_event failure"))
}
}
/// A `MemoryService` that always returns errors on all operations.
struct FailingMemoryService;
#[async_trait]
impl MemoryService for FailingMemoryService {
async fn add_session(
&self,
_app_name: &str,
_user_id: &str,
_session_id: &str,
_entries: Vec<MemoryEntry>,
) -> adk_core::Result<()> {
Err(AdkError::memory("simulated memory add_session failure"))
}
async fn search(&self, _req: SearchRequest) -> adk_core::Result<SearchResponse> {
Err(AdkError::memory("simulated memory search failure"))
}
}
// ─── Proptest Strategies ─────────────────────────────────────────────────
/// Generate arbitrary non-empty text delta strings.
fn arb_text_delta() -> impl Strategy<Value = String> {
"[a-zA-Z0-9 .,!?]{1,50}"
}
/// Generate an arbitrary sequence of ServerEvents representing a complete turn.
/// The sequence is: ResponseCreated, then N TextDeltas, then ResponseDone.
fn arb_turn_event_sequence() -> impl Strategy<Value = Vec<ServerEvent>> {
prop::collection::vec(arb_text_delta(), 0..10).prop_map(|deltas| {
let mut events = Vec::new();
// ResponseCreated
events.push(ServerEvent::ResponseCreated {
event_id: "evt_created".to_string(),
response: json!({}),
});
// TextDelta events
for (i, delta) in deltas.iter().enumerate() {
events.push(ServerEvent::TextDelta {
event_id: format!("evt_delta_{i}"),
response_id: "resp_1".to_string(),
item_id: "item_1".to_string(),
output_index: 0,
content_index: 0,
delta: delta.clone(),
});
}
// ResponseDone
events.push(ServerEvent::ResponseDone {
event_id: "evt_done".to_string(),
response: json!({}),
});
events
})
}
// ─── Property Tests ──────────────────────────────────────────────────────
// **Feature: realtime-adk-integration, Property 5: Graceful Degradation**
// *For any* `SessionService` or `MemoryService` that returns errors, verify
// `handle_aggregated_event` does not propagate errors and the aggregator
// still processes events correctly.
// **Validates: Requirements 2.5, 3.4**
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn prop_graceful_degradation_with_failing_services(
events in arb_turn_event_sequence()
) {
// Run the async test in a tokio runtime
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
// Create an IntegratedRealtimeRunner with failing services.
// We construct the struct directly since we can't connect to a real
// WebSocket in unit tests, and we only need to test the aggregator
// + handle_aggregated_event path.
let failing_session: Arc<dyn SessionService> =
Arc::new(FailingSessionService);
let failing_memory: Arc<dyn MemoryService> =
Arc::new(FailingMemoryService);
let mock_model: Arc<dyn RealtimeModel> = Arc::new(MockRealtimeModel);
let runner_struct = IntegratedRealtimeRunner {
runner: Arc::new(
crate::runner::RealtimeRunner::builder()
.model(mock_model)
.build()
.unwrap(),
),
session_service: Some(failing_session),
memory_service: Some(failing_memory),
plugin_manager: None,
aggregator: RwLock::new(TranscriptAggregator::new()),
identity: SessionIdentity {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: "test-session".to_string(),
},
config: IntegrationConfig {
persist_transcripts: true,
store_to_memory: true,
inject_memory_context: true,
max_memory_injection: 10,
max_history_injection: 20,
},
adk_tools: HashMap::new(),
};
// Process events through the aggregator — this is the path that
// next_event() would take internally. We test that no panics
// occur and no errors propagate even with failing services.
for event in &events {
let aggregated = runner_struct.aggregator.write().await.process(event);
if let Some(agg_event) = aggregated {
// This is the key test: handle_aggregated_event must NOT
// panic or propagate errors even when both services fail.
runner_struct.handle_aggregated_event(agg_event).await;
}
}
// After processing a full turn sequence (ResponseCreated...ResponseDone),
// verify the aggregator produced a TurnComplete event. Since our
// event sequence always ends with ResponseDone, a finalization
// MUST have been emitted (tested above in the loop). If we got
// here without panic, graceful degradation is confirmed.
});
}
}
/// Additional test: verify that even with a user utterance event flowing
/// through handle_aggregated_event with failing services, no errors propagate.
#[tokio::test]
async fn test_graceful_degradation_user_utterance() {
let failing_session: Arc<dyn SessionService> = Arc::new(FailingSessionService);
let mock_model: Arc<dyn RealtimeModel> = Arc::new(MockRealtimeModel);
let runner_struct = IntegratedRealtimeRunner {
runner: Arc::new(
crate::runner::RealtimeRunner::builder().model(mock_model).build().unwrap(),
),
session_service: Some(failing_session),
memory_service: None,
plugin_manager: None,
aggregator: RwLock::new(TranscriptAggregator::new()),
identity: SessionIdentity {
app_name: "test-app".to_string(),
user_id: "test-user".to_string(),
session_id: "test-session".to_string(),
},
config: IntegrationConfig {
persist_transcripts: true,
store_to_memory: false,
inject_memory_context: false,
max_history_injection: 20,
max_memory_injection: 0,
},
adk_tools: HashMap::new(),
};
// Process a UserUtteranceComplete event — should not panic even
// though session_service.append_event will fail.
let user_event = AggregatedEvent::UserUtteranceComplete {
transcript: "Hello, how are you?".to_string(),
};
runner_struct.handle_aggregated_event(user_event).await;
// If we get here without panic, the test passes — graceful degradation works.
}
}