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
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
//! RealtimeRunner for integrating realtime sessions with agents.
//!
//! This module provides the bridge between realtime audio sessions and
//! the ADK agent framework, handling tool execution and event routing.
use crate::config::{RealtimeConfig, SessionUpdateConfig, ToolDefinition};
use crate::error::{RealtimeError, Result};
use crate::events::{ServerEvent, ToolCall, ToolResponse};
use crate::metering::{RealtimePricing, ResponseMeter};
use crate::model::BoxedModel;
use crate::session::ContextMutationOutcome;
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tokio::sync::RwLock;
/// How long a realtime tool may run before its call is answered with a timeout error.
pub const DEFAULT_REALTIME_TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
/// The agent a realtime runner governs and meters its tool calls under unless
/// [`RealtimeRunnerBuilder::agent_name`] names another; `IntegratedRealtimeRunner` also
/// authors its held-call events with it, where [`adk_core::held_tool_calls`] finds them.
pub const DEFAULT_REALTIME_AGENT_NAME: &str = "realtime";
/// [`ToolOrigin::source`](adk_core::ToolOrigin::source) of a native handler registered on a
/// [`RealtimeRunner`] with [`RealtimeRunnerBuilder::tool`].
///
/// A governed call to the handler carries this source and a digest of the handler's
/// [`ToolDefinition`] ([`ToolDefinition::handler_origin`]), so an approval of the call never
/// authorizes a [`Tool`](adk_core::Tool) of the same name and stops applying when the
/// handler's description or parameters change.
pub const REALTIME_HANDLER_ORIGIN: &str = "realtime";
/// Runs `screen` on `result`, returning the result to deliver — the
/// [`result_blocked_response`](adk_core::result_blocked_response) that replaces a withheld one —
/// and whether the screen withheld it, which sets the answer's
/// [`ToolResultStatus`](adk_core::ToolResultStatus).
pub(crate) async fn screen_result(
screen: &dyn adk_core::ToolResultScreen,
name: &str,
args: &serde_json::Value,
result: serde_json::Value,
) -> (serde_json::Value, bool) {
match screen.screen_result(name, args, &result).await {
Ok(screened) => (screened, false),
Err(reason) => {
// The reason can describe the result, so it goes to the model, not the log.
tracing::warn!(tool.name = %name, "tool result withheld by its screen");
(adk_core::result_blocked_response(name, &reason), true)
}
}
}
/// Parses a provider's tool-call arguments.
///
/// Empty arguments are an empty object. Anything that is not a JSON object is refused,
/// so a malformed call is answered with an error instead of running with `{}`.
pub(crate) fn parse_tool_arguments(
arguments: &str,
) -> std::result::Result<serde_json::Value, String> {
if arguments.trim().is_empty() {
return Ok(serde_json::Value::Object(Default::default()));
}
match serde_json::from_str::<serde_json::Value>(arguments) {
Ok(value @ serde_json::Value::Object(_)) => Ok(value),
Ok(_) => Err("its arguments are not a JSON object".to_string()),
Err(error) => Err(format!("its arguments are not valid JSON ({error})")),
}
}
/// The user a runner built without [`RealtimeRunnerBuilder::tool_governance`] governs its
/// calls for.
const DEFAULT_REALTIME_USER: &str = "anonymous";
/// The run-wide governance a runner applies to every tool call it dispatches.
#[derive(Clone)]
pub(crate) struct ToolGovernance {
pub(crate) config: adk_core::RunConfig,
pub(crate) scope: adk_core::ApprovalScope,
}
/// Whether a call held for a decision can be decided later: the run records it in an
/// approval store or submits it to an approval service.
pub(crate) fn holds_reach_an_approver(config: &adk_core::RunConfig) -> bool {
config.approval_store.is_some() || config.approval_service.is_some()
}
/// The answer to a call that needs a person's approval when nothing can ask anyone for it:
/// the call is refused, in words the model can speak to the user.
pub(crate) fn no_approver_refusal(name: &str, reason: &str) -> String {
tracing::warn!(
tool.name = %name,
"tool call needs approval but the run has no approval store, approval service, or \
confirmation handler to decide it; refused. Configure one through tool_governance"
);
format!(
"{reason}. Nobody can approve it in this session, so it was not run. Tell the user it \
needs a person's approval and do not call it again."
)
}
/// Internal state machine tracking the resumability status of the RealtimeRunner.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum RunnerState {
/// Runner is ready to accept transport resumption immediately.
#[default]
Idle,
/// Model is currently generating a response; tearing down the connection would corrupt context.
Generating,
/// A tool is currently executing; teardown would cause tool loss.
ExecutingTool,
/// A context mutation was queued while the runner was busy, and must be executed once Idle.
///
/// **Provider Context:** This state is only utilized by providers that do *not* support
/// native mid-flight mutability (e.g., Gemini Live), requiring a physical transport teardown
/// and rebuild (Phantom Reconnect). Providers like OpenAI natively apply `session.update`
/// frames instantly and will never enter this queued state.
///
/// **Queue Policy:** The runner keeps only one pending resumption. If a new session update
/// arrives while a resumption is already pending, the previous pending resumption is replaced.
/// This is intentional: pending session updates represent desired end state, not an ordered
/// command queue. The policy is last write wins.
PendingResumption {
/// The new configuration to apply on reconnection.
config: Box<crate::config::RealtimeConfig>,
/// An optional message to inject immediately after resumption.
bridge_message: Option<String>,
/// Number of failed reconnection attempts for this mutation.
attempts: u8,
},
}
/// Handler for tool/function calls from the realtime model.
#[async_trait]
pub trait ToolHandler: Send + Sync {
/// Execute a tool call and return the result.
async fn execute(&self, call: &ToolCall) -> Result<serde_json::Value>;
}
/// A simple function-based tool handler.
pub struct FnToolHandler<F>
where
F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
{
handler: F,
}
impl<F> FnToolHandler<F>
where
F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
{
/// Create a new function-based tool handler.
pub fn new(handler: F) -> Self {
Self { handler }
}
}
#[async_trait]
impl<F> ToolHandler for FnToolHandler<F>
where
F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync,
{
async fn execute(&self, call: &ToolCall) -> Result<serde_json::Value> {
(self.handler)(call)
}
}
/// Async function-based tool handler.
#[allow(dead_code)]
pub struct AsyncToolHandler<F, Fut>
where
F: Fn(ToolCall) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<serde_json::Value>> + Send,
{
handler: F,
}
impl<F, Fut> AsyncToolHandler<F, Fut>
where
F: Fn(ToolCall) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<serde_json::Value>> + Send,
{
/// Create a new async tool handler.
pub fn new(handler: F) -> Self {
Self { handler }
}
}
/// Event handler for processing realtime events.
#[async_trait]
pub trait EventHandler: Send + Sync {
/// Called when an audio delta is received (raw PCM bytes).
async fn on_audio(&self, _audio: &[u8], _item_id: &str) -> Result<()> {
Ok(())
}
/// Called when a text delta is received.
async fn on_text(&self, _text: &str, _item_id: &str) -> Result<()> {
Ok(())
}
/// Called when a transcript delta is received.
async fn on_transcript(&self, _transcript: &str, _item_id: &str) -> Result<()> {
Ok(())
}
/// Called when speech is detected.
async fn on_speech_started(&self, _audio_start_ms: u64) -> Result<()> {
Ok(())
}
/// Called when speech ends.
async fn on_speech_stopped(&self, _audio_end_ms: u64) -> Result<()> {
Ok(())
}
/// Called when a response completes.
async fn on_response_done(&self) -> Result<()> {
Ok(())
}
/// Called on any error.
/// Called when the provider transport ends and [`RealtimeRunner::run`] is returning.
///
/// The runner does **not** reconnect automatically. Reconnection is deliberate: it
/// requires deciding what context to replay and, on Gemini, whether a resumption token
/// is still valid. Without this hook `run` returned `Ok(())` on transport loss, which a
/// caller could not tell apart from a graceful [`RealtimeRunner::close`].
///
/// # Example
///
/// ```rust,ignore
/// async fn on_disconnect(&self) -> adk_realtime::Result<()> {
/// tracing::warn!("realtime transport ended; reconnecting");
/// self.reconnect.notify_one();
/// Ok(())
/// }
/// ```
async fn on_disconnect(&self) -> Result<()> {
Ok(())
}
async fn on_error(&self, _error: &RealtimeError) -> Result<()> {
Ok(())
}
}
/// Default no-op event handler.
#[derive(Debug, Clone, Default)]
pub struct NoOpEventHandler;
#[async_trait]
impl EventHandler for NoOpEventHandler {}
/// A tool call the run loop still has to dispatch.
#[derive(Debug, Clone)]
struct PendingToolCall {
call_id: String,
name: String,
arguments: String,
}
/// Configuration for the RealtimeRunner.
#[derive(Clone)]
pub struct RunnerConfig {
/// Whether to automatically execute tool calls.
pub auto_execute_tools: bool,
/// Whether to automatically send tool responses.
pub auto_respond_tools: bool,
/// Maximum concurrent tool executions.
pub max_concurrent_tools: usize,
}
impl Default for RunnerConfig {
fn default() -> Self {
Self { auto_execute_tools: true, auto_respond_tools: true, max_concurrent_tools: 4 }
}
}
/// Builder for RealtimeRunner.
pub struct RealtimeRunnerBuilder {
model: Option<BoxedModel>,
config: RealtimeConfig,
runner_config: RunnerConfig,
tools: HashMap<String, (ToolDefinition, Arc<dyn ToolHandler>)>,
/// The first name registered twice; `build` rejects it.
duplicate_tool: Option<String>,
event_handler: Option<Arc<dyn EventHandler>>,
governance: Option<ToolGovernance>,
control: Option<adk_core::GovernanceControl>,
confirmation: adk_core::ToolConfirmationPolicy,
tool_timeout: std::time::Duration,
tool_result_screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
expose_tool_error_messages: bool,
pricing: Option<RealtimePricing>,
agent_name: String,
}
impl Default for RealtimeRunnerBuilder {
fn default() -> Self {
Self::new()
}
}
impl RealtimeRunnerBuilder {
/// Create a new builder.
pub fn new() -> Self {
Self {
model: None,
config: RealtimeConfig::default(),
runner_config: RunnerConfig::default(),
tools: HashMap::new(),
duplicate_tool: None,
event_handler: None,
governance: None,
control: None,
confirmation: adk_core::ToolConfirmationPolicy::Never,
tool_timeout: DEFAULT_REALTIME_TOOL_TIMEOUT,
tool_result_screen: None,
expose_tool_error_messages: false,
pricing: None,
agent_name: DEFAULT_REALTIME_AGENT_NAME.to_string(),
}
}
/// Names the agent every tool call is governed and metered under: the gate's agent
/// name, the acting agent of each call's fingerprint and audit record, and the agent in
/// the spend key. Defaults to [`DEFAULT_REALTIME_AGENT_NAME`]. A surface that runs an
/// existing agent's tools over a realtime session sets that agent's name, so the
/// agent's tool policy recognises its own tools (spec 3.1 §7.17).
pub fn agent_name(mut self, name: impl Into<String>) -> Self {
self.agent_name = name.into();
self
}
/// Prices each response's reported usage, so the cost committed in the run's spend
/// ledger is the usage's price rather than the run's per-call estimate. Metering needs
/// [`tool_governance`](Self::tool_governance) with a `spend_ledger`.
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::metering::RealtimePricing;
///
/// let runner = RealtimeRunner::builder()
/// .model(model)
/// .tool_governance(config, scope)
/// .realtime_pricing(RealtimePricing {
/// input_audio_micro_usd_per_million: 32_000_000,
/// output_audio_micro_usd_per_million: 64_000_000,
/// ..RealtimePricing::default()
/// })
/// .build()?;
/// ```
pub fn realtime_pricing(mut self, pricing: RealtimePricing) -> Self {
self.pricing = Some(pricing);
self
}
/// Governs every tool call this runner dispatches with `config`, under `scope`.
///
/// The config's `tool_policy`, `governance` kill switches, confirmation handler,
/// approvals, and approval store apply exactly as they do to an agent run, through
/// [`adk_core::authorize_tool_call`]. A call held for confirmation is answered with an
/// error and recorded in the approval store under `scope`. A frozen kill switch ends
/// [`run`](RealtimeRunner::run) with an error.
///
/// Without it, every call still takes the governed path, under `RunConfig::default()`
/// for the user `anonymous` in app `realtime`: no tool policy, so a call runs unless the
/// runner's kill switch ([`RealtimeRunner::governance`]) is frozen or the call needs
/// confirmation ([`require_tool_confirmation`](Self::require_tool_confirmation)), which
/// nobody can then give, so the call is refused.
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::{ApprovalScope, DeclarativePolicy, RunConfig};
///
/// let runner = RealtimeRunner::builder()
/// .model(model)
/// .tool_governance(
/// RunConfig::builder()
/// .tool_policy(Arc::new(DeclarativePolicy::builder().allow("get_weather").build()))
/// .build(),
/// ApprovalScope::new("voice", "user-1", "call-42"),
/// )
/// .build()?;
/// ```
pub fn tool_governance(
mut self,
config: adk_core::RunConfig,
scope: adk_core::ApprovalScope,
) -> Self {
self.governance = Some(ToolGovernance { config, scope });
self
}
/// Attaches `control` as this runner's kill switch, so one control freezes this runner
/// together with the others it is attached to, as `Runner::builder().governance(control)`
/// does. Without it the runner creates its own; either way
/// [`RealtimeRunner::governance`] returns it, and every tool call is checked against it
/// and against the controls of the [`tool_governance`](Self::tool_governance) config.
///
/// # Example
///
/// ```rust
/// use adk_core::GovernanceControl;
/// use adk_realtime::RealtimeRunner;
/// use adk_realtime::model::BoxedModel;
///
/// fn build(model: BoxedModel, control: GovernanceControl) -> adk_realtime::Result<RealtimeRunner> {
/// RealtimeRunner::builder().model(model).governance(control).build()
/// }
/// ```
pub fn governance(mut self, control: adk_core::GovernanceControl) -> Self {
self.control = Some(control);
self
}
/// Sets which tools need a person's approval before they run, as
/// `LlmAgentBuilder::tool_confirmation_policy` does. A call that needs one is decided by
/// the governance config's confirmation handler, approvals, or approval store; with none
/// of them it is refused rather than run.
pub fn tool_confirmation_policy(mut self, policy: adk_core::ToolConfirmationPolicy) -> Self {
self.confirmation = policy;
self
}
/// Requires a person's approval before `tool_name` runs. See
/// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
///
/// # Example
///
/// ```rust
/// use adk_realtime::config::ToolDefinition;
/// use adk_realtime::model::BoxedModel;
/// use adk_realtime::RealtimeRunner;
///
/// fn build(model: BoxedModel) -> adk_realtime::Result<RealtimeRunner> {
/// RealtimeRunner::builder()
/// .model(model)
/// .tool_fn(ToolDefinition::new("refund"), |_call| Ok(serde_json::json!({ "ok": true })))
/// .require_tool_confirmation("refund")
/// .build()
/// }
/// ```
pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
self.confirmation = self.confirmation.with_tool(tool_name);
self
}
/// Requires a person's approval before every tool call. See
/// [`tool_confirmation_policy`](Self::tool_confirmation_policy).
pub fn require_tool_confirmation_for_all(mut self) -> Self {
self.confirmation = adk_core::ToolConfirmationPolicy::Always;
self
}
/// Sets how long a tool may run before its call is answered with a timeout error.
/// Defaults to [`DEFAULT_REALTIME_TOOL_TIMEOUT`].
pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
self.tool_timeout = timeout;
self
}
/// Screens every tool result before it is sent to the model.
///
/// The screen sees each handler's result, or its error response, before
/// `function_call_output` is sent. A result the screen rewrites is sent rewritten; a result it
/// withholds, or that it cannot decide on (`Err`), is replaced by
/// [`result_blocked_response`](adk_core::result_blocked_response), so the runner fails
/// closed. `adk-guardrail`'s `ToolGuardrailSet` is a screen.
///
/// # Example
///
/// ```rust,ignore
/// use adk_guardrail::{PiiRedactor, ResultTextGuardrail, ToolGuardrailSet};
///
/// let runner = RealtimeRunner::builder()
/// .model(model)
/// .tool_fn(ToolDefinition::new("lookup_order"), lookup_order)
/// .tool_result_screen(Arc::new(
/// ToolGuardrailSet::new().with(ResultTextGuardrail::new(PiiRedactor::new())),
/// ))
/// .build()?;
/// ```
pub fn tool_result_screen(mut self, screen: Arc<dyn adk_core::ToolResultScreen>) -> Self {
self.tool_result_screen = Some(screen);
self
}
/// Sends the full message of a handler's error to the model.
///
/// By default a handler that fails is answered with `tool '<name>' failed` only, because
/// the message can quote credentials, internal hosts, or upstream bodies, and the output is
/// sent to the provider and can be spoken to the user. Timeouts and policy refusals keep
/// their message.
pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
self.expose_tool_error_messages = expose;
self
}
/// Set the realtime model.
pub fn model(mut self, model: BoxedModel) -> Self {
self.model = Some(model);
self
}
/// Set the session configuration.
pub fn config(mut self, config: RealtimeConfig) -> Self {
self.config = config;
self
}
/// Set the runner configuration.
pub fn runner_config(mut self, config: RunnerConfig) -> Self {
self.runner_config = config;
self
}
/// Set the system instruction.
pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
self.config.instruction = Some(instruction.into());
self
}
/// Set the voice.
pub fn voice(mut self, voice: impl Into<String>) -> Self {
self.config.voice = Some(voice.into());
self
}
/// Register a tool with its handler.
///
/// Each tool needs a name of its own: [`build`](Self::build) fails when two
/// share one.
pub fn tool(self, definition: ToolDefinition, handler: impl ToolHandler + 'static) -> Self {
self.tool_arc(definition, Arc::new(handler))
}
/// Register a tool with a sync function handler.
pub fn tool_fn<F>(self, definition: ToolDefinition, handler: F) -> Self
where
F: Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync + 'static,
{
self.tool(definition, FnToolHandler::new(handler))
}
/// Register a tool with an `Arc<dyn ToolHandler>` directly.
///
/// This is useful when you already have a shared handler and want to avoid
/// an extra `Arc` wrapping that the `tool()` method would perform.
pub fn tool_arc(mut self, definition: ToolDefinition, handler: Arc<dyn ToolHandler>) -> Self {
let name = definition.name.clone();
if self.tools.insert(name.clone(), (definition, handler)).is_some() {
self.duplicate_tool.get_or_insert(name);
}
self
}
/// Set the event handler.
pub fn event_handler(mut self, handler: impl EventHandler + 'static) -> Self {
self.event_handler = Some(Arc::new(handler));
self
}
/// Set the event handler from an `Arc<dyn EventHandler>` directly.
///
/// This is useful when you already have a shared handler and want to avoid
/// an extra `Arc` wrapping that the `event_handler()` method would perform.
pub fn event_handler_arc(mut self, handler: Arc<dyn EventHandler>) -> Self {
self.event_handler = Some(handler);
self
}
/// Build the runner (does not connect yet).
///
/// # Errors
///
/// Returns a config error when no model was set or when two tools were
/// registered under one name.
pub fn build(self) -> Result<RealtimeRunner> {
let model = self.model.ok_or_else(|| RealtimeError::config("Model is required"))?;
if let Some(name) = self.duplicate_tool {
return Err(RealtimeError::config(format!(
"two tools are registered as '{name}'; the model calls tools by name, so only \
one could ever run. Rename one of them or register it once."
)));
}
// Add tool definitions to config
let mut config = self.config;
if !self.tools.is_empty() {
let tool_defs: Vec<ToolDefinition> =
self.tools.values().map(|(def, _)| def.clone()).collect();
config.tools = Some(tool_defs);
}
let max_concurrent_tools = self.runner_config.max_concurrent_tools.max(1);
// Every call takes the governed path; without a configuration of its own the runner
// governs under the defaults, as an agent under a default `Runner` is governed.
let mut governance = self.governance.unwrap_or_else(|| ToolGovernance {
config: adk_core::RunConfig::default(),
scope: adk_core::ApprovalScope::new(
DEFAULT_REALTIME_AGENT_NAME,
DEFAULT_REALTIME_USER,
format!("realtime-{}", uuid::Uuid::new_v4().simple()),
),
});
let control = self.control.unwrap_or_default();
if !governance.config.governance.iter().any(|existing| existing.same_as(&control)) {
governance.config.governance.push(control.clone());
}
// Every response is metered in the run's spend ledger, as `LlmAgent` meters a call.
let meter = ResponseMeter::for_run(
&governance.config,
&governance.scope.app_name,
&self.agent_name,
model.model_id(),
self.pricing,
);
Ok(RealtimeRunner {
model,
config: Arc::new(RwLock::new(config)),
runner_config: self.runner_config,
tools: self.tools,
event_handler: self.event_handler.unwrap_or_else(|| Arc::new(NoOpEventHandler)),
session: Arc::new(RwLock::new(None)),
state: Arc::new(RwLock::new(RunnerState::Idle)),
pending_tool_response: AtomicBool::new(false),
tool_permits: Arc::new(tokio::sync::Semaphore::new(max_concurrent_tools)),
outstanding_tools: Arc::new(AtomicUsize::new(0)),
response_closed_awaiting_tools: Arc::new(AtomicBool::new(false)),
governance,
control,
confirmation: self.confirmation,
tool_timeout: self.tool_timeout,
tool_result_screen: self.tool_result_screen,
expose_tool_error_messages: self.expose_tool_error_messages,
meter,
agent_name: self.agent_name,
})
}
}
/// A runner that manages a realtime session with tool execution.
///
/// RealtimeRunner provides a high-level interface for:
/// - Connecting to realtime providers
/// - Automatically executing tool calls
/// - Routing events to handlers
/// - Managing the session lifecycle
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::{RealtimeRunner, RealtimeConfig, ToolDefinition};
/// use adk_realtime::openai::OpenAIRealtimeModel;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// let model = OpenAIRealtimeModel::new(api_key, "gpt-realtime-2.1");
///
/// let runner = RealtimeRunner::builder()
/// .model(Box::new(model))
/// .instruction("You are a helpful voice assistant.")
/// .voice("alloy")
/// .tool_fn(
/// ToolDefinition::new("get_weather")
/// .with_description("Get weather for a location"),
/// |call| {
/// Ok(serde_json::json!({"temperature": 72, "condition": "sunny"}))
/// }
/// )
/// .build()?;
///
/// runner.connect().await?;
/// runner.run().await?;
///
/// Ok(())
/// }
/// ```
pub struct RealtimeRunner {
model: BoxedModel,
config: Arc<RwLock<RealtimeConfig>>,
runner_config: RunnerConfig,
tools: HashMap<String, (ToolDefinition, Arc<dyn ToolHandler>)>,
event_handler: Arc<dyn EventHandler>,
session: Arc<RwLock<Option<Arc<dyn crate::session::RealtimeSession>>>>,
state: Arc<RwLock<RunnerState>>,
/// Set when tool output(s) have been sent for the in-flight response and a
/// single follow-up `create_response` is owed once that response finishes.
pending_tool_response: AtomicBool,
/// Bounds how many tool handlers run at once, from
/// [`RunnerConfig::max_concurrent_tools`].
tool_permits: Arc<tokio::sync::Semaphore>,
/// Tool calls dispatched for the current response and not yet finished.
outstanding_tools: Arc<AtomicUsize>,
/// Set when the dispatching response closed while tool calls were still running, so
/// the follow-up `create_response` is owed by whichever tool finishes last.
response_closed_awaiting_tools: Arc<AtomicBool>,
/// Policy, kill switches, and confirmation applied to every dispatched call.
governance: ToolGovernance,
/// The runner's own kill switch, also among `governance.config.governance`.
control: adk_core::GovernanceControl,
/// The tools that need a person's approval before they run.
confirmation: adk_core::ToolConfirmationPolicy,
/// How long one tool call may run.
tool_timeout: std::time::Duration,
/// Screens every tool result before it is sent to the model.
tool_result_screen: Option<Arc<dyn adk_core::ToolResultScreen>>,
/// Whether handler error messages reach the model.
expose_tool_error_messages: bool,
/// Meters each response in the run's spend ledger, when the governance has one.
meter: Option<ResponseMeter>,
/// The agent every tool call is governed and metered under.
agent_name: String,
}
impl RealtimeRunner {
/// Helper to safely acquire a cloned Arc of the current session, dropping the lock.
async fn session_handle(&self) -> Result<Arc<dyn crate::session::RealtimeSession>> {
let guard = self.session.read().await;
guard.as_ref().cloned().ok_or_else(|| RealtimeError::connection("Not connected"))
}
/// Create a new builder.
pub fn builder() -> RealtimeRunnerBuilder {
RealtimeRunnerBuilder::new()
}
/// The runner's kill switch: the control passed to
/// [`RealtimeRunnerBuilder::governance`], or the one the runner created. While it is
/// frozen no tool call runs, and the dispatch, and so [`run`](Self::run), ends with the
/// `governance.frozen` error.
///
/// # Example
///
/// ```rust
/// use adk_realtime::RealtimeRunner;
///
/// fn stop_all_tools(runner: &RealtimeRunner) {
/// runner.governance().freeze("incident 4012");
/// }
/// ```
pub fn governance(&self) -> &adk_core::GovernanceControl {
&self.control
}
/// The run config every tool call is governed under: the config passed to
/// [`RealtimeRunnerBuilder::tool_governance`], or `RunConfig::default()`, with the
/// runner's kill switch among its `governance` controls.
pub fn run_config(&self) -> &adk_core::RunConfig {
&self.governance.config
}
/// Connect to the realtime provider.
pub async fn connect(&self) -> Result<()> {
let config = self.config.read().await.clone();
let session = self.model.connect(config).await?;
let mut guard = self.session.write().await;
*guard = Some(session.into());
Ok(())
}
/// Check if currently connected.
pub async fn is_connected(&self) -> bool {
let guard = self.session.read().await;
guard.as_ref().map(|s| s.is_connected()).unwrap_or(false)
}
/// Get the session ID if connected.
pub async fn session_id(&self) -> Option<String> {
let guard = self.session.read().await;
guard.as_ref().map(|s| s.session_id().to_string())
}
/// Send a client event directly to the session.
///
/// This method intercepts internal control-plane events (like `UpdateSession`) to route
/// them through the provider-agnostic orchestration layer instead of forwarding raw JSON
/// to the underlying WebSocket transport. This guarantees that `adk-realtime` never leaks
/// invalid event payloads to providers (e.g., OpenAI or Gemini) and universally bridges
/// the Cognitive Handoff mechanics transparently.
pub async fn send_client_event(&self, event: crate::events::ClientEvent) -> Result<()> {
match event {
crate::events::ClientEvent::UpdateSession { instructions, tools } => {
let update_config = SessionUpdateConfig(crate::config::RealtimeConfig {
instruction: instructions,
tools,
..Default::default()
});
self.update_session(update_config).await
}
other => {
let session = self.session_handle().await?;
session.send_event(other).await
}
}
}
/// Internal helper to merge a `SessionUpdateConfig` delta into the canonical `RealtimeConfig` state.
///
/// **Why this exists**: The `RealtimeRunner` must maintain an absolute, single source of truth
/// for its configuration (`self.config`). Orchestrators fire `SessionUpdateConfig`s as sparse
/// partial deltas (intents to hot-swap instructions or tools mid-flight). By accumulating
/// these sparse updates into the single `base` config, any subsequent "Phantom Reconnect"
/// (e.g., due to a Gemini domain shift or an unexpected network drop) natively inherits all
/// prior hot-swaps alongside the immutable transport parameters (like sample rates) defined at startup.
///
/// Note: This is intentionally narrow and specifically scoped to merge only
/// hot-swappable cognitive fields (instruction, tools, voice, temperature, extra).
/// Transport-level attributes like sample rates and audio formats are not dynamically swappable.
fn merge_config(base: &mut RealtimeConfig, update: &SessionUpdateConfig) {
if let Some(instruction) = &update.0.instruction {
base.instruction = Some(instruction.clone());
}
if let Some(tools) = &update.0.tools {
base.tools = Some(tools.clone());
}
if let Some(voice) = &update.0.voice {
base.voice = Some(voice.clone());
}
if let Some(temp) = update.0.temperature {
base.temperature = Some(temp);
}
if let Some(extra) = &update.0.extra {
base.extra = Some(extra.clone());
}
}
/// Update the session configuration.
///
/// Delegates to [`Self::update_session_with_bridge`] with no bridge message.
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::config::{SessionUpdateConfig, RealtimeConfig};
///
/// async fn example(runner: &adk_realtime::RealtimeRunner) {
/// let update = SessionUpdateConfig(
/// RealtimeConfig::default().with_instruction("You are now a pirate.")
/// );
/// runner.update_session(update).await.unwrap();
/// }
/// ```
pub async fn update_session(&self, config: SessionUpdateConfig) -> Result<()> {
self.update_session_with_bridge(config, None).await
}
/// Update the session configuration, optionally injecting a bridge message if
/// a transport resumption (Phantom Reconnect) occurs.
///
/// The RealtimeRunner will attempt to mutate the session natively if the underlying
/// API supports it (e.g., OpenAI). If it does not (e.g., Gemini), the Runner will
/// queue a transport resumption, executing it only when the session
/// is in a resumable state (Idle) to prevent data corruption.
///
/// The runner keeps only one pending resumption. If a new session update arrives while
/// a resumption is already pending, the previous pending resumption is replaced. This is
/// intentional: pending session updates represent desired end state, not an ordered command queue.
/// The policy is last write wins.
pub async fn update_session_with_bridge(
&self,
config: SessionUpdateConfig,
bridge_message: Option<String>,
) -> Result<()> {
// 1. Merge the incoming delta into the runner's canonical, persisted configuration.
// This ensures that any future reconnects (e.g., due to network drops) naturally
// inherit this latest state.
let mut full_config = self.config.write().await;
Self::merge_config(&mut full_config, &config);
let cloned_config = full_config.clone();
drop(full_config); // Free the write lock early to avoid deadlocks.
// 2. Safely obtain a cloned handle of the active session.
let session = self.session_handle().await?;
// 3. Delegate the mutation attempt to the provider-specific adapter.
match session.mutate_context(cloned_config).await? {
// PATH A: Native Mutability (e.g., OpenAI)
// The provider natively updated the context over the active WebSocket.
ContextMutationOutcome::Applied => {
tracing::info!("Context mutated natively mid-flight.");
// Since the transport wasn't dropped, we can inject the bridge message
// immediately as a standard user message to update the model's short-term memory.
if let Some(msg) = bridge_message {
let event = crate::events::ClientEvent::Message {
role: "user".to_string(),
parts: vec![adk_core::types::Part::Text { text: msg }],
};
session.send_event(event).await?;
}
Ok(())
}
// PATH B: Rigid Initialization (e.g., Gemini)
// The provider requires us to tear down the WebSocket and establish a new one (Phantom Reconnect).
ContextMutationOutcome::RequiresResumption(new_config) => {
drop(session); // CRITICAL: Drop the cloned handle before attempting state mutation.
// 4. Check the Runner's internal state machine to ensure it is safe to tear down the socket.
let mut state_guard = self.state.write().await;
if *state_guard == RunnerState::Idle {
// Safe to reconnect: The model is neither generating audio nor executing a tool.
drop(state_guard); // Free state lock before the heavy async network operation.
tracing::info!("Runner is idle. Executing resumption immediately.");
if let Err(e) =
self.execute_resumption((*new_config).clone(), bridge_message.clone()).await
{
tracing::error!("Immediate resumption failed: {}. Queueing for retry.", e);
// If the reconnect fails (e.g., transient network issue), we must not lose the mutation intent.
// We push it back into the queue for the background loop to retry.
let mut fallback_state = self.state.write().await;
*fallback_state = RunnerState::PendingResumption {
config: Box::new(*new_config),
bridge_message,
attempts: 1,
};
return Err(e);
}
} else {
// Unsafe to reconnect: Tearing down the socket now would corrupt the in-flight context.
// We must queue the mutation. The event loop will execute it once it returns to Idle.
if let RunnerState::PendingResumption { .. } = *state_guard {
tracing::warn!(
"Runner already had a pending resumption. Overwriting with last-write-wins policy."
);
} else {
tracing::info!("Runner is busy ({:?}). Queueing resumption.", *state_guard);
}
// Queue the intent using a last-write-wins policy.
*state_guard = RunnerState::PendingResumption {
config: new_config,
bridge_message,
attempts: 0,
};
}
Ok(())
}
}
}
/// Internal helper to execute a transport resumption (teardown and rebuild).
async fn execute_resumption(
&self,
new_config: crate::config::RealtimeConfig,
bridge_message: Option<String>,
) -> Result<()> {
tracing::warn!("Executing transport resumption with new configuration.");
// 1. Extract the old session safely under the write lock.
let old_session = {
let mut write_guard = self.session.write().await;
write_guard.take()
};
// 2. Explicitly tear down the old WebSocket connection to release upstream resources.
// Do this WITHOUT holding the lock across `.await`.
if let Some(session) = old_session
&& let Err(e) = session.close().await
{
tracing::warn!("Failed to cleanly close old session during resumption: {}", e);
}
// 3. Establish a brand new connection using the provider-agnostic factory interface.
// If the provider supports resumption natively (like Gemini), the `new_config`
// payload already contains the cached `resumeToken`.
let new_session = self.model.connect(new_config).await?;
// 4. Overwrite the active session pointer with the newly connected transport.
{
let mut write_guard = self.session.write().await;
*write_guard = Some(new_session.into());
}
// 5. If the orchestrator provided a bridge message (e.g. to explain the domain shift),
// safely inject it into the new connection's context window.
if let Some(msg) = bridge_message {
self.inject_bridge_message(msg).await?;
}
tracing::info!("Resumption complete. New transport established.");
Ok(())
}
/// Internal helper to safely inject a bridge message directly into the active session.
///
/// This intentionally bypasses the `send_client_event` router to avoid `E0733`
/// (un-Boxed async recursion) where `send_client_event` -> `update_session` ->
/// `execute_resumption` -> `send_client_event` creates an infinite compiler loop.
async fn inject_bridge_message(&self, msg: String) -> Result<()> {
tracing::info!("Injecting bridge message post-resumption.");
let event = crate::events::ClientEvent::Message {
role: "user".to_string(),
parts: vec![adk_core::types::Part::Text { text: msg }],
};
let session = self.session_handle().await?;
session.send_event(event).await
}
/// Send a typed raw-audio chunk to the session.
///
/// This preserves the audio format at the provider boundary and lets the
/// provider choose its native encoding path. Prefer this method when the
/// caller already owns raw audio bytes.
pub async fn send_audio_chunk(&self, audio: &crate::audio::AudioChunk) -> Result<()> {
let session = self.session_handle().await?;
session.send_audio(audio).await
}
/// Send base64-encoded audio to the session.
///
/// This compatibility entry point is useful when the caller already has a
/// base64 payload. Raw-audio callers should use
/// [`send_audio_chunk`](Self::send_audio_chunk) to avoid forcing an encoding
/// decision at the provider-neutral runner boundary.
pub async fn send_audio(&self, audio_base64: &str) -> Result<()> {
let session = self.session_handle().await?;
session.send_audio_base64(audio_base64).await
}
/// Send text to the session.
pub async fn send_text(&self, text: &str) -> Result<()> {
let session = self.session_handle().await?;
session.send_text(text).await
}
/// Send a base64-encoded video/image frame (e.g. `image/jpeg`) for
/// multimodal input, where the provider supports it (Gemini Live; OpenAI as
/// an image-in-context item).
pub async fn send_video_frame(&self, mime_type: &str, data_base64: &str) -> Result<()> {
let session = self.session_handle().await?;
session.send_video_frame(mime_type, data_base64).await
}
/// Commit the audio buffer (for manual VAD mode).
pub async fn commit_audio(&self) -> Result<()> {
let session = self.session_handle().await?;
session.commit_audio().await
}
/// Trigger a response from the model.
pub async fn create_response(&self) -> Result<()> {
let session = self.session_handle().await?;
session.create_response().await
}
/// Interrupt the current response.
pub async fn interrupt(&self) -> Result<()> {
let session = self.session_handle().await?;
session.interrupt().await
}
/// Get the next raw event from the session.
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::events::ServerEvent;
/// use tracing::{info, error};
///
/// async fn process_events(runner: &adk_realtime::RealtimeRunner) {
/// while let Some(event) = runner.next_event().await {
/// match event {
/// Ok(ServerEvent::SpeechStarted { .. }) => info!("User is speaking"),
/// Ok(_) => info!("Received other event"),
/// Err(e) => error!("Error: {e}"),
/// }
/// }
/// }
/// ```
/// Why the provider ended the stream, once [`Self::next_event`] has returned
/// `None`.
///
/// Callers that poll `next_event` never see the runner's `on_disconnect`
/// dispatch, so without this a provider that deliberately closed an idle
/// session is indistinguishable from a dropped socket — and both get
/// recorded as the same generic stream failure.
pub async fn disconnect_reason(&self) -> Option<crate::session::DisconnectReason> {
self.session_handle().await.ok().and_then(|session| session.disconnect_reason())
}
pub async fn next_event(&self) -> Option<Result<ServerEvent>> {
let session = match self.session_handle().await {
Ok(session) => session,
Err(_) => {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
return None;
}
};
// Some sessions might yield inside next_event, but just in case, yield here too
tokio::task::yield_now().await;
let event = session.next_event().await?;
if let Ok(event) = &event
&& let Err(error) = self.observe_event(event).await
{
return Some(Err(error));
}
Some(event)
}
/// Meters `event` when it starts or ends a response.
///
/// Returns the usage a `ResponseDone` reported, priced with
/// [`realtime_pricing`](RealtimeRunnerBuilder::realtime_pricing).
///
/// # Errors
///
/// [`RealtimeError::SpendRefused`] when the run's spend ledger refuses the response's
/// hold; the caller ends the session.
pub(crate) async fn observe_event(
&self,
event: &ServerEvent,
) -> Result<Option<adk_core::UsageMetadata>> {
let Some(meter) = &self.meter else {
return Ok(None);
};
match event {
ServerEvent::ResponseCreated { .. } => {
meter.begin_response().await?;
Ok(None)
}
ServerEvent::ResponseDone { response, .. } => meter.end_response(response).await,
_ => Ok(None),
}
}
/// The agent every tool call is governed and metered under.
#[cfg(feature = "integration")]
pub(crate) fn agent_name(&self) -> &str {
&self.agent_name
}
/// The approval scope held calls are recorded under.
#[cfg(feature = "integration")]
pub(crate) fn approval_scope(&self) -> &adk_core::ApprovalScope {
&self.governance.scope
}
/// Counts a tool dispatch the caller runs outside [`run`](Self::run), so the follow-up
/// response waits for it; pair with [`end_dispatch`](Self::end_dispatch).
#[cfg(feature = "integration")]
pub(crate) fn begin_dispatch(&self) {
self.outstanding_tools.fetch_add(1, Ordering::AcqRel);
}
/// Marks a dispatch counted by [`begin_dispatch`](Self::begin_dispatch) as finished.
/// Returns `true` when the dispatching response closed meanwhile, so the caller owes
/// the follow-up response ([`respond_after_tools`](Self::respond_after_tools)).
#[cfg(feature = "integration")]
pub(crate) fn end_dispatch(&self) -> bool {
self.outstanding_tools.fetch_sub(1, Ordering::AcqRel) == 1
&& self.response_closed_awaiting_tools.swap(false, Ordering::AcqRel)
}
/// Send a tool response to the session.
///
/// # Example
///
/// ```rust,ignore
/// use adk_realtime::events::ToolResponse;
/// use serde_json::json;
///
/// async fn example(runner: &adk_realtime::RealtimeRunner) {
/// let response = ToolResponse {
/// call_id: "call_123".to_string(),
/// output: json!({"temperature": 72}),
/// };
/// runner.send_tool_response(response).await.unwrap();
/// }
/// ```
pub async fn send_tool_response(&self, response: ToolResponse) -> Result<()> {
let session = self.session_handle().await?;
session.send_tool_response(response).await
}
/// Execute a tool call against the registered handlers, sending the result
/// back to the model when `auto_respond_tools` is enabled.
///
/// This is the same dispatch the [`run`](Self::run) loop performs for a
/// `response.function_call_arguments.done` event, exposed so that callers
/// driving the session manually via [`next_event`](Self::next_event) — such
/// as `IntegratedRealtimeRunner` (available with the `integration` feature) —
/// can execute tools without re-implementing the lookup/respond logic.
pub async fn dispatch_tool_call(
&self,
call_id: &str,
name: &str,
arguments: &str,
) -> Result<()> {
self.execute_tool_call(call_id, name, arguments).await
}
/// Sends a tool result the caller produced, honouring `auto_respond_tools`.
///
/// Used by the integration layer, which runs ADK tools through its own policy pipeline and
/// then needs the result delivered exactly as `execute_tool_call` would deliver it: the
/// output is sent now, and the single follow-up `create_response` is deferred until the
/// dispatching response closes, so several parallel calls produce one response.
///
/// # Example
///
/// ```rust,ignore
/// let result = my_policy_pipeline.run(&call).await?;
/// runner.send_tool_result(&call.call_id, result).await?;
/// ```
pub async fn send_tool_result(&self, call_id: &str, output: serde_json::Value) -> Result<()> {
if !self.runner_config.auto_respond_tools {
return Ok(());
}
if let Ok(session) = self.session_handle().await {
session.send_tool_output(ToolResponse { call_id: call_id.to_string(), output }).await?;
self.pending_tool_response.store(true, Ordering::Release);
}
Ok(())
}
/// Run the event loop, processing events until disconnected.
pub async fn run(&self) -> Result<()> {
use futures::stream::{FuturesUnordered, StreamExt};
// Tool handlers run as futures on this set rather than inline, so reading the next
// provider event never waits for a tool. `max_concurrent_tools` bounds how many
// are past their permit acquisition at once.
let mut running_tools = FuturesUnordered::new();
loop {
let session = self.session_handle().await?;
let old_session_id = session.session_id().to_string();
// With no tools in flight there is nothing to drain, and polling an empty
// `FuturesUnordered` in a `select!` would spin.
let event = if running_tools.is_empty() {
session.next_event().await
} else {
tokio::select! {
biased;
Some(finished) = running_tools.next() => {
let () = finished?;
continue;
}
event = session.next_event() => event,
}
};
match event {
Some(Ok(event)) => {
if let Err(error) = self.observe_event(&event).await {
self.event_handler.on_error(&error).await?;
let _ = self.close().await;
return Err(error);
}
if let Some(call) = self.handle_event(event).await? {
self.outstanding_tools.fetch_add(1, Ordering::AcqRel);
running_tools.push(self.run_tool_call(call));
}
}
Some(Err(e)) => {
self.event_handler.on_error(&e).await?;
return Err(e);
}
None => {
// Session closed or swapped out. Check if a new session was installed (e.g., during reconnect).
let current_session_id = self.session_id().await;
if let Some(id) = current_session_id
&& id != old_session_id
{
// A new session handle was installed concurrently. Continue polling.
continue;
}
// A real disconnect. Let dispatched tools finish so their output and
// the follow-up response are not dropped mid-flight.
while let Some(finished) = running_tools.next().await {
finished?;
}
// Surfaced distinctly: `run` returning `Ok(())` alone cannot be told
// apart from a graceful `close`.
self.event_handler.on_disconnect().await?;
break;
}
}
}
Ok(())
}
/// Run one dispatched tool call under the configured concurrency bound.
///
/// The permit is acquired inside the future so queueing a call never blocks the event
/// loop; the bound applies to execution, not to admission.
async fn run_tool_call(&self, call: PendingToolCall) -> Result<()> {
let permit = Arc::clone(&self.tool_permits).acquire_owned().await;
let result = self.execute_tool_call(&call.call_id, &call.name, &call.arguments).await;
drop(permit);
// The follow-up response is owed once *every* dispatched tool is in and the
// dispatching response has closed, whichever happens last. Before tools ran
// concurrently, ordering was implicit: `ResponseDone` could not arrive until the
// inline await returned. It can now, so the last tool to finish issues it.
if self.outstanding_tools.fetch_sub(1, Ordering::AcqRel) == 1
&& self.response_closed_awaiting_tools.swap(false, Ordering::AcqRel)
{
self.respond_after_tools().await?;
}
result
}
/// Process a single event.
async fn handle_event(&self, event: ServerEvent) -> Result<Option<PendingToolCall>> {
// Track state transitions before forwarding the event
match &event {
ServerEvent::ResponseCreated { .. } => {
let mut state = self.state.write().await;
if let RunnerState::Idle = *state {
*state = RunnerState::Generating;
}
}
ServerEvent::FunctionCallDone { .. } => {
let mut state = self.state.write().await;
if let RunnerState::Generating | RunnerState::Idle = *state {
*state = RunnerState::ExecutingTool;
}
}
_ => {}
}
match event {
ServerEvent::AudioDelta { delta, item_id, .. } => {
self.event_handler.on_audio(&delta, &item_id).await?;
}
ServerEvent::TextDelta { delta, item_id, .. } => {
self.event_handler.on_text(&delta, &item_id).await?;
}
ServerEvent::TranscriptDelta { delta, item_id, .. } => {
self.event_handler.on_transcript(&delta, &item_id).await?;
}
ServerEvent::SpeechStarted { audio_start_ms, .. } => {
self.event_handler.on_speech_started(audio_start_ms).await?;
}
ServerEvent::SpeechStopped { audio_end_ms, .. } => {
self.event_handler.on_speech_stopped(audio_end_ms).await?;
}
ServerEvent::ResponseDone { .. } => {
self.event_handler.on_response_done().await?;
// If this response dispatched tool call(s), send the one owed
// follow-up response now that it's closed.
self.respond_after_tools().await?;
self.check_resumption_queue().await?;
}
ServerEvent::FunctionCallDone { call_id, name, arguments, .. }
if self.runner_config.auto_execute_tools =>
{
// Returned rather than awaited: the run loop dispatches it so event
// intake — audio deltas included — continues while the tool runs.
return Ok(Some(PendingToolCall { call_id, name, arguments }));
}
ServerEvent::SessionUpdated { session, .. } => {
// Check if the generic session update contains a resumption token
if let Some(token) = session.get("resumeToken").and_then(|t| t.as_str()) {
tracing::info!(
"Received Gemini sessionResumption token, saving for future reconnects."
);
let mut config = self.config.write().await;
let mut extra = config.extra.clone().unwrap_or_else(|| serde_json::json!({}));
extra["resumeToken"] = serde_json::Value::String(token.to_string());
config.extra = Some(extra);
}
}
ServerEvent::Error { error, .. } => {
let err = RealtimeError::server(error.code.unwrap_or_default(), error.message);
self.event_handler.on_error(&err).await?;
}
_ => {
// Ignore other events
}
}
Ok(None)
}
/// Safely transitions the runner back to Idle and executes any queued resumptions.
async fn check_resumption_queue(&self) -> Result<()> {
// 1. Acquire the state lock to inspect the queue.
let mut state = self.state.write().await;
// 2. Extract the pending configuration and attempt count if one exists.
let pending =
if let RunnerState::PendingResumption { config, bridge_message, attempts } = &*state {
Some((config.clone(), bridge_message.clone(), *attempts))
} else {
None
};
if let Some((config, bridge_message, attempts)) = pending {
tracing::info!(
"Executing queued resumption after turn completion. (Attempt {})",
attempts + 1
);
// 3. Mark the state as Idle so the background loop is unblocked.
*state = RunnerState::Idle;
// 4. Release the state lock *before* performing the heavy async socket connection.
drop(state);
// 5. Attempt the actual transport teardown/rebuild.
if let Err(e) = self.execute_resumption((*config).clone(), bridge_message.clone()).await
{
tracing::error!("Resumption failed: {}.", e);
// 6. If the reconnect fails (e.g., transient network error), re-acquire the lock
// to safely handle the retry logic without crashing the event loop.
let mut fallback_state = self.state.write().await;
// 7. Enforce a maximum retry budget to prevent infinite "hot-looping"
if attempts + 1 >= 3 {
tracing::error!(
"Maximum resumption attempts reached (3). Dropping queued mutation to prevent infinite loop."
);
*fallback_state = RunnerState::Idle;
} else {
tracing::info!("Restoring pending queue state for retry.");
*fallback_state = RunnerState::PendingResumption {
config,
bridge_message,
attempts: attempts + 1,
};
}
// 8. Do not return Err(e) here, as that would permanently kill the `run()` loop.
// Instead, report the error to the downstream handler and allow the event loop to continue spinning.
let _ = self.event_handler.on_error(&e).await;
}
} else {
// No resumptions were queued; simply mark as Idle.
*state = RunnerState::Idle;
}
Ok(())
}
/// Runs one call through the governed path: the
/// [`tool_governance`](RealtimeRunnerBuilder::tool_governance) config, or the defaults,
/// with the runner's kill switch and confirmation policy.
///
/// # Errors
///
/// Returns [`RealtimeError::ToolError`] when a kill switch is frozen or the
/// confirmation handler or approval store fails; the run ends.
pub(crate) async fn authorize_tool_call(
&self,
mut call: adk_core::GovernedCall,
) -> Result<adk_core::ToolAuthorization> {
call.requires_confirmation |= self.confirmation.requires_confirmation(&call.tool_name);
let governance = &self.governance;
let gate = adk_core::ToolGate::new(
&governance.config,
&self.agent_name,
&governance.scope.session_id,
governance.scope.clone(),
);
adk_core::authorize_tool_call(&gate, call)
.await
.map_err(|error| RealtimeError::ToolError(error.to_string()))
}
/// Withdraws `request`, a call's confirmation request that will not be waited on, so no
/// decision on it authorizes an identical call ([`adk_core::withdraw_held_call`]).
#[cfg(feature = "integration")]
pub(crate) async fn withdraw_held_call(
&self,
request: &adk_core::ToolConfirmationRequest,
) -> Result<()> {
let governance = &self.governance;
let gate = adk_core::ToolGate::new(
&governance.config,
&self.agent_name,
&governance.scope.session_id,
governance.scope.clone(),
);
adk_core::withdraw_held_call(&gate, request)
.await
.map_err(|error| RealtimeError::ToolError(error.to_string()))
}
/// How long one tool call may run.
#[cfg(feature = "integration")]
pub(crate) fn tool_timeout(&self) -> std::time::Duration {
self.tool_timeout
}
/// Whether tool error messages reach the model.
#[cfg(feature = "integration")]
pub(crate) fn exposes_tool_error_messages(&self) -> bool {
self.expose_tool_error_messages
}
/// Runs the configured result screen, if any, on `result`, returning the result to deliver
/// and whether the screen withheld it.
pub(crate) async fn screen_tool_result(
&self,
name: &str,
args: &serde_json::Value,
result: serde_json::Value,
) -> (serde_json::Value, bool) {
match &self.tool_result_screen {
Some(screen) => screen_result(screen.as_ref(), name, args, result).await,
None => (result, false),
}
}
/// Whether tool error messages may be logged: the `record_payloads` of the config passed to
/// [`RealtimeRunnerBuilder::tool_governance`]. Without one, only content-free fields are.
pub(crate) fn records_payloads(&self) -> bool {
self.governance.config.record_payloads
}
/// Execute a tool call and optionally send the response.
async fn execute_tool_call(&self, call_id: &str, name: &str, arguments: &str) -> Result<()> {
let handler = self.tools.get(name).map(|(definition, h)| (definition, h.clone()));
let result = match (handler, parse_tool_arguments(arguments)) {
(None, _) => serde_json::json!({ "error": format!("Unknown tool: {name}") }),
(Some(_), Err(reason)) => {
serde_json::json!({ "error": format!("Tool '{name}' was not run: {reason}") })
}
(Some((definition, handler)), Ok(args)) => {
let screened_args = self.tool_result_screen.as_ref().map(|_| args.clone());
// Native handlers declare no read-only flag, so the policy treats them as
// having side effects.
let mut call = adk_core::GovernedCall::new(name, call_id, args);
call.origin = Some(definition.handler_origin());
let result = match self.authorize_tool_call(call).await? {
adk_core::ToolAuthorization::Execute { args, .. } => {
let call = ToolCall {
call_id: call_id.to_string(),
name: name.to_string(),
arguments: args,
};
match tokio::time::timeout(self.tool_timeout, handler.execute(&call)).await
{
Ok(Ok(value)) => value,
Ok(Err(e)) => {
// A message can quote credentials or internal hosts.
if self.records_payloads() {
tracing::warn!(
tool.name = %name,
error.kind = e.kind(),
error.message = %e,
"realtime tool handler failed"
);
} else {
tracing::warn!(
tool.name = %name,
error.kind = e.kind(),
"realtime tool handler failed"
);
}
if self.expose_tool_error_messages {
serde_json::json!({ "error": e.to_string() })
} else {
serde_json::json!({ "error": format!("tool '{name}' failed") })
}
}
Err(_) => serde_json::json!({
"error": format!(
"Tool '{name}' timed out after {:?}",
self.tool_timeout
)
}),
}
}
adk_core::ToolAuthorization::Refuse { reason, .. } => {
serde_json::json!({ "error": reason })
}
// A native handler's call is not held in the session, so it waits only
// where an approval store or service can take a decision on it.
adk_core::ToolAuthorization::Pending { reason, .. } => {
if holds_reach_an_approver(&self.governance.config) {
serde_json::json!({ "error": reason })
} else {
serde_json::json!({ "error": no_approver_refusal(name, &reason) })
}
}
};
match screened_args {
Some(args) => self.screen_tool_result(name, &args, result).await.0,
None => result,
}
}
};
if self.runner_config.auto_respond_tools {
let response = ToolResponse { call_id: call_id.to_string(), output: result };
if let Ok(session) = self.session_handle().await {
// Send the output now, but defer the response trigger: several
// parallel tool calls in one response must produce a *single*
// `create_response`, issued once the dispatch response finishes
// (see `respond_after_tools`). Firing one per output collides
// with the still-active response on OpenAI.
session.send_tool_output(response).await?;
self.pending_tool_response.store(true, Ordering::Release);
}
}
Ok(())
}
/// The system instruction the next connection will use.
///
/// Exposed so callers and tests can confirm what context a session was actually created
/// with, rather than inferring it from log lines.
pub async fn instruction(&self) -> Option<String> {
self.config.read().await.instruction.clone()
}
/// Prepends a context block to the system instruction before connecting.
///
/// The integration layer uses this to carry prior conversation history and recalled memory
/// into the provider session. Call it before [`RealtimeRunner::connect`]: providers read
/// the instruction at session creation, so a later change needs `update_session`.
///
/// # Example
///
/// ```rust,ignore
/// runner.prepend_instruction_context("Previously discussed: the refund policy.").await;
/// runner.connect().await?;
/// ```
pub async fn prepend_instruction_context(&self, block: &str) {
if block.is_empty() {
return;
}
let mut config = self.config.write().await;
config.instruction = Some(match config.instruction.take() {
Some(existing) if !existing.is_empty() => format!("{block}\n\n{existing}"),
_ => block.to_string(),
});
}
/// Trigger the single follow-up response owed after a tool-dispatching turn.
///
/// Call this when a response finishes (`ResponseDone`). If tool output(s)
/// were sent back during that response (`auto_respond_tools`), the model now
/// needs one `create_response` to speak its answer — issued here, after the
/// dispatch response is closed and every parallel tool output is in, rather
/// than once per tool call. Gemini's `create_response` is a no-op, so this is
/// safely uniform across providers. No-op when nothing is pending.
pub async fn respond_after_tools(&self) -> Result<()> {
// Tools run concurrently with event intake, so this can be reached before their
// output is in. Defer to the last tool to finish rather than firing a response the
// model cannot yet answer — or, worse, dropping it because
// `pending_tool_response` is not set yet.
if self.outstanding_tools.load(Ordering::Acquire) > 0 {
self.response_closed_awaiting_tools.store(true, Ordering::Release);
return Ok(());
}
if self.pending_tool_response.swap(false, Ordering::AcqRel)
&& let Ok(session) = self.session_handle().await
{
session.create_response().await?;
}
Ok(())
}
/// Close the session.
pub async fn close(&self) -> Result<()> {
if let Some(meter) = &self.meter {
meter.abandon().await;
}
if let Ok(session) = self.session_handle().await {
session.close().await?;
}
Ok(())
}
}
#[cfg(test)]
mod runner_tests {
use super::*;
use crate::audio::{AudioChunk, AudioFormat};
use crate::events::{ClientEvent, ToolResponse};
use crate::model::RealtimeModel;
use crate::session::{BoxedSession, ContextMutationOutcome, RealtimeSession};
use std::pin::Pin;
use std::sync::atomic::AtomicUsize;
/// A model just good enough to satisfy the builder (never connects in tests).
struct MockModel;
#[async_trait]
impl RealtimeModel for MockModel {
fn provider(&self) -> &str {
"mock"
}
fn model_id(&self) -> &str {
"mock"
}
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) -> Result<BoxedSession> {
Err(RealtimeError::connection("mock model does not connect"))
}
}
/// Records which provider-session entry points the runner calls.
#[derive(Default)]
struct Counts {
raw_audio: AtomicUsize,
base64_audio: AtomicUsize,
last_audio: parking_lot::Mutex<Option<AudioChunk>>,
tool_output: AtomicUsize,
tool_response: AtomicUsize,
create_response: AtomicUsize,
last_output: parking_lot::Mutex<Option<serde_json::Value>>,
}
struct RecordingSession {
counts: Arc<Counts>,
}
#[async_trait]
impl RealtimeSession for RecordingSession {
fn session_id(&self) -> &str {
"mock-session"
}
fn is_connected(&self) -> bool {
true
}
async fn send_audio(&self, audio: &AudioChunk) -> Result<()> {
self.counts.raw_audio.fetch_add(1, Ordering::SeqCst);
*self.counts.last_audio.lock() = Some(audio.clone());
Ok(())
}
async fn send_audio_base64(&self, _audio: &str) -> Result<()> {
self.counts.base64_audio.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn send_text(&self, _text: &str) -> Result<()> {
Ok(())
}
async fn send_tool_response(&self, _response: ToolResponse) -> Result<()> {
self.counts.tool_response.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn send_tool_output(&self, response: ToolResponse) -> Result<()> {
self.counts.tool_output.fetch_add(1, Ordering::SeqCst);
*self.counts.last_output.lock() = Some(response.output);
Ok(())
}
async fn commit_audio(&self) -> Result<()> {
Ok(())
}
async fn clear_audio(&self) -> Result<()> {
Ok(())
}
async fn create_response(&self) -> Result<()> {
self.counts.create_response.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn interrupt(&self) -> Result<()> {
Ok(())
}
async fn send_event(&self, _event: ClientEvent) -> Result<()> {
Ok(())
}
async fn next_event(&self) -> Option<Result<ServerEvent>> {
None
}
fn events(&self) -> Pin<Box<dyn futures::Stream<Item = Result<ServerEvent>> + Send + '_>> {
Box::pin(futures::stream::empty())
}
async fn close(&self) -> Result<()> {
Ok(())
}
async fn mutate_context(&self, _config: RealtimeConfig) -> Result<ContextMutationOutcome> {
Ok(ContextMutationOutcome::Applied)
}
}
fn tool_def(name: &str) -> ToolDefinition {
ToolDefinition::new(name)
}
#[test]
fn runner_builder_rejects_two_tools_with_one_name() {
let builder = || {
RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.tool_fn(tool_def("pay"), |_call| Ok(serde_json::json!({ "paid": 1 })))
};
let Err(err) = builder()
.tool_fn(tool_def("pay"), |_call| Ok(serde_json::json!({ "paid": 2 })))
.build()
else {
panic!("two tools named `pay` must fail the build");
};
assert!(matches!(err, RealtimeError::ConfigError(_)), "{err}");
assert!(err.to_string().contains("'pay'"), "{err}");
assert!(
builder()
.tool_fn(tool_def("refund"), |_call| Ok(serde_json::json!({})))
.build()
.is_ok()
);
}
#[test]
fn agent_builder_rejects_two_tools_with_one_name() {
struct Lookup;
#[async_trait]
impl adk_core::Tool for Lookup {
fn name(&self) -> &str {
"lookup"
}
fn description(&self) -> &str {
"looks things up"
}
async fn execute(
&self,
_ctx: Arc<dyn adk_core::ToolContext>,
args: serde_json::Value,
) -> adk_core::Result<serde_json::Value> {
Ok(args)
}
}
let Err(err) = crate::agent::RealtimeAgent::builder("voice")
.model(Arc::new(MockModel) as BoxedModel)
.tool(Arc::new(Lookup))
.tool(Arc::new(Lookup))
.build()
else {
panic!("two tools named `lookup` must fail the build");
};
assert_eq!(err.code, adk_core::DUPLICATE_TOOL_NAME_CODE);
assert!(err.message.contains("'lookup'"), "{}", err.message);
}
fn ok_tool() -> FnToolHandler<impl Fn(&ToolCall) -> Result<serde_json::Value> + Send + Sync> {
FnToolHandler::new(|_call: &ToolCall| Ok(serde_json::json!({ "ok": true })))
}
fn function_call(call_id: &str, name: &str) -> ServerEvent {
ServerEvent::FunctionCallDone {
event_id: "evt".into(),
response_id: "resp".into(),
item_id: "item".into(),
output_index: 0,
call_id: call_id.into(),
name: name.into(),
arguments: "{}".into(),
}
}
fn response_done() -> ServerEvent {
ServerEvent::ResponseDone { event_id: "evt".into(), response: serde_json::json!({}) }
}
async fn runner_with_session(counts: Arc<Counts>) -> RealtimeRunner {
let runner =
RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).build().unwrap();
let session = Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>;
// The unit test owns the runner and installs the same session handle
// that `connect` would publish after provider setup.
*runner.session.write().await = Some(session);
runner
}
/// A runner whose `pay` tool counts executions, governed by `config`.
async fn governed_runner(
counts: Arc<Counts>,
executions: Arc<AtomicUsize>,
config: adk_core::RunConfig,
) -> RealtimeRunner {
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.tool_fn(tool_def("pay"), move |_call| {
executions.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({ "paid": true }))
})
.tool_governance(config, adk_core::ApprovalScope::new("voice", "user", "session"))
.build()
.unwrap();
*runner.session.write().await =
Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
runner
}
/// A runner whose `lookup` handler returns a customer record, or fails quoting a
/// credential, configured by `configure`.
async fn lookup_runner(
counts: Arc<Counts>,
fails: bool,
configure: impl FnOnce(RealtimeRunnerBuilder) -> RealtimeRunnerBuilder,
) -> RealtimeRunner {
let builder = RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).tool_fn(
tool_def("lookup"),
move |_call| {
if fails {
Err(RealtimeError::ToolError(
"connect postgres://admin:hunter2@db.internal/prod failed".into(),
))
} else {
Ok(serde_json::json!({ "ssn": "123-45-6789" }))
}
},
);
let runner = configure(builder).build().unwrap();
*runner.session.write().await =
Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
runner
}
/// Withholds every result, or redacts its `ssn`.
struct SsnScreen {
fail: bool,
}
#[async_trait]
impl adk_core::ToolResultScreen for SsnScreen {
async fn screen_result(
&self,
_tool_name: &str,
_args: &serde_json::Value,
result: &serde_json::Value,
) -> std::result::Result<serde_json::Value, String> {
if self.fail {
return Err("the screening service is unavailable".into());
}
let mut result = result.clone();
if result.get("ssn").is_some() {
result["ssn"] = serde_json::json!("[SSN REDACTED]");
}
Ok(result)
}
}
#[tokio::test]
async fn handler_errors_reach_the_model_redacted_unless_exposed() {
let counts = Arc::new(Counts::default());
let runner = lookup_runner(Arc::clone(&counts), true, |b| b).await;
runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
let output = counts.last_output.lock().clone().unwrap();
assert_eq!(output, serde_json::json!({ "error": "tool 'lookup' failed" }));
let runner =
lookup_runner(Arc::clone(&counts), true, |b| b.expose_tool_error_messages(true)).await;
runner.dispatch_tool_call("c2", "lookup", "{}").await.unwrap();
let output = counts.last_output.lock().clone().unwrap();
assert!(output["error"].as_str().unwrap_or_default().contains("hunter2"), "{output}");
}
/// Records every event field the runner logs.
#[derive(Clone, Default)]
struct Logged(Arc<parking_lot::Mutex<Vec<String>>>);
struct LoggedValues<'a>(&'a mut Vec<String>);
impl tracing::field::Visit for LoggedValues<'_> {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
self.0.push(format!("{}={value:?}", field.name()));
}
}
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Logged {
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
event.record(&mut LoggedValues(&mut self.0.lock()));
}
}
#[tokio::test(flavor = "current_thread")]
async fn handler_error_messages_are_logged_only_under_the_payload_rule() {
use tracing_subscriber::layer::SubscriberExt;
for record_payloads in [false, true] {
let logged = Logged::default();
let _guard = tracing::subscriber::set_default(
tracing_subscriber::registry().with(logged.clone()),
);
let counts = Arc::new(Counts::default());
let config = adk_core::RunConfig { record_payloads, ..adk_core::RunConfig::default() };
let runner = lookup_runner(Arc::clone(&counts), true, |b| {
b.tool_governance(config, adk_core::ApprovalScope::new("voice", "user", "s"))
})
.await;
runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
let values = logged.0.lock().clone();
assert!(values.contains(&"error.kind=\"tool\"".to_string()), "{values:#?}");
assert_eq!(
values.iter().any(|value| value.contains("hunter2")),
record_payloads,
"the message is logged only when payloads are recorded: {values:#?}"
);
}
}
#[tokio::test]
async fn the_result_screen_runs_before_the_output_is_sent() {
let counts = Arc::new(Counts::default());
let runner = lookup_runner(Arc::clone(&counts), false, |b| {
b.tool_result_screen(Arc::new(SsnScreen { fail: false }))
})
.await;
runner.dispatch_tool_call("c1", "lookup", "{}").await.unwrap();
let output = counts.last_output.lock().clone().unwrap();
assert_eq!(output, serde_json::json!({ "ssn": "[SSN REDACTED]" }));
let runner = lookup_runner(Arc::clone(&counts), false, |b| {
b.tool_result_screen(Arc::new(SsnScreen { fail: true }))
})
.await;
runner.dispatch_tool_call("c2", "lookup", "{}").await.unwrap();
let output = counts.last_output.lock().clone().unwrap();
assert_eq!(output["status"], adk_core::RESULT_WITHHELD_STATUS, "{output}");
assert!(!output.to_string().contains("123-45-6789"), "{output}");
}
#[tokio::test]
async fn malformed_tool_arguments_are_refused() {
let counts = Arc::new(Counts::default());
let executions = Arc::new(AtomicUsize::new(0));
let runner = governed_runner(
Arc::clone(&counts),
Arc::clone(&executions),
adk_core::RunConfig::default(),
)
.await;
runner.dispatch_tool_call("c1", "pay", r#"{"amount": 5"#).await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 0, "a malformed call must not run");
let output = counts.last_output.lock().clone().expect("the call is answered");
assert!(output["error"].as_str().unwrap_or_default().contains("not valid JSON"));
}
#[tokio::test]
async fn the_runner_policy_and_kill_switch_govern_dispatched_calls() {
let counts = Arc::new(Counts::default());
let executions = Arc::new(AtomicUsize::new(0));
let control = adk_core::GovernanceControl::new();
let config = adk_core::RunConfig::builder()
.tool_policy(Arc::new(adk_core::DeclarativePolicy::builder().allow("get_*").build()))
.governance(control.clone())
.build();
let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
runner.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 0);
let output = counts.last_output.lock().clone().unwrap();
assert!(output["error"].as_str().unwrap_or_default().contains("denied by policy"));
control.freeze("drill");
let error = runner.dispatch_tool_call("c2", "pay", "{}").await.unwrap_err();
assert!(error.to_string().contains("frozen"), "{error}");
assert_eq!(executions.load(Ordering::SeqCst), 0);
}
/// The review of #1005: a freeze while the confirmation handler decides ends the wait,
/// and the dispatch ends with the freeze before the handler runs, as an agent's call is
/// refused.
#[tokio::test]
async fn a_freeze_ends_the_wait_for_the_confirmation_handler() {
#[derive(Debug)]
struct NeverAnswers;
#[async_trait]
impl adk_core::ToolConfirmationHandler for NeverAnswers {
async fn decide(
&self,
_request: &adk_core::ToolConfirmationRequest,
) -> adk_core::Result<adk_core::ToolConfirmationDecision> {
std::future::pending().await
}
}
let counts = Arc::new(Counts::default());
let executions = Arc::new(AtomicUsize::new(0));
let control = adk_core::GovernanceControl::new();
let config = adk_core::RunConfig::builder()
.tool_policy(Arc::new(
adk_core::DeclarativePolicy::builder()
.require_approval("pay", "payments need a person")
.build(),
))
.tool_confirmation_handler(Arc::new(NeverAnswers))
.governance(control.clone())
.build();
let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
control.freeze("incident 4017");
});
let error = tokio::time::timeout(
std::time::Duration::from_secs(5),
runner.dispatch_tool_call("c1", "pay", "{}"),
)
.await
.expect("the freeze ends the wait")
.unwrap_err();
assert!(error.to_string().contains("incident 4017"), "{error}");
assert_eq!(executions.load(Ordering::SeqCst), 0, "the handler never runs");
assert_eq!(*counts.last_output.lock(), None, "nothing is sent for the refused call");
}
/// A native handler's held call names the runner's agent and the `realtime` origin of
/// the handler's definition, so an approval of it never covers the handler once
/// redefined, nor another agent's identical call (#1210).
#[tokio::test]
async fn a_native_handlers_held_call_names_its_agent_and_handler_origin() {
use adk_core::ApprovalStore;
let counts = Arc::new(Counts::default());
let executions = Arc::new(AtomicUsize::new(0));
let store = Arc::new(adk_core::InMemoryApprovalStore::new());
let scope = adk_core::ApprovalScope::new("voice", "user", "session");
let config = adk_core::RunConfig::builder()
.tool_policy(Arc::new(
adk_core::DeclarativePolicy::builder()
.require_approval("pay", "payments need a person")
.build(),
))
.approval_store(store.clone())
.build();
let runner = |definition: ToolDefinition, agent: &str| {
let executions = Arc::clone(&executions);
RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.agent_name(agent)
.tool_fn(definition, move |_call| {
executions.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({ "paid": true }))
})
.tool_governance(config.clone(), scope.clone())
.build()
.unwrap()
};
let install = |runner: RealtimeRunner| {
let counts = Arc::clone(&counts);
async move {
*runner.session.write().await =
Some(Arc::new(RecordingSession { counts }) as Arc<dyn RealtimeSession>);
runner
}
};
let pay = tool_def("pay").with_description("Pays an invoice");
let reworded_pay = pay.clone().with_description("Pays anyone");
let voice = install(runner(pay.clone(), "voice")).await;
voice.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
let pending = store.pending(&scope).await.unwrap();
let [held] = pending.as_slice() else { panic!("one held call: {pending:?}") };
assert_eq!(held.request.origin, Some(pay.handler_origin()));
assert_eq!(held.request.origin.as_ref().unwrap().source, REALTIME_HANDLER_ORIGIN);
assert_eq!(
held.request.acting.as_ref().map(|acting| acting.agent.id.as_str()),
Some("urn:adk:agent:voice/voice")
);
assert_eq!(
adk_core::ToolConfirmationRequest::fingerprint_agent(&held.fingerprint),
Some("urn:adk:agent:voice/voice")
);
// Redefined, the handler is not the one approved.
store.decide(&scope, &held.fingerprint, adk_core::ToolApproval::approve()).await.unwrap();
let reworded = install(runner(reworded_pay.clone(), "voice")).await;
reworded.dispatch_tool_call("c2", "pay", "{}").await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 0, "a redefined handler needs approval");
// Another agent's identical call is not the one approved.
let intern = install(runner(pay.clone(), "intern")).await;
intern.dispatch_tool_call("c3", "pay", "{}").await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 0, "another agent needs its own approval");
// The handler as approved, by the agent it was approved for, runs once.
voice.dispatch_tool_call("c4", "pay", "{}").await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 1);
let mut waiting: Vec<_> = store
.pending(&scope)
.await
.unwrap()
.into_iter()
.map(|entry| {
let agent =
adk_core::ToolConfirmationRequest::fingerprint_agent(&entry.fingerprint)
.map(str::to_string);
(agent, entry.request.origin)
})
.collect();
waiting.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
waiting,
[
(Some("urn:adk:agent:voice/intern".to_string()), Some(pay.handler_origin())),
(
Some("urn:adk:agent:voice/voice".to_string()),
Some(reworded_pay.handler_origin())
),
],
"each unapproved call waits on its own"
);
}
#[tokio::test]
async fn policy_rules_match_the_configured_voice_agent() {
let counts = Arc::new(Counts::default());
let executions = Arc::new(AtomicUsize::new(0));
let principal = adk_core::AgentPrincipal::new(
adk_core::AgentId::new("spiffe://acme.test/agent/voice").unwrap(),
);
let config = adk_core::RunConfig::builder()
.tool_policy(Arc::new(
adk_core::DeclarativePolicy::builder()
.rule(
adk_core::PolicyRule::allow("pay")
.for_agent("spiffe://acme.test/agent/voice"),
)
.build(),
))
.agent_principal("realtime", principal)
.build();
let runner = governed_runner(Arc::clone(&counts), Arc::clone(&executions), config).await;
runner.dispatch_tool_call("c1", "pay", "{}").await.unwrap();
assert_eq!(executions.load(Ordering::SeqCst), 1, "the voice agent's rule allows it");
let unconfigured = adk_core::RunConfig::builder()
.tool_policy(Arc::new(
adk_core::DeclarativePolicy::builder()
.rule(
adk_core::PolicyRule::allow("pay")
.for_agent("spiffe://acme.test/agent/voice"),
)
.build(),
))
.build();
let runner =
governed_runner(Arc::clone(&counts), Arc::clone(&executions), unconfigured).await;
runner.dispatch_tool_call("c2", "pay", "{}").await.unwrap();
assert_eq!(
executions.load(Ordering::SeqCst),
1,
"the derived identity urn:adk:agent:voice/realtime is not the voice agent"
);
}
#[tokio::test]
async fn send_audio_chunk_preserves_bytes_and_format_on_raw_path() {
let counts = Arc::new(Counts::default());
let runner = runner_with_session(Arc::clone(&counts)).await;
let chunk = AudioChunk::pcm16_24khz(vec![1, 2, 3, 4]);
runner.send_audio_chunk(&chunk).await.unwrap();
assert_eq!(counts.raw_audio.load(Ordering::SeqCst), 1);
assert_eq!(counts.base64_audio.load(Ordering::SeqCst), 0);
let recorded = counts.last_audio.lock();
let recorded = recorded.as_ref().unwrap();
assert_eq!(recorded.data, chunk.data);
assert_eq!(recorded.format, chunk.format);
}
#[tokio::test]
async fn send_audio_keeps_base64_compatibility_path() {
let counts = Arc::new(Counts::default());
let runner = runner_with_session(Arc::clone(&counts)).await;
runner.send_audio("AQIDBA==").await.unwrap();
assert_eq!(counts.raw_audio.load(Ordering::SeqCst), 0);
assert_eq!(counts.base64_audio.load(Ordering::SeqCst), 1);
}
/// Two parallel tool calls in one response must produce exactly one
/// `create_response` — issued after the dispatch response finishes — not one
/// per tool (which collides with the still-active response on OpenAI).
#[tokio::test]
async fn parallel_tool_calls_trigger_a_single_response() {
let counts = Arc::new(Counts::default());
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.tool(tool_def("get_weather"), ok_tool())
.tool(tool_def("get_time"), ok_tool())
.build()
.unwrap();
*runner.session.write().await =
Some(Arc::new(RecordingSession { counts: counts.clone() }) as Arc<dyn RealtimeSession>);
// One model response dispatching two tool calls, then ending. Driven through
// `run`, because dispatch is the run loop's job now — `handle_event` returns the
// call rather than awaiting it, so event intake is not blocked by a tool.
let scripted = Arc::new(ScriptedSession::new(
counts.clone(),
vec![
function_call("c1", "get_weather"),
function_call("c2", "get_time"),
response_done(),
],
));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
runner.run().await.unwrap();
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 2, "both outputs sent");
assert_eq!(counts.create_response.load(Ordering::SeqCst), 1, "exactly one response");
assert_eq!(
counts.tool_response.load(Ordering::SeqCst),
0,
"auto path must use send_tool_output, not the output+create combo"
);
// The follow-up (spoken-answer) response finishing creates nothing more.
runner.handle_event(response_done()).await.unwrap();
assert_eq!(counts.create_response.load(Ordering::SeqCst), 1, "no extra response");
}
/// A response with no tool calls must not trigger an auto follow-up response.
#[tokio::test]
async fn plain_response_triggers_no_auto_response() {
let counts = Arc::new(Counts::default());
let runner =
RealtimeRunner::builder().model(Arc::new(MockModel) as BoxedModel).build().unwrap();
*runner.session.write().await =
Some(Arc::new(RecordingSession { counts: counts.clone() }) as Arc<dyn RealtimeSession>);
runner.handle_event(response_done()).await.unwrap();
assert_eq!(counts.create_response.load(Ordering::SeqCst), 0);
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 0);
}
// ── Bounded concurrent tool dispatch ──────────────────────────────────
//
// `RunnerConfig::max_concurrent_tools` defaulted to four and was read by nothing: no
// semaphore, no scheduler. `FunctionCallDone` was awaited inline inside `handle_event`,
// which the run loop awaited before reading the next event, so tool calls ran strictly
// one at a time *and* stalled audio and every other event for the duration.
/// A session that replays a scripted event sequence, then reports disconnect.
struct ScriptedSession {
counts: Arc<Counts>,
events: parking_lot::Mutex<std::collections::VecDeque<ServerEvent>>,
}
impl ScriptedSession {
fn new(counts: Arc<Counts>, events: Vec<ServerEvent>) -> Self {
Self { counts, events: parking_lot::Mutex::new(events.into()) }
}
}
#[async_trait]
impl RealtimeSession for ScriptedSession {
fn session_id(&self) -> &str {
"scripted-session"
}
fn is_connected(&self) -> bool {
true
}
async fn send_audio(&self, _audio: &AudioChunk) -> Result<()> {
Ok(())
}
async fn send_audio_base64(&self, _audio: &str) -> Result<()> {
Ok(())
}
async fn send_text(&self, _text: &str) -> Result<()> {
Ok(())
}
async fn send_tool_response(&self, _response: ToolResponse) -> Result<()> {
self.counts.tool_response.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn send_tool_output(&self, _response: ToolResponse) -> Result<()> {
self.counts.tool_output.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn commit_audio(&self) -> Result<()> {
Ok(())
}
async fn clear_audio(&self) -> Result<()> {
Ok(())
}
async fn create_response(&self) -> Result<()> {
self.counts.create_response.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn interrupt(&self) -> Result<()> {
Ok(())
}
async fn send_event(&self, _event: ClientEvent) -> Result<()> {
Ok(())
}
async fn next_event(&self) -> Option<Result<ServerEvent>> {
let event = self.events.lock().pop_front();
event.map(Ok)
}
fn events(&self) -> Pin<Box<dyn futures::Stream<Item = Result<ServerEvent>> + Send + '_>> {
Box::pin(futures::stream::empty())
}
async fn close(&self) -> Result<()> {
Ok(())
}
async fn mutate_context(&self, _config: RealtimeConfig) -> Result<ContextMutationOutcome> {
Ok(ContextMutationOutcome::Applied)
}
}
/// A tool that reports how many copies of itself run at once.
struct ConcurrencyProbe {
in_flight: Arc<AtomicUsize>,
peak: Arc<AtomicUsize>,
barrier: Option<Arc<tokio::sync::Barrier>>,
}
#[async_trait]
impl ToolHandler for ConcurrencyProbe {
async fn execute(&self, _call: &ToolCall) -> Result<serde_json::Value> {
let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
self.peak.fetch_max(now, Ordering::SeqCst);
match &self.barrier {
// Every participant must be running for this to return, so it can only
// complete if the dispatcher truly overlaps them.
Some(barrier) => {
barrier.wait().await;
}
None => {
tokio::task::yield_now().await;
}
}
self.in_flight.fetch_sub(1, Ordering::SeqCst);
Ok(serde_json::json!({ "ok": true }))
}
}
fn audio_delta() -> ServerEvent {
ServerEvent::AudioDelta {
event_id: "evt".into(),
response_id: "resp".into(),
item_id: "item".into(),
output_index: 0,
content_index: 0,
delta: vec![1, 2, 3],
}
}
#[tokio::test]
async fn tool_calls_overlap_up_to_the_configured_bound() {
let counts = Arc::new(Counts::default());
let in_flight = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
// Only satisfiable if all three run at once, which serial dispatch cannot do.
let barrier = Arc::new(tokio::sync::Barrier::new(3));
let probe = || ConcurrencyProbe {
in_flight: Arc::clone(&in_flight),
peak: Arc::clone(&peak),
barrier: Some(Arc::clone(&barrier)),
};
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.runner_config(RunnerConfig {
auto_execute_tools: true,
auto_respond_tools: true,
max_concurrent_tools: 3,
})
.tool(tool_def("a"), probe())
.tool(tool_def("b"), probe())
.tool(tool_def("c"), probe())
.build()
.unwrap();
let scripted = Arc::new(ScriptedSession::new(
Arc::clone(&counts),
vec![function_call("c1", "a"), function_call("c2", "b"), function_call("c3", "c")],
));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
.await
.expect("serial dispatch cannot satisfy a three-way barrier")
.unwrap();
assert_eq!(peak.load(Ordering::SeqCst), 3, "all three tools must overlap");
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 3, "every output is sent");
}
#[tokio::test]
async fn the_bound_caps_how_many_tools_overlap() {
let counts = Arc::new(Counts::default());
let in_flight = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
let probe = || ConcurrencyProbe {
in_flight: Arc::clone(&in_flight),
peak: Arc::clone(&peak),
barrier: None,
};
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.runner_config(RunnerConfig {
auto_execute_tools: true,
auto_respond_tools: true,
max_concurrent_tools: 2,
})
.tool(tool_def("a"), probe())
.tool(tool_def("b"), probe())
.tool(tool_def("c"), probe())
.tool(tool_def("d"), probe())
.build()
.unwrap();
let scripted = Arc::new(ScriptedSession::new(
Arc::clone(&counts),
vec![
function_call("c1", "a"),
function_call("c2", "b"),
function_call("c3", "c"),
function_call("c4", "d"),
],
));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
runner.run().await.unwrap();
assert!(
peak.load(Ordering::SeqCst) <= 2,
"the bound was exceeded: peak {}",
peak.load(Ordering::SeqCst)
);
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 4, "all four still complete");
}
/// A tool that blocks until an audio event has been handled.
struct WaitsForAudio {
audio_seen: Arc<tokio::sync::Notify>,
}
#[async_trait]
impl ToolHandler for WaitsForAudio {
async fn execute(&self, _call: &ToolCall) -> Result<serde_json::Value> {
self.audio_seen.notified().await;
Ok(serde_json::json!({ "ok": true }))
}
}
/// Signals the tool once audio is delivered.
struct AudioSignaller {
audio_seen: Arc<tokio::sync::Notify>,
audio_events: Arc<AtomicUsize>,
}
#[async_trait]
impl EventHandler for AudioSignaller {
async fn on_audio(&self, _audio: &[u8], _item_id: &str) -> Result<()> {
self.audio_events.fetch_add(1, Ordering::SeqCst);
self.audio_seen.notify_waiters();
Ok(())
}
}
#[tokio::test]
async fn audio_keeps_flowing_while_a_tool_runs() {
let counts = Arc::new(Counts::default());
let audio_seen = Arc::new(tokio::sync::Notify::new());
let audio_events = Arc::new(AtomicUsize::new(0));
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.tool(tool_def("slow"), WaitsForAudio { audio_seen: Arc::clone(&audio_seen) })
.event_handler(AudioSignaller {
audio_seen: Arc::clone(&audio_seen),
audio_events: Arc::clone(&audio_events),
})
.build()
.unwrap();
// The tool can only finish once the audio delta *after* it has been handled, so
// this sequence completes only if event intake continues during tool execution.
let scripted = Arc::new(ScriptedSession::new(
Arc::clone(&counts),
vec![function_call("c1", "slow"), audio_delta(), response_done()],
));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
.await
.expect("a tool awaiting a later event deadlocks when dispatch blocks intake")
.unwrap();
assert_eq!(audio_events.load(Ordering::SeqCst), 1, "the audio delta was handled");
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 1, "the tool still reported output");
}
#[tokio::test]
async fn the_follow_up_response_waits_for_tools_that_outlive_the_response() {
let counts = Arc::new(Counts::default());
let audio_seen = Arc::new(tokio::sync::Notify::new());
let audio_events = Arc::new(AtomicUsize::new(0));
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.tool(tool_def("slow"), WaitsForAudio { audio_seen: Arc::clone(&audio_seen) })
.event_handler(AudioSignaller {
audio_seen: Arc::clone(&audio_seen),
audio_events: Arc::clone(&audio_events),
})
.build()
.unwrap();
// `ResponseDone` arrives while the tool is still running — impossible before
// dispatch was concurrent, and the case that would silently drop the follow-up
// response, since `pending_tool_response` is only set once output is sent.
let scripted = Arc::new(ScriptedSession::new(
Arc::clone(&counts),
vec![function_call("c1", "slow"), response_done(), audio_delta()],
));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
tokio::time::timeout(std::time::Duration::from_secs(5), runner.run())
.await
.expect("run must finish")
.unwrap();
assert_eq!(counts.tool_output.load(Ordering::SeqCst), 1, "the output was sent");
assert_eq!(
counts.create_response.load(Ordering::SeqCst),
1,
"exactly one follow-up response, issued after the last tool finished"
);
}
/// Records terminal disconnects.
#[derive(Default)]
struct DisconnectWatcher {
disconnects: Arc<AtomicUsize>,
}
#[async_trait]
impl EventHandler for DisconnectWatcher {
async fn on_disconnect(&self) -> Result<()> {
self.disconnects.fetch_add(1, Ordering::SeqCst);
Ok(())
}
}
#[tokio::test]
async fn a_terminal_disconnect_is_surfaced_once() {
let counts = Arc::new(Counts::default());
let disconnects = Arc::new(AtomicUsize::new(0));
let runner = RealtimeRunner::builder()
.model(Arc::new(MockModel) as BoxedModel)
.event_handler(DisconnectWatcher { disconnects: Arc::clone(&disconnects) })
.build()
.unwrap();
let scripted = Arc::new(ScriptedSession::new(Arc::clone(&counts), vec![response_done()]));
*runner.session.write().await = Some(scripted as Arc<dyn RealtimeSession>);
// `run` returns `Ok(())` on transport loss, which on its own is indistinguishable
// from a graceful `close`.
runner.run().await.unwrap();
assert_eq!(
disconnects.load(Ordering::SeqCst),
1,
"transport loss must be reported exactly once"
);
}
}