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
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
//! Agent - the core agent orchestrator
//!
//! The Agent struct ties together all components and runs the agent loop.
mod builder;
pub mod comms_impl;
pub mod compact;
mod extraction;
mod hook_impl;
#[cfg(test)]
mod hooks_behavior_tests;
mod runner;
pub mod skills;
mod state;
#[cfg(test)]
#[doc(hidden)]
pub(crate) mod test_turn_state_handle;
use crate::budget::Budget;
use crate::comms::{
CommsCommand, CommsTrustMutation, CommsTrustMutationResult, EventStream, PeerDirectoryEntry,
PeerId, SendAndStreamError, SendError, SendReceipt, StreamError, StreamScope,
TrustedPeerDescriptor,
};
use crate::compact::SessionCompactionCadence;
use crate::completion_feed::CompletionSeq;
use crate::config::{AgentConfig, HookRunOverrides};
use crate::error::AgentError;
use crate::event::ExternalToolDelta;
use crate::hooks::HookEngine;
use crate::lifecycle::RunId;
use crate::lifecycle::run_primitive::ProviderParamsOverride;
use crate::ops::OperationId;
use crate::ops_lifecycle::{OperationKind, OperationStatus, OperationTerminalOutcome};
use crate::retry::RetryPolicy;
use crate::schema::{CompiledSchema, SchemaError};
use crate::session::Session;
use crate::state::LoopState;
#[cfg(target_arch = "wasm32")]
use crate::tokio;
use crate::tool_catalog::{
ToolCatalogCapabilities, ToolCatalogEntry, ToolCatalogMode, deferred_session_entry_count,
select_catalog_mode_from_snapshot,
};
use crate::tool_scope::ToolScope;
use crate::turn_execution_authority::{
ContentShape, TurnPhase, TurnPrimitiveKind, TurnTerminalCauseKind, TurnTerminalOutcome,
};
use crate::types::{
AssistantBlock, BlockAssistantMessage, Message, OutputSchema, StopReason, ToolCallView,
ToolDef, ToolName, ToolNameSet, Usage,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
pub use builder::{AgentBuildPolicyError, AgentBuilder, DefaultSystemPromptPolicy};
pub use runner::{AgentRunner, SnapshotProjectionError, SystemContextStateError};
/// Trait for LLM clients that can be used with the agent
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait AgentLlmClient: Send + Sync {
/// Stream a response from the LLM
async fn stream_response(
&self,
messages: &[Message],
tools: &[Arc<ToolDef>],
max_tokens: u32,
temperature: Option<f32>,
provider_params: Option<&ProviderParamsOverride>,
) -> Result<LlmStreamResult, AgentError>;
/// Get the typed catalog provider identity for this client.
///
/// Clients return the typed [`crate::provider::Provider`] directly so no
/// boundary ever parses a caller-supplied string back into catalog
/// identity. String projections are derived via
/// [`crate::provider::Provider::as_str`].
fn provider(&self) -> crate::provider::Provider;
/// Get the current effective model identifier.
///
/// Used by the agent loop for profile-default resolution (e.g., call timeout
/// defaults that vary per model family). Must reflect the current model even
/// after hot-swap.
fn model(&self) -> &str;
/// Prepare the next prebuilt fallback model after the generated turn
/// authority has classified the LLM failure as recoverable.
///
/// This method does not classify failures and must not call the provider.
/// It only selects an already-constructed candidate and returns the typed
/// state the agent loop must apply before the retry attempt.
fn prepare_model_fallback(&self, _failure: &AgentError) -> Option<AgentLlmFallbackSwitch> {
None
}
/// Move the client-local active candidate from `previous_identity` to the
/// exact `target_identity` as one reversible transaction step.
///
/// The core loop invokes this only after every target-dependent operation
/// (including target-provider schema compilation) has been prevalidated,
/// but before auth/session/machine state is committed. Implementations must
/// either perform the exact switch or return an error. The default fails
/// closed so a custom client cannot propose a fallback while silently
/// continuing to issue requests through its old provider client.
///
/// Core verifies [`AgentLlmClient::active_model_fallback_identity`] after
/// the call and invokes this method in reverse if a later transaction step
/// fails.
fn commit_model_fallback(
&self,
_previous_identity: &crate::SessionLlmIdentity,
target_identity: &crate::SessionLlmIdentity,
) -> Result<(), AgentError> {
Err(AgentError::ConfigError(format!(
"LLM client proposed fallback target '{}:{}' without an activation implementation",
target_identity.provider.as_str(),
target_identity.model
)))
}
/// Exact identity of the client-local active fallback candidate.
///
/// Fallback-capable clients must expose the full session identity,
/// including auth binding and provider parameters. The default is absent,
/// which makes fallback activation fail closed before canonical state is
/// mutated.
fn active_model_fallback_identity(&self) -> Option<crate::SessionLlmIdentity> {
None
}
/// Compile an extraction schema against an inactive fallback target.
///
/// This must delegate to the exact prebuilt target client without changing
/// which client is active. Core calls it before auth, machine, visibility,
/// session, or client activation state is mutated, then injects the
/// compiled representation into the target provider request.
fn compile_model_fallback_schema(
&self,
target_identity: &crate::SessionLlmIdentity,
_output_schema: &OutputSchema,
) -> Result<CompiledSchema, AgentError> {
Err(AgentError::ConfigError(format!(
"LLM client cannot compile structured output for fallback target '{}:{}'",
target_identity.provider.as_str(),
target_identity.model
)))
}
/// Reset per-call observation of user-visible streaming output.
///
/// Adapters that emit display/reasoning deltas before returning the final
/// stream result use this to let the retry loop distinguish a pre-stream
/// failure from a post-partial-output failure. The default is no-op for
/// clients that do not stream visible events outside the returned blocks.
fn begin_stream_output_observation(&self) {}
/// Whether the current LLM call has emitted user-visible streaming output.
///
/// A `true` value suppresses model fallback for the failed call: retrying
/// against a different model after users already saw partial output can
/// produce duplicate assistant answers. Ordinary same-model retry policy is
/// still governed by the generated turn recovery authority.
fn stream_output_observed(&self) -> bool {
false
}
/// Monotonic count of raw provider stream events observed by this client.
///
/// This feeds the agent loop's stream-inactivity watchdog
/// (`RetryPolicy::stream_inactivity_timeout`): the loop snapshots the
/// count around each stream-event window and treats "no change" as a
/// silent stream. Clients that consume a provider event stream should bump
/// the count on every received event — including non-visible ones — so
/// liveness is distinct from visible output
/// ([`Self::stream_output_observed`]).
///
/// `None` (the default) means this client does not report stream liveness
/// and the watchdog is disabled for its calls; only the hard call/turn
/// timeouts apply. This fails open on purpose: a non-streaming custom
/// client would otherwise look permanently silent and be killed while
/// healthy.
fn stream_activity_count(&self) -> Option<u64> {
None
}
/// Compile an output schema for this provider.
///
/// Default implementation normalizes the schema without provider-specific lowering.
/// Adapters override this to apply provider-specific transformations (e.g.,
/// Anthropic adds `additionalProperties: false`, Gemini strips unsupported keywords).
fn compile_schema(&self, output_schema: &OutputSchema) -> Result<CompiledSchema, SchemaError> {
// Default passthrough: normalized clone, no provider-specific lowering
Ok(CompiledSchema {
schema: output_schema.schema.as_value().clone(),
warnings: Vec::new(),
})
}
}
/// Hook for wrapping the final agent-facing LLM client.
///
/// Factories and runtimes apply this after provider/raw-client adaptation so
/// embedders can compose cross-cutting behavior without provider-specific
/// registry hooks.
pub type AgentLlmClientDecorator =
Arc<dyn Fn(Arc<dyn AgentLlmClient>) -> Arc<dyn AgentLlmClient> + Send + Sync + 'static>;
/// One fallback target skipped while selecting a viable backup model.
#[derive(Debug, Clone)]
pub struct AgentLlmFallbackSkippedTarget {
pub identity: crate::SessionLlmIdentity,
pub reason: String,
}
/// Typed state produced when an agent-facing LLM client activates a fallback.
///
/// The client owns only prebuilt candidate selection. The agent loop owns
/// applying request policy, durable identity metadata, and tool visibility
/// before issuing the machine-authorized retry.
#[derive(Debug, Clone)]
pub struct AgentLlmFallbackSwitch {
pub previous_identity: crate::SessionLlmIdentity,
pub new_identity: crate::SessionLlmIdentity,
pub request_policy: crate::SessionLlmRequestPolicy,
/// Proposed effective-registry witness for the exact target provider/model.
/// Core rejects foreign authority and freshly resolves all capability and
/// token-limit facts through the agent's captured registry. The witness is
/// required: unresolved fallback targets fail closed.
pub target_profile: crate::ModelProfileWitness,
pub skipped_targets: Vec<AgentLlmFallbackSkippedTarget>,
}
/// One-shot authorization for an exact sticky model-fallback activation.
///
/// There is deliberately no public constructor and the fields are private.
/// The constructor is owned by the `agent` module, so only the core agent loop
/// can mint this value after generated recovery acceptance and exact
/// effective-registry validation. A public
/// [`crate::handles::ModelRoutingHandle`] therefore cannot be driven directly
/// with a caller-minted or foreign-registry profile.
///
/// ```compile_fail
/// use meerkat_core::StickyModelFallbackActivationProof;
///
/// // Routing callers cannot fabricate an activation proof.
/// let _proof = StickyModelFallbackActivationProof::new();
/// ```
pub struct StickyModelFallbackActivationProof {
previous_identity: crate::SessionLlmIdentity,
target_identity: crate::SessionLlmIdentity,
target_profile: crate::ModelProfileWitness,
target_capability_base_filter: crate::ToolFilter,
retry_attempt: u32,
}
impl StickyModelFallbackActivationProof {
fn new(
previous_identity: crate::SessionLlmIdentity,
target_identity: crate::SessionLlmIdentity,
target_profile: crate::ModelProfileWitness,
retry_attempt: u32,
) -> Self {
let target_capability_base_filter = crate::capability_base_filter_for_image_tool_results(
target_profile.profile().image_tool_results,
);
Self {
previous_identity,
target_identity,
target_profile,
target_capability_base_filter,
retry_attempt,
}
}
/// Exact identity the generated recovery transition must still own.
pub fn previous_identity(&self) -> &crate::SessionLlmIdentity {
&self.previous_identity
}
/// Exact registry-resolved identity being activated.
pub fn target_identity(&self) -> &crate::SessionLlmIdentity {
&self.target_identity
}
/// Registry-owned target profile carried by this authorization.
pub fn target_profile(&self) -> &crate::ModelProfileWitness {
&self.target_profile
}
/// Registry-derived capability filter for the target model.
pub fn target_capability_base_filter(&self) -> &crate::ToolFilter {
&self.target_capability_base_filter
}
/// Machine-accepted retry attempt bound into this authorization.
pub fn retry_attempt(&self) -> u32 {
self.retry_attempt
}
}
/// Result of streaming from the LLM
pub struct LlmStreamResult {
blocks: Vec<AssistantBlock>,
stop_reason: StopReason,
usage: Usage,
}
impl LlmStreamResult {
pub fn new(blocks: Vec<AssistantBlock>, stop_reason: StopReason, usage: Usage) -> Self {
Self {
blocks,
stop_reason,
usage,
}
}
pub fn blocks(&self) -> &[AssistantBlock] {
&self.blocks
}
pub fn stop_reason(&self) -> StopReason {
self.stop_reason
}
pub fn usage(&self) -> &Usage {
&self.usage
}
pub fn into_message(self) -> BlockAssistantMessage {
BlockAssistantMessage::new(self.blocks, self.stop_reason)
}
pub fn into_parts(self) -> (Vec<AssistantBlock>, StopReason, Usage) {
(self.blocks, self.stop_reason, self.usage)
}
}
/// Snapshot of the core agent's live execution state.
///
/// When a runtime-backed turn-state handle is attached, this snapshots the
/// runtime-owned turn machine; otherwise it falls back to the in-process
/// standalone turn state used by core-only execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentExecutionSnapshot {
pub loop_state: LoopState,
pub turn_phase: TurnPhase,
/// Machine-owned turn-terminality verdict.
///
/// The `TurnTerminalityClassified.terminal` verdict emitted by the canonical
/// MeerkatMachine `ClassifyTurnTerminality` input. Consumers mirror this bool
/// and must not reclassify [`TurnPhase`] locally.
pub turn_terminal: bool,
pub active_run_id: Option<RunId>,
pub terminal_run_id: Option<RunId>,
pub primitive_kind: TurnPrimitiveKind,
pub admitted_content_shape: Option<ContentShape>,
pub vision_enabled: bool,
pub image_tool_results_enabled: bool,
pub tool_calls_pending: u32,
pub pending_operation_ids: Option<Vec<OperationId>>,
pub barrier_operation_ids: Vec<OperationId>,
pub has_barrier_ops: bool,
pub barrier_satisfied: bool,
pub boundary_count: u32,
pub cancel_after_boundary: bool,
pub terminal_outcome: TurnTerminalOutcome,
pub terminal_cause_kind: Option<TurnTerminalCauseKind>,
pub extraction_attempts: u32,
pub max_extraction_retries: u32,
pub applied_cursor: CompletionSeq,
}
/// Result of polling for external tool updates.
///
/// Returned by [`AgentToolDispatcher::poll_external_updates`].
#[derive(Debug, Clone, Default)]
pub struct ExternalToolUpdate {
/// Notices about completed background operations since last poll.
pub notices: Vec<ExternalToolDelta>,
/// Names of servers still connecting in the background.
pub pending: Vec<String>,
}
/// Typed command requesting cancellation at the next turn boundary.
///
/// Carried over the cancel-after-boundary command channel from the surface
/// that authorized the request (e.g. `SessionService::cancel_after_boundary`)
/// to the agent loop, which observes it at the next boundary. The agent
/// resolves the request against its own live active run. The exact run witness
/// prevents a delayed request from an old executor attachment from cancelling
/// a successor run after same-session replacement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CancelAfterBoundaryCommand {
expected_run_id: RunId,
}
impl CancelAfterBoundaryCommand {
/// Bind a cooperative-cancel command to one exact run incarnation.
pub fn for_run(expected_run_id: RunId) -> Self {
Self { expected_run_id }
}
/// Exact run incarnation this command is authorized to affect.
pub fn expected_run_id(&self) -> &RunId {
&self.expected_run_id
}
}
/// Producer end of the cancel-after-boundary command channel.
///
/// Cloned and handed to the requesting surface via
/// [`Agent::cancel_after_boundary_handle`]; mirrors the cloneable-handle shape
/// of the session-side `interrupt_notify` so a surface can request boundary
/// cancellation without holding a reference to the agent.
pub type CancelAfterBoundarySender = tokio::sync::mpsc::UnboundedSender<CancelAfterBoundaryCommand>;
/// Typed context supplied by the agent loop when dispatching a tool call.
///
/// This is a dispatch-time projection of the already-admitted turn input. It
/// lets tool surfaces resolve typed turn-scoped references, such as a
/// `source=current_turn, index=0` image ref, without writing surface-local
/// metadata into canonical transcript history.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolDispatchContext {
current_turn: Option<CurrentTurnContent>,
turn_metadata: BTreeMap<String, serde_json::Value>,
origin_session_id: Option<crate::types::SessionId>,
interaction_lineage_id: Option<crate::interaction::InteractionId>,
streaming: Option<crate::ToolStreamingDispatchContext>,
}
/// Dispatch-context key carrying the current durable objective id.
pub const TOOL_DISPATCH_OBJECTIVE_ID_KEY: &str = "meerkat.objective_id";
impl ToolDispatchContext {
pub fn from_current_turn_input(input: &crate::types::ContentInput) -> Self {
let blocks = match input {
crate::types::ContentInput::Text(_) => None,
crate::types::ContentInput::Blocks(blocks) => Some(blocks.clone()),
};
Self {
current_turn: blocks.map(CurrentTurnContent::new),
turn_metadata: BTreeMap::new(),
origin_session_id: None,
interaction_lineage_id: None,
streaming: None,
}
}
/// Project the typed run input into a dispatch context. The
/// pending-tool-results continuation carries no caller content, so it
/// projects to an empty context rather than a fabricated empty prompt.
pub fn from_run_input(input: &crate::types::RunInput) -> Self {
match input {
crate::types::RunInput::Content { content } => Self::from_current_turn_input(content),
crate::types::RunInput::PendingToolResults => Self::default(),
}
}
#[must_use]
pub fn with_turn_metadata(mut self, metadata: BTreeMap<String, serde_json::Value>) -> Self {
self.turn_metadata = metadata;
self
}
pub fn turn_metadata(&self, key: &str) -> Option<&serde_json::Value> {
self.turn_metadata.get(key)
}
pub fn current_turn(&self) -> Option<&CurrentTurnContent> {
self.current_turn.as_ref()
}
/// Bind the runtime-owned durable identity of the turn being dispatched.
///
/// Standalone callers may leave this absent. Durable execution owners must
/// fail closed rather than minting replacement identity at dispatch time.
#[must_use]
pub fn with_runtime_identity(
mut self,
origin_session_id: crate::types::SessionId,
interaction_lineage_id: Option<crate::interaction::InteractionId>,
) -> Self {
self.origin_session_id = Some(origin_session_id);
self.interaction_lineage_id = interaction_lineage_id;
self
}
pub fn origin_session_id(&self) -> Option<&crate::types::SessionId> {
self.origin_session_id.as_ref()
}
pub const fn interaction_lineage_id(&self) -> Option<crate::interaction::InteractionId> {
self.interaction_lineage_id
}
/// Streaming-only liveness surface minted by the canonical supervisor.
///
/// Fast and detached dispatch contexts carry no streaming surface. A tool
/// that declared `Streaming` must fail closed if this is absent rather than
/// fabricating a progress sink or cancellation authority.
pub const fn streaming(&self) -> Option<&crate::ToolStreamingDispatchContext> {
self.streaming.as_ref()
}
pub(crate) fn with_streaming(mut self, streaming: crate::ToolStreamingDispatchContext) -> Self {
self.streaming = Some(streaming);
self
}
pub fn current_turn_image(
&self,
image_ref: CurrentTurnImageRef,
) -> Option<&crate::types::ContentBlock> {
self.current_turn
.as_ref()
.and_then(|current_turn| current_turn.image(image_ref))
}
}
/// Typed reference to an image in the current admitted turn.
///
/// The wrapped index addresses the turn's *filtered image stream*, not the
/// raw block list: ref `N` designates the `(N + 1)`-th image block of the
/// current turn, skipping non-image blocks (so ref `0` is the first image
/// even when text blocks precede it).
///
/// The field is private. In-process code mints refs only via
/// [`CurrentTurnContent::image_ref`], which returns a ref only when the
/// referenced image exists. Wire ingress (e.g. the comms `image_ref` tool
/// input) deserializes a bare JSON integer directly into this type via
/// `#[serde(transparent)]` — that is the sanctioned parse-at-ingress path,
/// and resolution through [`CurrentTurnContent::image`] still validates
/// existence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CurrentTurnImageRef(usize);
impl std::fmt::Display for CurrentTurnImageRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
/// Multimodal content from the currently admitted turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentTurnContent {
blocks: Vec<crate::types::ContentBlock>,
}
impl CurrentTurnContent {
pub fn new(blocks: Vec<crate::types::ContentBlock>) -> Self {
Self { blocks }
}
pub fn blocks(&self) -> &[crate::types::ContentBlock] {
&self.blocks
}
/// Mint a typed reference to the `n`-th image of this turn's filtered
/// image stream. Returns `Some` only when that image exists, so every
/// in-process [`CurrentTurnImageRef`] is resolvable at mint time.
pub fn image_ref(&self, n: usize) -> Option<CurrentTurnImageRef> {
self.images().nth(n).map(|_| CurrentTurnImageRef(n))
}
pub fn image(&self, image_ref: CurrentTurnImageRef) -> Option<&crate::types::ContentBlock> {
self.images().nth(image_ref.0)
}
fn images(&self) -> impl Iterator<Item = &crate::types::ContentBlock> {
self.blocks
.iter()
.filter(|block| matches!(block, crate::types::ContentBlock::Image { .. }))
}
}
/// Completion notice for a detached background operation, projected from
/// canonical ops-lifecycle terminal state plus dispatcher-owned display metadata.
///
/// This is a rebuildable projection (INV-003), not authoritative state.
/// Terminal class and timing come from `OperationLifecycleSnapshot` (INV-001).
/// Shell-projected detail is supplementary display only (INV-002).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetachedOpCompletion {
/// App-facing job identifier (the control noun for surfaces).
pub job_id: String,
/// Operation kind from canonical ops-lifecycle.
pub kind: OperationKind,
/// Terminal status from canonical ops-lifecycle.
pub status: OperationStatus,
/// Terminal outcome from canonical ops-lifecycle.
pub terminal_outcome: Option<OperationTerminalOutcome>,
/// Canonical display label from ops-lifecycle snapshot.
pub display_name: String,
/// Dispatcher-projected summary (exit code, output tail). Display only.
pub detail: String,
/// Monotonic elapsed millis from ops-lifecycle snapshot.
pub elapsed_ms: Option<u64>,
}
/// Dispatcher binding capabilities — what optional bindings this dispatcher supports.
///
/// Returned by [`AgentToolDispatcher::capabilities`]. Replaces individual
/// `supports_*` boolean methods with a single structured query.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DispatcherCapabilities {
/// Whether `bind_ops_lifecycle` is implemented.
pub ops_lifecycle: bool,
}
/// Result of a dispatcher binding operation.
///
/// Distinguishes "binding was applied" from "binding was skipped" so callers
/// can decide whether to wire downstream side effects (e.g. bridge tasks).
///
/// **Semantics (decision 11 — supported/best-effort/rejected):**
/// - `Ok(Bound(d))` = **supported** — binding succeeded, side effects should be wired
/// - `Ok(Skipped(d))` = **best-effort** — inner shared or incompatible, dispatcher unchanged
/// - `Err(SharedOwnership)` = **rejected** — outer wrapper is shared, caught by factory pre-check
/// - `Err(Unsupported)` = **rejected** — type doesn't support this binding, caught by `capabilities()`
pub enum BindOutcome {
/// Binding was applied. The dispatcher was rebound.
Bound(Arc<dyn AgentToolDispatcher>),
/// Binding was skipped — inner dispatcher was shared or unsupported.
/// The returned dispatcher is unchanged but safe to use.
Skipped(Arc<dyn AgentToolDispatcher>),
}
impl BindOutcome {
/// Extract the dispatcher, regardless of bind status.
pub fn into_dispatcher(self) -> Arc<dyn AgentToolDispatcher> {
match self {
Self::Bound(d) | Self::Skipped(d) => d,
}
}
/// Whether the binding was actually applied.
pub fn was_bound(&self) -> bool {
matches!(self, Self::Bound(_))
}
}
/// Trait for tool dispatchers
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait AgentToolDispatcher: Send + Sync {
/// Get available tool definitions
fn tools(&self) -> Arc<[Arc<ToolDef>]>;
/// Query exact catalog support for this dispatcher.
///
/// Dispatchers report `exact_catalog=true` only when `tool_catalog()`
/// returns the exact precedence-resolved winner registry for the plane
/// they own. Wrappers that cannot prove exactness must leave this false.
fn tool_catalog_capabilities(&self) -> ToolCatalogCapabilities {
ToolCatalogCapabilities::default()
}
/// Return the precedence-resolved tool catalog for this dispatcher.
///
/// The default implementation mirrors `tools()` as a visible-only inline
/// catalog. Callers must gate any deferred-catalog behavior on
/// `tool_catalog_capabilities().exact_catalog`.
fn tool_catalog(&self) -> Arc<[ToolCatalogEntry]> {
self.tools()
.iter()
.map(|tool| ToolCatalogEntry::session_inline(Arc::clone(tool), true))
.collect::<Vec<_>>()
.into()
}
/// Live generation for one logical tool binding.
///
/// Static dispatchers keep the default zero epoch. Mutable authorities
/// must override this and advance it for every replacement, including an
/// identical-metadata A→B replacement.
fn execution_binding_epoch(&self, _tool_name: &str) -> u64 {
0
}
/// Snapshot the current live logical binding advertised for `tool_name`.
fn execution_binding_fingerprint(
&self,
tool_name: &str,
) -> Result<crate::EphemeralToolBindingFingerprint, crate::ToolExecutionResolutionError> {
let catalog = self.tool_catalog();
let entry = catalog
.iter()
.find(|entry| entry.tool.name == tool_name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: tool_name.to_string(),
})?;
Ok(crate::ephemeral_tool_catalog_binding_fingerprint(entry)
.with_live_authority(0, self.execution_binding_epoch(tool_name)))
}
/// Resolve the exact execution class and deadline chain before dispatch.
///
/// The default uses this dispatcher's effective catalog, so wrappers that
/// filter or select winners apply the same decision to declaration and
/// resolution. Hybrid tools may override this method to inspect typed
/// arguments while preserving the catalog contract as the upper bound.
fn resolve_execution_plan(
&self,
call: ToolCallView<'_>,
_dispatch_context: &ToolDispatchContext,
resolution_context: &crate::ToolExecutionResolutionContext,
) -> Result<crate::ResolvedToolExecutionPlan, crate::ToolExecutionResolutionError> {
let catalog = self.tool_catalog();
let entry = catalog
.iter()
.find(|entry| entry.tool.name == call.name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: call.name.to_string(),
})?;
if let Some(reason) = entry.callability.unavailable_reason() {
return Err(crate::ToolExecutionResolutionError::Unavailable {
tool_name: call.name.to_string(),
reason,
});
}
entry
.execution
.resolve_default(resolution_context.deadlines().clone())
.map_err(crate::ToolExecutionResolutionError::from)
}
/// Validate a resolved plan against both the caller-owned deadline prefix
/// and this dispatcher's live advertised catalog contract.
///
/// This is the mandatory root seam after argument-sensitive resolution:
/// hybrid tools may select any advertised mode, while an override cannot
/// return a mode or mode-derived facet absent from the effective catalog.
fn validate_resolved_execution_plan(
&self,
call: ToolCallView<'_>,
resolution_context: &crate::ToolExecutionResolutionContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<(), crate::ToolExecutionResolutionError> {
resolution_context.validate_resolved_plan(plan)?;
let catalog = self.tool_catalog();
let entry = catalog
.iter()
.find(|entry| entry.tool.name == call.name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: call.name.to_string(),
})?;
if let Some(reason) = entry.callability.unavailable_reason() {
return Err(crate::ToolExecutionResolutionError::Unavailable {
tool_name: call.name.to_string(),
reason,
});
}
entry
.execution
.validate_resolved_plan(plan)
.map_err(crate::ToolExecutionResolutionError::from)
}
/// Return non-draining pending source names for exact-catalog discovery.
///
/// Pending sources are catalog-level discovery metadata rather than
/// provider-visible tools. The default implementation reports none.
fn pending_catalog_sources(&self) -> Arc<[String]> {
Arc::from([])
}
/// Execute a tool call, returning the transcript result and any async operations.
///
/// The `ToolDispatchOutcome` separates transcript data (`result`) from
/// execution metadata (`async_ops`). Most tools return no async ops;
/// use `ToolDispatchOutcome::from(result)` for synchronous tools.
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError>;
/// Execute a tool call with the current turn's typed dispatch context.
///
/// Most tools do not need turn-local context and inherit the plain
/// `dispatch` behavior. Context-sensitive surfaces override this method
/// rather than reaching into session history or prompt text.
async fn dispatch_with_context(
&self,
call: ToolCallView<'_>,
_context: &ToolDispatchContext,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
self.dispatch(call).await
}
/// Execute a previously resolved plan without re-selecting its mode.
///
/// The default is deliberately a one-way lowering for Fast calls only.
/// Streaming and Detached require an explicit mode owner; silently sending
/// either through ordinary dispatch would erase their liveness, output,
/// restart, and idempotency contracts.
async fn dispatch_resolved_with_context(
&self,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
match plan.mode() {
crate::ToolExecutionMode::Fast => self.dispatch_with_context(call, context).await,
crate::ToolExecutionMode::Streaming | crate::ToolExecutionMode::Detached => {
Err(crate::error::ToolError::unavailable(
call.name,
crate::ToolUnavailableReason::ExecutionModeOwnerUnavailable,
))
}
}
}
/// Poll for external tool updates from background operations (e.g. async MCP loading).
///
/// The default implementation returns an empty update. Implementations that
/// support background tool loading (like `McpRouterAdapter`) override this
/// to drain completed results and report pending servers.
async fn poll_external_updates(&self) -> ExternalToolUpdate {
ExternalToolUpdate::default()
}
/// Snapshot the live external tool-surface machine state, if supported.
///
/// This is a hidden diagnostic surface for MeerkatMachine mapping work.
/// Dispatchers that do not own dynamic external tool mutation should
/// return `None`.
fn external_tool_surface_snapshot(&self) -> Option<crate::ExternalToolSurfaceSnapshot> {
None
}
/// Query which optional bindings this dispatcher supports.
fn capabilities(&self) -> DispatcherCapabilities {
DispatcherCapabilities::default()
}
/// Bind a session-canonical ops registry into this dispatcher.
///
/// Dispatchers that emit session-visible `AsyncOpRef`s must route those
/// operation IDs into the bound registry. Under the identity-first Mob
/// regime the owner binding passed here is the canonical bridge session
/// binding, even though many compatibility surfaces still spell it
/// `session_id`. Default returns Unsupported.
fn bind_ops_lifecycle(
self: Arc<Self>,
_registry: Arc<dyn crate::ops_lifecycle::OpsLifecycleRegistry>,
_owner_bridge_session_id: crate::types::SessionId,
) -> Result<BindOutcome, OpsLifecycleBindError> {
Err(OpsLifecycleBindError::Unsupported)
}
/// Return the completion enrichment provider, if available.
///
/// Dispatchers with shell job management return a provider that maps
/// operation IDs to display details (job ID, status detail string).
fn completion_enrichment(
&self,
) -> Option<Arc<dyn crate::completion_feed::CompletionEnrichmentProvider>> {
None
}
/// Bind a session-scoped MCP server lifecycle handle (Phase 5G / T5g).
///
/// Dispatchers that manage per-server MCP handshake lifecycle (like
/// `McpRouterAdapter`) use the handle to mirror connection state into
/// the session's MeerkatMachine DSL. The default implementation is a
/// no-op for dispatchers that have no MCP handshake to route.
fn bind_mcp_server_lifecycle_handle(
&self,
_handle: Arc<dyn crate::handles::McpServerLifecycleHandle>,
) {
}
/// Bind the session-canonical external tool-surface handle.
///
/// MCP dispatchers use this to route add/remove/reload/call lifecycle
/// semantics through the session's MeerkatMachine DSL instead of their
/// standalone compatibility projection. The default implementation is a
/// no-op for dispatchers that do not own dynamic external tool surfaces.
fn bind_external_tool_surface_handle(
&self,
_handle: Arc<dyn crate::handles::ExternalToolSurfaceHandle>,
) {
}
}
/// Resolve a plan against the exact live root dispatcher allocation.
///
/// The returned plan retains an ephemeral `Arc` lease to that allocation.
/// This makes reconstruction and allocator address reuse unforgeable without
/// serializing process-local authority or conflating it with durable job
/// fencing.
pub fn resolve_tool_execution_plan_fenced<T: AgentToolDispatcher + ?Sized + 'static>(
dispatcher: &Arc<T>,
call: ToolCallView<'_>,
dispatch_context: &ToolDispatchContext,
resolution_context: &crate::ToolExecutionResolutionContext,
) -> Result<crate::ResolvedToolExecutionPlan, crate::ToolExecutionResolutionError> {
let before = dispatcher.execution_binding_fingerprint(call.name)?;
let plan = dispatcher.resolve_execution_plan(call, dispatch_context, resolution_context)?;
if dispatcher.execution_binding_fingerprint(call.name)? != before {
return Err(crate::ToolExecutionResolutionError::Unavailable {
tool_name: call.name.to_string(),
reason: crate::ToolUnavailableReason::ExecutionOwnerChanged,
});
}
let witness = crate::ToolExecutionOwnerWitness::new("root-dispatcher", call.name, before)
.map_err(crate::ToolExecutionResolutionError::from)?;
plan.with_owner_witness(witness)?
.bind_root_dispatch(Arc::clone(dispatcher), call)
}
/// Dispatch a plan only through the exact root allocation and exact canonical
/// call identity used during resolution.
pub async fn dispatch_tool_execution_plan_fenced<T: AgentToolDispatcher + ?Sized + 'static>(
dispatcher: &Arc<T>,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
plan.validate_root_dispatch(dispatcher, call)?;
let witness = plan.owner_witness("root-dispatcher").ok_or_else(|| {
crate::error::ToolError::unavailable(
call.name,
crate::ToolUnavailableReason::ExecutionOwnerChanged,
)
})?;
if witness.binding_fingerprint() != &dispatcher.execution_binding_fingerprint(call.name)? {
return Err(crate::error::ToolError::unavailable(
call.name,
crate::ToolUnavailableReason::ExecutionOwnerChanged,
));
}
match plan.kind() {
crate::ResolvedExecutionKind::Streaming(policy) => {
let absolute_timeout = plan
.deadlines()
.effective_timeout()
.unwrap_or_else(|| policy.absolute_timeout());
crate::streaming_tool::supervise_streaming_tool(
call.name,
policy.inactivity_timeout(),
absolute_timeout,
|streaming| {
let streaming_context = context.clone().with_streaming(streaming);
async move {
dispatcher
.dispatch_resolved_with_context(call, &streaming_context, plan)
.await
}
},
)
.await
}
crate::ResolvedExecutionKind::Fast | crate::ResolvedExecutionKind::Detached(_) => {
dispatcher
.dispatch_resolved_with_context(call, context, plan)
.await
}
}
}
/// Compute whether the current exact catalog should stay inline or switch to deferred mode.
pub fn select_tool_catalog_mode<T>(dispatcher: &T) -> ToolCatalogMode
where
T: AgentToolDispatcher + ?Sized,
{
let capabilities = dispatcher.tool_catalog_capabilities();
if !capabilities.exact_catalog {
return ToolCatalogMode::Inline;
}
let pending_sources = dispatcher.pending_catalog_sources();
let catalog = dispatcher.tool_catalog();
select_catalog_mode_from_snapshot(
capabilities.exact_catalog,
catalog.as_ref(),
pending_sources.as_ref(),
)
}
/// Compute whether the catalog control plane should be composed for this
/// dispatcher, even if the current adaptive snapshot remains inline.
pub fn should_compose_tool_catalog_control_plane<T>(dispatcher: &T) -> bool
where
T: AgentToolDispatcher + ?Sized,
{
let capabilities = dispatcher.tool_catalog_capabilities();
if !capabilities.exact_catalog {
return false;
}
if capabilities.may_require_catalog_control_plane {
return true;
}
let pending_sources = dispatcher.pending_catalog_sources();
if !pending_sources.is_empty() {
return true;
}
let catalog = dispatcher.tool_catalog();
deferred_session_entry_count(catalog.as_ref()) > 0
}
/// Error from [`AgentToolDispatcher::bind_ops_lifecycle`].
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum OpsLifecycleBindError {
#[error("ops lifecycle binding is unsupported")]
Unsupported,
#[error("dispatcher has shared ownership and cannot be rebound")]
SharedOwnership,
}
/// A tool dispatcher that filters tools based on a policy
///
/// Legacy tool lists are filtered once at construction time based on the
/// allowed_tools list. Exact-catalog dispatchers keep catalog callability live.
/// The inner dispatcher is used for actual dispatch, but only allowed tools are
/// exposed via tools() and dispatch() returns AccessDenied for filtered tools.
pub struct FilteredToolDispatcher<T: AgentToolDispatcher + ?Sized> {
inner: Arc<T>,
allowed_tools: ToolNameSet,
/// Pre-computed filtered tool list for non-exact dispatchers.
filtered_tools: Arc<[Arc<ToolDef>]>,
}
impl<T: AgentToolDispatcher + ?Sized> FilteredToolDispatcher<T> {
pub fn new<I, N>(inner: Arc<T>, allowed_tools: I) -> Self
where
I: IntoIterator<Item = N>,
N: Into<ToolName>,
{
let allowed_set: ToolNameSet = allowed_tools
.into_iter()
.map(Into::into)
.collect::<ToolNameSet>();
let filtered: Vec<Arc<ToolDef>> = if inner.tool_catalog_capabilities().exact_catalog {
inner
.tool_catalog()
.iter()
.filter(|entry| entry.currently_callable())
.map(|entry| Arc::clone(&entry.tool))
.filter(|t| allowed_set.contains(t.name.as_str()))
.collect()
} else {
inner
.tools()
.iter()
.filter(|t| allowed_set.contains(t.name.as_str()))
.map(Arc::clone)
.collect()
};
Self {
inner,
allowed_tools: allowed_set,
filtered_tools: filtered.into(),
}
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T: AgentToolDispatcher + ?Sized + 'static> AgentToolDispatcher for FilteredToolDispatcher<T> {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
if self.inner.tool_catalog_capabilities().exact_catalog {
return self
.inner
.tool_catalog()
.iter()
.filter(|entry| entry.currently_callable())
.map(|entry| Arc::clone(&entry.tool))
.filter(|tool| self.allowed_tools.contains(tool.name.as_str()))
.collect::<Vec<_>>()
.into();
}
Arc::clone(&self.filtered_tools)
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
self.dispatch_with_context(call, &ToolDispatchContext::default())
.await
}
async fn dispatch_with_context(
&self,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
if !self.allowed_tools.contains(call.name) {
let inner_knows_tool = if self.inner.tool_catalog_capabilities().exact_catalog {
self.inner
.tool_catalog()
.iter()
.any(|entry| entry.tool.name == call.name)
} else {
self.inner.tools().iter().any(|tool| tool.name == call.name)
};
if !inner_knows_tool {
return Err(crate::error::ToolError::not_found(call.name));
}
return Err(crate::error::ToolError::access_denied(call.name));
}
self.inner.dispatch_with_context(call, context).await
}
async fn dispatch_resolved_with_context(
&self,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
if !self.allowed_tools.contains(call.name) {
let inner_knows_tool = if self.inner.tool_catalog_capabilities().exact_catalog {
self.inner
.tool_catalog()
.iter()
.any(|entry| entry.tool.name == call.name)
} else {
self.inner.tools().iter().any(|tool| tool.name == call.name)
};
if !inner_knows_tool {
return Err(crate::error::ToolError::not_found(call.name));
}
return Err(crate::error::ToolError::access_denied(call.name));
}
self.inner
.dispatch_resolved_with_context(call, context, plan)
.await
}
fn tool_catalog_capabilities(&self) -> ToolCatalogCapabilities {
self.inner.tool_catalog_capabilities()
}
fn tool_catalog(&self) -> Arc<[ToolCatalogEntry]> {
if !self.inner.tool_catalog_capabilities().exact_catalog {
return self
.tools()
.iter()
.map(|tool| ToolCatalogEntry::session_inline(Arc::clone(tool), true))
.collect::<Vec<_>>()
.into();
}
self.inner
.tool_catalog()
.iter()
.filter(|entry| self.allowed_tools.contains(entry.tool.name.as_str()))
.cloned()
.collect::<Vec<_>>()
.into()
}
fn execution_binding_fingerprint(
&self,
tool_name: &str,
) -> Result<crate::EphemeralToolBindingFingerprint, crate::ToolExecutionResolutionError> {
let catalog = self.tool_catalog();
let entry = catalog
.iter()
.find(|entry| entry.tool.name == tool_name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: tool_name.to_string(),
})?;
let child = self.inner.execution_binding_fingerprint(tool_name)?;
Ok(crate::ephemeral_tool_catalog_binding_fingerprint(entry)
.with_live_authority(0, 0)
.with_dependency(&child))
}
fn resolve_execution_plan(
&self,
call: ToolCallView<'_>,
dispatch_context: &ToolDispatchContext,
resolution_context: &crate::ToolExecutionResolutionContext,
) -> Result<crate::ResolvedToolExecutionPlan, crate::ToolExecutionResolutionError> {
if !self.allowed_tools.contains(call.name) {
let inner_knows_tool = if self.inner.tool_catalog_capabilities().exact_catalog {
self.inner
.tool_catalog()
.iter()
.any(|entry| entry.tool.name == call.name)
} else {
self.inner.tools().iter().any(|tool| tool.name == call.name)
};
return Err(if inner_knows_tool {
crate::ToolExecutionResolutionError::AccessDenied {
tool_name: call.name.to_string(),
}
} else {
crate::ToolExecutionResolutionError::NotFound {
tool_name: call.name.to_string(),
}
});
}
let catalog = self.tool_catalog();
let entry = catalog
.iter()
.find(|entry| entry.tool.name == call.name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: call.name.to_string(),
})?;
if let Some(reason) = entry.callability.unavailable_reason() {
return Err(crate::ToolExecutionResolutionError::Unavailable {
tool_name: call.name.to_string(),
reason,
});
}
self.inner
.resolve_execution_plan(call, dispatch_context, resolution_context)
}
fn pending_catalog_sources(&self) -> Arc<[String]> {
self.inner.pending_catalog_sources()
}
async fn poll_external_updates(&self) -> ExternalToolUpdate {
self.inner.poll_external_updates().await
}
fn external_tool_surface_snapshot(&self) -> Option<crate::ExternalToolSurfaceSnapshot> {
self.inner.external_tool_surface_snapshot()
}
fn capabilities(&self) -> DispatcherCapabilities {
self.inner.capabilities()
}
fn bind_ops_lifecycle(
self: Arc<Self>,
registry: Arc<dyn crate::ops_lifecycle::OpsLifecycleRegistry>,
owner_bridge_session_id: crate::types::SessionId,
) -> Result<BindOutcome, OpsLifecycleBindError> {
let owned = Arc::try_unwrap(self).map_err(|_| OpsLifecycleBindError::SharedOwnership)?;
if Arc::strong_count(&owned.inner) == 1 {
let outcome = owned
.inner
.bind_ops_lifecycle(registry, owner_bridge_session_id)?;
let bound = outcome.was_bound();
let d = outcome.into_dispatcher();
let allowed_tools = owned.allowed_tools.into_iter().collect::<Vec<_>>();
Ok(if bound {
BindOutcome::Bound(Arc::new(FilteredToolDispatcher::new(d, allowed_tools)))
} else {
BindOutcome::Skipped(Arc::new(FilteredToolDispatcher::new(d, allowed_tools)))
})
} else {
Ok(BindOutcome::Skipped(Arc::new(FilteredToolDispatcher {
inner: owned.inner,
allowed_tools: owned.allowed_tools,
filtered_tools: owned.filtered_tools,
})))
}
}
fn completion_enrichment(
&self,
) -> Option<Arc<dyn crate::completion_feed::CompletionEnrichmentProvider>> {
self.inner.completion_enrichment()
}
fn bind_mcp_server_lifecycle_handle(
&self,
handle: Arc<dyn crate::handles::McpServerLifecycleHandle>,
) {
self.inner.bind_mcp_server_lifecycle_handle(handle);
}
fn bind_external_tool_surface_handle(
&self,
handle: Arc<dyn crate::handles::ExternalToolSurfaceHandle>,
) {
self.inner.bind_external_tool_surface_handle(handle);
}
}
/// Trait for session stores
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait AgentSessionStore: Send + Sync {
async fn save(&self, session: &Session) -> Result<(), AgentError>;
async fn load(&self, id: &str) -> Result<Option<Session>, AgentError>;
}
/// Runtime policy for inlining peer lifecycle updates into session context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InlinePeerNotificationPolicy {
/// Always inline batched peer lifecycle updates.
Always,
/// Never inline batched peer lifecycle updates.
Never,
/// Inline only when post-drain peer count is at or below this threshold.
AtMost(usize),
}
/// Default inline threshold when no explicit value is configured.
pub const DEFAULT_MAX_INLINE_PEER_NOTIFICATIONS: usize = 50;
impl InlinePeerNotificationPolicy {
/// Resolve policy from transport/build-layer config representation.
pub fn try_from_raw(raw: Option<i32>) -> Result<Self, i32> {
match raw {
None => Ok(Self::AtMost(DEFAULT_MAX_INLINE_PEER_NOTIFICATIONS)),
Some(-1) => Ok(Self::Always),
Some(0) => Ok(Self::Never),
Some(v) if v > 0 => Ok(Self::AtMost(v as usize)),
Some(v) => Err(v),
}
}
}
/// Error returned when a comms runtime capability is not available.
#[derive(Debug, thiserror::Error)]
pub enum CommsCapabilityError {
/// The runtime does not support this capability.
#[error("comms capability not supported: {0}")]
Unsupported(String),
}
/// Trait for comms runtime that can be used with the agent
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait CommsRuntime: Send + Sync {
/// Canonical runtime routing identity for this peer, if available.
///
/// `PeerId` is the UUID-shaped routing key used by peer directories and
/// trust stores. Implementations that only have the legacy string carrier
/// may return a parsed UUID-shaped `public_key()` value; implementations
/// with Ed25519 public keys should override this and return the pubkey-
/// derived canonical [`PeerId`].
fn peer_id(&self) -> Option<PeerId> {
self.public_key()
.as_deref()
.and_then(|public_key| PeerId::parse(public_key).ok())
}
/// Runtime-local transport/auth public key, if available.
///
/// Returns an Ed25519 public key string in `ed25519:<base64>` format.
/// This is not the canonical routing [`PeerId`]; use [`Self::peer_id`]
/// for roster/projection identity and peer-directory lookups.
fn public_key(&self) -> Option<String> {
None
}
/// Runtime-local Ed25519 public key bytes, if available.
///
/// This is the typed form of [`Self::public_key`]. Trust installation
/// paths that need to verify `PeerId`/pubkey consistency should prefer
/// this method over reparsing the string carrier.
fn public_key_bytes(&self) -> Option<[u8; 32]> {
None
}
/// Runtime-local canonical comms routing name, if available.
///
/// This is the peer name used in trusted-peer descriptors and peer
/// directories. It is separate from the advertised transport address so
/// callers do not recover identity by parsing transport strings.
fn comms_name(&self) -> Option<String> {
None
}
/// Runtime-local advertised comms address, if available.
///
/// This is the canonical address the runtime expects peers to use when
/// constructing a [`TrustedPeerDescriptor`]. Implementations that do not
/// expose a stable advertised address can return `None`.
fn advertised_address(&self) -> Option<String> {
None
}
/// Runtime-local bootstrap proof for the initial supervisor bind, if
/// available.
fn bridge_bootstrap_token(&self) -> Option<String> {
None
}
/// Apply a comms trust projection mutation authorized by generated
/// machine/composition authority.
///
/// This is the only mutable trust-store seam.
async fn apply_trust_mutation(
&self,
_mutation: CommsTrustMutation,
) -> Result<CommsTrustMutationResult, SendError> {
Err(SendError::Unsupported(
"apply_trust_mutation not supported for this CommsRuntime".to_string(),
))
}
/// Bind this target runtime to the generated MobMachine owner token whose
/// trust handoffs may mutate mob-owned trust rows.
///
/// Mob runtimes call this before submitting a generated mob trust mutation.
/// Implementations must fail closed when they cannot remember and compare
/// the owner token during [`Self::apply_trust_mutation`].
async fn install_generated_mob_trust_owner(
&self,
_owner: Arc<dyn std::any::Any + Send + Sync>,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"generated mob trust owner binding not supported for this CommsRuntime".to_string(),
))
}
/// Read-only preflight for binding this target runtime to a recovered
/// MobMachine owner token.
///
/// Resume uses this to validate every generated trust repair target before
/// mutating any trust projection row. Implementations must not change the
/// stored owner token here; [`Self::install_recovered_generated_mob_trust_owner`]
/// performs the actual binding after the full batch has passed preflight.
async fn validate_recovered_generated_mob_trust_owner(
&self,
_owner: Arc<dyn std::any::Any + Send + Sync>,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"recovered generated mob trust owner validation not supported for this CommsRuntime"
.to_string(),
))
}
/// Rebind this target runtime to the owner token of a recovered
/// MobMachine authority.
///
/// Recovery reconstructs generated authority from persisted machine state,
/// which gives it a fresh process-local owner token. Implementations may
/// bind this owner only when no generated MobMachine owner is already
/// installed, or when it is the same owner token. They must fail closed
/// rather than replacing a different live owner through recovery plumbing.
async fn install_recovered_generated_mob_trust_owner(
&self,
_owner: Arc<dyn std::any::Any + Send + Sync>,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"recovered generated mob trust owner binding not supported for this CommsRuntime"
.to_string(),
))
}
/// Opaque host-acceptor registration material for reverse-lane demux
/// composition (the runtime's identity pubkey, its ack-signing keypair,
/// and its inbox sender), encoded by the concrete comms crate.
///
/// A host that composes an acceptor demux in front of this runtime (so
/// remote peers can dial one shared listener and be routed to this
/// identity's inbox) decodes the payload where it holds the concrete
/// comms dependency (`meerkat_comms::HostAcceptorRegistrationMaterial`).
/// `None` means this runtime exposes no registration material and the
/// composer must fail closed (no acceptor registration). The default is
/// `None`; only the concrete comms runtime overrides it — the typed
/// trait surface itself continues to expose no signing material.
fn host_acceptor_registration_payload(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
None
}
/// Register a peer for admission-only trust without listing it in the
/// directory.
///
/// Used for control-plane edges — the canonical case is the supervisor
/// bridge for session-backed mob members: lifecycle notifications
/// (`mob.peer_added`, `mob.peer_retired`, …) must land at the member's
/// inbox, but the supervisor must not appear as an ordinary sendable
/// peer in `comms.peers` / REST / RPC / MCP. The admission gate consults
/// both the public and private trust sets; `resolve_peer_directory()`
/// consults only the public set.
async fn add_private_trusted_peer(
&self,
_peer: TrustedPeerDescriptor,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"generated comms private trust mutation authority required".to_string(),
))
}
/// Remove a previously registered private-trust edge by peer ID.
///
/// Returns `true` if the edge was present and removed, `false` if it
/// was not.
async fn remove_private_trusted_peer(&self, _peer_id: &str) -> Result<bool, SendError> {
Err(SendError::Unsupported(
"generated comms private trust mutation authority required".to_string(),
))
}
/// Install the host-owned outbound content-taint declaration.
///
/// The declaration is host-set carrier config, not machine state: the
/// host owns the "this session's content is tainted" fact and this
/// runtime stamps it (inside the signed envelope region) on every
/// outbound content-bearing send until changed. `None` clears the
/// declaration (subsequent envelopes carry no claim — which receivers
/// must never coalesce into `Clean`).
///
/// The declaration is in-memory runtime state: a rebuilt runtime (e.g.
/// a respawned mob member) starts with no declaration, which aligns
/// with fresh-context taint semantics — hosts re-declare when their
/// tracker re-marks the new context.
///
/// Fails typed (never a silent no-op — silently dropping a security
/// declaration would let tainted content ship with a clean-looking
/// envelope) for runtimes that do not carry outbound comms.
fn set_outbound_content_taint(
&self,
_taint: Option<crate::comms::SenderContentTaint>,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"outbound content-taint declaration not supported by this CommsRuntime".to_string(),
))
}
/// Dispatch a canonical comms command.
async fn send(&self, _cmd: CommsCommand) -> Result<SendReceipt, SendError> {
Err(SendError::Unsupported(
"send not implemented for this CommsRuntime".to_string(),
))
}
#[doc(hidden)]
fn stream(&self, scope: StreamScope) -> Result<EventStream, StreamError> {
let scope_desc = match scope {
StreamScope::Session(session_id) => format!("session {session_id}"),
StreamScope::Interaction(interaction_id) => format!("interaction {}", interaction_id.0),
};
Err(StreamError::NotFound(scope_desc))
}
/// List peers visible to this runtime.
async fn peers(&self) -> Vec<PeerDirectoryEntry> {
Vec::new()
}
/// Count peers visible to this runtime.
///
/// Implementations can override this to avoid materializing a full peer list.
async fn peer_count(&self) -> usize {
self.peers().await.len()
}
#[doc(hidden)]
async fn send_and_stream(
&self,
cmd: CommsCommand,
) -> Result<(SendReceipt, EventStream), SendAndStreamError> {
let receipt = self.send(cmd).await?;
Err(SendAndStreamError::StreamAttach {
receipt,
error: StreamError::Internal(
"send_and_stream is not implemented for this runtime".to_string(),
),
})
}
/// Drain comms inbox and return messages formatted for the LLM
async fn drain_messages(&self) -> Vec<String>;
/// Get a notification when new messages arrive
fn inbox_notify(&self) -> Arc<tokio::sync::Notify>;
/// Returns true if a DISMISS signal was seen during the last `drain_messages` call.
fn dismiss_received(&self) -> bool {
false
}
/// Get an event injector for this runtime's inbox.
///
/// Surfaces use this to push external events into the agent inbox.
/// Returns `None` if the implementation doesn't support event injection.
fn event_injector(&self) -> Option<Arc<dyn crate::EventInjector>> {
None
}
/// Internal runtime seam for interaction-scoped streaming.
#[doc(hidden)]
fn interaction_event_injector(
&self,
) -> Option<Arc<dyn crate::event_injector::SubscribableInjector>> {
None
}
/// Drain comms inbox and return structured interactions.
///
/// Default implementation wraps `drain_messages()` results as `InteractionContent::Message`
/// with generated IDs.
async fn drain_inbox_interactions(&self) -> Vec<crate::interaction::InboxInteraction> {
self.drain_messages()
.await
.into_iter()
.map(|text| crate::interaction::InboxInteraction {
objective_id: None,
id: crate::interaction::InteractionId(uuid::Uuid::new_v4()),
from_route: None,
from: "unknown".into(),
content: crate::interaction::InteractionContent::Message {
body: text.clone(),
blocks: None,
},
rendered_text: text,
handling_mode: crate::types::HandlingMode::Queue,
render_metadata: None,
sender_taint: None,
})
.collect()
}
/// Look up and remove a one-shot subscriber for the given interaction.
///
/// Returns the event sender if a subscriber was registered (via `inject_with_subscription`).
/// The entry is removed from the registry on lookup (one-shot).
fn interaction_subscriber(
&self,
_id: &crate::interaction::InteractionId,
) -> Option<tokio::sync::mpsc::Sender<crate::event::AgentEvent>> {
None
}
/// Take and clear the one-shot sender for an interaction-scoped stream.
fn take_interaction_stream_sender(
&self,
_id: &crate::interaction::InteractionId,
) -> Option<tokio::sync::mpsc::Sender<crate::event::AgentEvent>> {
self.interaction_subscriber(_id)
}
/// Signal that an interaction has reached a terminal state (complete or failed).
///
/// Implementations should transition the reservation FSM to `Completed` and
/// clean up registry entries. Called from the keep-alive loop after sending
/// terminal events to the tap.
fn mark_interaction_complete(&self, _id: &crate::interaction::InteractionId) {}
/// Signal that an interaction stream became unusable for an explicit,
/// typed reason. Implementations with machine-owned stream lifecycle must
/// drive `InteractionStreamAbandoned`; transport-only implementations may
/// clean up their local projection directly.
fn abandon_interaction_stream(
&self,
_id: &crate::interaction::InteractionId,
_reason: crate::InteractionStreamAbandonReason,
) {
}
/// Access the session's peer-interaction DSL handle (W1-A).
///
/// Returns `None` for transport-only comms runtimes. A runtime that emits
/// semantic peer request/response receipts must return `Some` after the
/// surface installs machine authority.
fn peer_interaction_handle(
&self,
) -> Option<std::sync::Arc<dyn crate::handles::PeerInteractionHandle>> {
None
}
/// Access peer request/response authority only when the runtime has the
/// complete machine-owned lifecycle pair.
///
/// Semantic peer request/response ingress requires both the peer
/// interaction handle and the paired interaction-stream handle. The stream
/// handle itself stays hidden behind runtime ownership; this witness lets
/// authority boundaries fail closed instead of treating a lone peer handle
/// as sufficient.
fn peer_request_response_authority_handle(
&self,
) -> Option<std::sync::Arc<dyn crate::handles::PeerInteractionHandle>> {
None
}
/// Drain classified inbox interactions.
///
/// Returns interactions with pre-computed classification from ingress.
/// The host loop routes on the stored `PeerInputClass` instead of
/// re-classifying after drain.
///
/// Default returns `Unsupported`. Comms-enabled runtimes must override.
async fn drain_classified_inbox_interactions(
&self,
) -> Result<Vec<crate::interaction::ClassifiedInboxInteraction>, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"drain_classified_inbox_interactions".to_string(),
))
}
/// Drain canonical peer/event ingress candidates.
///
/// This remains the live runtime drain bridge for call sites that consume
/// the `PeerInputCandidate` noun directly. The underlying drain unit is
/// identical to `ClassifiedInboxInteraction`, so the default
/// implementation simply forwards the classified drain path.
async fn drain_peer_input_candidates(&self) -> Vec<crate::interaction::PeerInputCandidate> {
self.drain_classified_inbox_interactions()
.await
.unwrap_or_default()
}
/// Snapshot the currently queued peer-ingress surface without draining it.
///
/// This is a hidden diagnostic capability used while mapping the internal
/// MeerkatMachine boundary onto existing comms ownership.
async fn peer_ingress_queue_snapshot(
&self,
) -> Result<crate::interaction::PeerIngressQueueSnapshot, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"peer_ingress_queue_snapshot".to_string(),
))
}
/// Snapshot the current peer runtime surface for MeerkatMachine mapping.
///
/// This extends the queued ingress snapshot with the local trust membership
/// that governs peer admission.
async fn peer_ingress_runtime_snapshot(
&self,
) -> Result<crate::interaction::PeerIngressRuntimeSnapshot, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"peer_ingress_runtime_snapshot".to_string(),
))
}
/// Snapshot only the public trust projection owned by generated public
/// peer authority.
///
/// Private/control-plane trust edges are admitted by separate generated
/// private authority and must not be reconciled or removed by public peer
/// projection owners.
async fn public_trusted_peer_projection_snapshot(
&self,
) -> Result<Vec<crate::comms::TrustedPeerDescriptor>, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"public_trusted_peer_projection_snapshot".to_string(),
))
}
/// Snapshot the public trust projection owned by one generated source.
///
/// This is the behavior-authority read used by generated trust
/// reconciliation. Compatibility/public snapshots may still union public
/// rows for display, but generated removals must diff only against rows
/// previously installed by the same generated owner.
async fn trusted_peer_projection_snapshot_for_source(
&self,
_source_kind: crate::comms::GeneratedCommsTrustAuthoritySourceKind,
) -> Result<Vec<crate::comms::TrustedPeerDescriptor>, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"trusted_peer_projection_snapshot_for_source".to_string(),
))
}
/// Get a notification that fires only for actionable peer input.
///
/// Default returns `Unsupported`. Comms-enabled runtimes must override.
/// Used by the factory to bridge into `WaitTool` interrupt.
fn actionable_input_notify(&self) -> Result<Arc<tokio::sync::Notify>, CommsCapabilityError> {
Err(CommsCapabilityError::Unsupported(
"actionable_input_notify".to_string(),
))
}
/// Stage a one-shot reply endpoint for a Response to a peer outside the
/// trust store.
///
/// This is the legacy uncorrelated compatibility seam. It is
/// Response-only, one-shot, and trust-store-losing; callers may supply
/// only a machine-authorized endpoint already held in runtime state.
/// Neither a Request's `reply_endpoint` nor any decoded payload/sender
/// address is authority for this method. New ingress response paths use
/// [`Self::stage_correlated_reply_endpoint`] instead.
///
/// Parameters are primitives because core cannot name the comms-crate
/// newtypes (dependency direction). Default fails typed, not no-op:
/// silently dropping a reply-repair staging would strand the remote
/// sender in a timeout with no cause. Callers decide policy — reply
/// drains treat `Unsupported` as "runtime has no staging capability" and
/// proceed, since in-proc runtimes resolve via the ingress route anyway.
async fn stage_declared_reply_endpoint(
&self,
_dest: PeerId,
_signer_pubkey: [u8; 32],
_declared_address: String,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"declared reply endpoint staging not supported".to_string(),
))
}
/// Stage an authenticated one-shot endpoint for the Response correlated
/// to `in_reply_to` from `dest`.
///
/// Unlike the legacy uncorrelated staging seam above, this endpoint is
/// keyed by both peer identity and request id and therefore takes
/// precedence over durable trust only for that exact Response. This is
/// the only Request-ingress callback seam. `signer_pubkey` must
/// come from a signature-verified envelope and derive `dest` in the
/// concrete runtime. `declared_endpoint` must be the classifier's
/// source-confined TCP projection: kernel-observed source IP plus the
/// signed, nonzero declared port. Arbitrary payload addresses,
/// sender-selected hosts, UDS addresses, and open-auth ingress are never
/// callback authority.
async fn stage_correlated_reply_endpoint(
&self,
_dest: PeerId,
_in_reply_to: crate::interaction::InteractionId,
_signer_pubkey: [u8; 32],
_declared_endpoint: crate::comms::PeerAddress,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"correlated reply endpoint staging not supported".to_string(),
))
}
/// Idempotently discard a previously staged correlated endpoint.
/// Responders call this when validation or response sending fails before
/// the Router consumes the exact one-shot entry.
async fn unstage_correlated_reply_endpoint(
&self,
_dest: PeerId,
_in_reply_to: crate::interaction::InteractionId,
) -> Result<(), SendError> {
Err(SendError::Unsupported(
"correlated reply endpoint cleanup not supported".to_string(),
))
}
/// One-shot reply waiter for an agent-blocking bridge request (member
/// upcall lane). Consulted by the comms drain BEFORE session injection: a
/// taken waiter receives the terminal Response candidate (typed
/// terminality intact) and the candidate never becomes session input.
///
/// Returns `Some(sender)` only for a live waiter. A tombstoned (timed
/// out) waiter entry is consumed and `None` is returned — pair with
/// [`Self::has_bridge_reply_waiter`] to distinguish "tombstone consumed"
/// (discard the late reply) from "never registered" (ordinary session
/// path). Default: no registry (a query, not a capability — absence of a
/// waiter is the universal normal case).
fn take_bridge_reply_waiter(
&self,
_in_reply_to: &crate::interaction::InteractionId,
) -> Option<tokio::sync::oneshot::Sender<crate::interaction::PeerInputCandidate>> {
None
}
/// True when a bridge-reply waiter entry (live or tombstoned) is
/// registered for `in_reply_to`. See [`Self::take_bridge_reply_waiter`].
fn has_bridge_reply_waiter(&self, _in_reply_to: &crate::interaction::InteractionId) -> bool {
false
}
}
/// The main Agent struct
pub struct Agent<C, T, S>
where
C: AgentLlmClient + ?Sized,
T: AgentToolDispatcher + ?Sized,
S: AgentSessionStore + ?Sized,
{
config: AgentConfig,
client: Arc<C>,
tools: Arc<T>,
tool_scope: ToolScope,
store: Arc<S>,
session: Session,
budget: Budget,
retry_policy: RetryPolicy,
depth: u32,
pub(super) comms_runtime: Option<Arc<dyn CommsRuntime>>,
pub(super) hook_engine: Option<Arc<dyn HookEngine>>,
pub(super) hook_run_overrides: HookRunOverrides,
/// Optional context compaction strategy.
pub(crate) compactor: Option<Arc<dyn crate::compact::Compactor>>,
/// Optional host-supplied compaction summary curator. When present it
/// produces the compaction summary instead of the summarization LLM call.
pub(crate) compaction_curator: Option<Arc<dyn crate::compact::CompactionCurator>>,
/// Input tokens from the last LLM response (for compaction trigger).
pub(crate) last_input_tokens: u64,
/// Session-scoped compaction cadence tracked across runs.
pub(crate) compaction_cadence: SessionCompactionCadence,
/// Optional memory store for indexing compaction discards.
pub(crate) memory_store: Option<Arc<dyn crate::memory::MemoryStore>>,
/// Runtime-owned resultful handoff for durable transcript+memory
/// compaction pairs. Absent on standalone paths.
pub(crate) compaction_commit_coordinator:
Option<Arc<dyn crate::memory::CompactionCommitCoordinator>>,
/// Typed lifecycle for the current transcript-rewrite + staged-memory
/// transaction. Runtime reconciliation advances this to commit-only before
/// touching the memory store; abort is legal only while runtime commit is
/// still pending.
pub(crate) compaction_transaction: Option<CompactionTransaction>,
/// Deterministic projection identity installed immediately before the
/// durable stage await. A hard interrupt can drop that await before a
/// receipt reaches the transaction owner, so cleanup must retain the exact
/// identity rather than infer empty RuntimeStore authority.
pub(crate) in_flight_compaction_stage: Option<crate::memory::CompactionProjectionId>,
/// Optional skill engine for per-turn `/skill-ref` activation.
pub(crate) skill_engine: Option<Arc<crate::skills::SkillRuntime>>,
/// Skill references to resolve and inject for the next turn.
/// Set by surfaces before calling `run()`, consumed on run start.
pub pending_skill_references: Option<Vec<crate::skills::SkillKey>>,
/// Per-interaction event tap for streaming events to subscribers.
pub(crate) event_tap: crate::event_tap::EventTap,
/// Shared control state for runtime system-context appends.
pub(crate) system_context_state: crate::session::SystemContextStateHandle,
/// Optional default event channel configured at build time.
/// Used by run methods when no per-call event channel is provided.
pub(crate) default_event_tx: Option<tokio::sync::mpsc::Sender<crate::event::AgentEvent>>,
/// Optional session checkpointer for keep-alive persistence.
///
/// Wired by `AgentBuilder::with_checkpointer`, installed by
/// `PersistentSessionService`, and consumed by
/// `Agent::checkpoint_current_session`.
pub(crate) checkpointer: Option<Arc<dyn crate::checkpoint::SessionCheckpointer>>,
/// Optional blob store used to hydrate image refs at execution seams.
pub(crate) blob_store: Option<Arc<dyn crate::BlobStore>>,
/// Original error detail preserved from `terminalize_fatal_error` so
/// `build_result` can include the actual failure message (e.g. the API
/// error body) instead of only the generic terminal-cause description.
pub(crate) terminal_error_detail: Option<String>,
/// Structured metadata captured from that concrete error before the
/// public result is normalized into `AgentError::TerminalFailure`.
pub(crate) terminal_error_metadata: Option<crate::TurnErrorMetadata>,
/// True once the current run has accepted `RunCompleted` hooks.
pub(crate) run_completed_hooks_applied: bool,
/// True once the current run's public `RunCompleted` event has been
/// emitted. Extraction may continue afterward as a separate post-run phase.
pub(crate) run_completed_event_emitted: bool,
/// Comms intents that should be silently injected into the session
/// without triggering an LLM turn. Matched against `InteractionContent::Request.intent`.
#[allow(dead_code)] // Used by comms_impl when comms feature is enabled
pub(crate) silent_comms_intents: Vec<String>,
/// Optional shared lifecycle registry for async operations.
pub(crate) ops_lifecycle: Option<Arc<dyn crate::ops_lifecycle::OpsLifecycleRegistry>>,
/// Optional completion feed for cursor-based completion delivery.
pub(crate) completion_feed: Option<Arc<dyn crate::completion_feed::CompletionFeed>>,
/// Shared epoch cursor state for runtime-backed cursor writeback.
pub(crate) epoch_cursor_state: Option<Arc<crate::runtime_epoch::EpochCursorState>>,
/// Local cursor into the completion feed — only the agent boundary advances this.
pub(crate) applied_cursor: crate::completion_feed::CompletionSeq,
/// Optional enrichment provider for completion display details.
pub(crate) completion_enrichment:
Option<Arc<dyn crate::completion_feed::CompletionEnrichmentProvider>>,
/// Shared effective mob authority handle. Owned by the agent, passed to
/// mob tools at construction for authorization reads. Updated by
/// `apply_session_effects` after each tool batch as a derived projection
/// of the canonical `session.build_state().mob_tool_authority_context`.
pub(crate) mob_authority_handle:
Option<Arc<std::sync::RwLock<crate::service::MobToolAuthorityContext>>>,
/// Runtime-backed turn-state handle, provided by the session runtime bindings.
pub(crate) turn_state_handle: Option<Arc<dyn crate::TurnStateHandle>>,
/// Runtime-backed model-routing authority. Sticky fallback commits route
/// through this handle in the compensated client/auth/machine transaction.
pub(crate) model_routing_handle: Option<Arc<dyn crate::handles::ModelRoutingHandle>>,
/// Runtime-owned durable sticky-fallback transaction coordinator.
/// Standalone agents leave this absent and consume staged machine commits
/// synchronously in-process.
pub(crate) sticky_model_fallback_commit_coordinator:
Option<Arc<dyn crate::handles::StickyModelFallbackCommitCoordinator>>,
/// Saga state retained across cancellation while the supervised durable
/// sticky-fallback transaction is in flight.
pub(crate) pending_sticky_model_fallback_activation:
Option<state::PendingStickyModelFallbackActivation>,
/// Async operation references staged behind an external callback boundary.
/// They are registered with the fresh continuation run before it can call
/// the provider, preserving Barrier versus Detached semantics.
pub(crate) pending_callback_async_ops: Option<Vec<crate::ops::AsyncOpRef>>,
/// Effective model registry captured by the construction pipeline.
/// Fallback profile and limit truth is freshly resolved through this exact
/// registry before it can reach the routing machine.
pub(crate) effective_model_registry: Option<Arc<crate::ModelRegistry>>,
/// Registry-minted facts for the active model. This replaces client-local
/// capability/limit projections as the durable source used by later turns.
pub(crate) active_model_profile: Option<crate::ModelProfileWitness>,
/// True when the runtime control plane must stamp execution kind metadata.
pub(crate) runtime_execution_kind_required: bool,
/// Typed execution intent for the current run, when this turn is owned by
/// the runtime control plane rather than a direct surface call.
pub(crate) runtime_execution_kind: Option<crate::lifecycle::RuntimeExecutionKind>,
/// Exact per-call witness that the core turn machine admitted a runtime
/// run. A completed future alone is not sufficient evidence: preflight
/// failures can return before `StartConversationRun` and must never reuse
/// the previous turn's terminal snapshot.
pub(crate) runtime_started_run_id: Option<crate::lifecycle::RunId>,
/// Machine-terminal failure observed for the exact runtime run above.
/// Kept separate from the public `AgentError` so direct session surfaces
/// preserve their original typed errors while the runtime can commit a
/// failed-but-applied turn atomically.
pub(crate) runtime_terminal_failure_witness:
Option<Result<crate::TurnErrorMetadata, crate::error::AgentError>>,
/// Stable transcript identity for the active runtime-owned turn.
pub(crate) active_transcript_identity: Option<crate::types::TranscriptMessageIdentity>,
/// Runtime-backed external tool-surface diagnostic handle, when provided
/// by the session runtime bindings.
pub(crate) external_tool_surface_handle: Option<Arc<dyn crate::ExternalToolSurfaceHandle>>,
/// Runtime-backed auth lease handle (Phase 1.5-rev).
pub(crate) auth_lease_handle: Option<crate::handles::GeneratedAuthLeaseHandle>,
/// Runtime-backed MCP server lifecycle handle (Phase 5G / T5g). When set,
/// the agent loop reads `pending_server_ids()` at each CallingLlm boundary
/// to decide whether to emit the `[MCP_PENDING]` system notice.
pub(crate) mcp_server_lifecycle_handle:
Option<Arc<dyn crate::handles::McpServerLifecycleHandle>>,
/// Producer end of the typed cancel-after-boundary command channel.
///
/// Retained so [`Agent::cancel_after_boundary_handle`] can hand cloned
/// senders to the surface that requests boundary-only cancellation. The
/// agent never sends on this end itself; it only drains the matching
/// receiver at turn boundaries.
pub(crate) cancel_after_boundary_tx: CancelAfterBoundarySender,
/// Consumer end of the typed cancel-after-boundary command channel.
///
/// Drained (non-blocking) at each turn boundary by
/// `observe_cancel_after_boundary_request`, replacing the previous
/// `.swap`-polled `AtomicBool`. A delivered [`CancelAfterBoundaryCommand`]
/// is observed at most once per boundary, mirroring the prior edge
/// semantics.
pub(crate) cancel_after_boundary_rx:
tokio::sync::mpsc::UnboundedReceiver<CancelAfterBoundaryCommand>,
/// Optional resolver for model-specific operational defaults (e.g., call timeout).
/// Consulted at each LLM call for hot-swap-aware profile default resolution.
pub(crate) model_defaults_resolver:
Option<Arc<dyn crate::model_defaults::ModelOperationalDefaultsResolver>>,
/// Explicit call-timeout override from the build/config composition seam.
/// Takes precedence over profile-derived defaults.
pub(crate) call_timeout_override: crate::config::CallTimeoutOverride,
/// Structured-output extraction state carried into RunResult.
pub(crate) extraction_state: extraction::ExtractionState,
/// Last published hidden deferred-catalog names.
pub(crate) last_hidden_deferred_catalog_names: BTreeSet<crate::types::ToolName>,
/// Last published pending catalog sources.
pub(crate) last_pending_catalog_sources: BTreeSet<String>,
/// Dispatch-time projection of the current turn input for contextual tools.
pub(crate) tool_dispatch_context: ToolDispatchContext,
/// Runtime-owned dispatch metadata for this turn.
pub(crate) turn_tool_dispatch_metadata: BTreeMap<String, serde_json::Value>,
/// Typed tool-execution policy (per-call timeouts + concurrency bound)
/// applied to the normal LLM-driven tool dispatch loop. Populated by the
/// composition seam via `AgentBuilder::with_tools_config`; defaults to
/// `ToolsConfig::default()` for standalone/test construction.
pub(crate) tools_config: crate::config::ToolsConfig,
}
#[derive(Clone)]
pub(crate) struct CompactionRollbackState {
pub(crate) rollback_session: Session,
pub(crate) rollback_last_input_tokens: u64,
pub(crate) rollback_compaction_cadence: SessionCompactionCadence,
}
pub(crate) enum CompactionTransactionPhase {
AwaitingRuntimeCommit(Box<CompactionRollbackState>),
RuntimeCommitted { bookkeeping_complete: bool },
AbortPending { cadence_persist_pending: bool },
}
pub(crate) struct CompactionTransaction {
pub(crate) phase: CompactionTransactionPhase,
pub(crate) projections: Vec<crate::memory::CompactionProjectionId>,
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
mod tests {
use super::{
AgentToolDispatcher, CommsRuntime, DEFAULT_MAX_INLINE_PEER_NOTIFICATIONS,
FilteredToolDispatcher, InlinePeerNotificationPolicy, ToolDispatchContext,
};
use crate::comms::{
PeerAddress, PeerId, PeerName, PeerTransport, SendError, TrustedPeerDescriptor,
};
use crate::types::{ContentBlock, ContentInput, ToolCallView, ToolDef, ToolResult};
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
use tokio::sync::Notify;
struct NoopCommsRuntime {
notify: Arc<Notify>,
}
struct ContextAwareToolDispatcher;
struct ExactExecutionDispatcher {
catalog: Arc<[crate::ToolCatalogEntry]>,
}
struct HybridExecutionDispatcher {
catalog: Arc<[crate::ToolCatalogEntry]>,
}
struct StreamingExecutionDispatcher {
catalog: Arc<[crate::ToolCatalogEntry]>,
saw_streaming_context: Arc<std::sync::atomic::AtomicBool>,
}
struct IdenticalMutationDispatcher {
tool: ToolDef,
epoch: std::sync::atomic::AtomicU64,
mutate_on_resolve: bool,
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AgentToolDispatcher for ContextAwareToolDispatcher {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
Arc::from([Arc::new(ToolDef {
name: "inspect_context".into(),
description: "inspect context".to_string(),
input_schema: json!({"type": "object"}),
provenance: None,
})])
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
Ok(ToolResult::new(
call.id.to_string(),
json!({"saw_context_image": false}).to_string(),
false,
)
.into())
}
async fn dispatch_with_context(
&self,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
let saw_context_image = context
.current_turn()
.and_then(|turn| turn.image_ref(0))
.and_then(|image_ref| context.current_turn_image(image_ref))
.is_some();
Ok(ToolResult::new(
call.id.to_string(),
json!({"saw_context_image": saw_context_image}).to_string(),
false,
)
.into())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AgentToolDispatcher for ExactExecutionDispatcher {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
self.catalog
.iter()
.filter(|entry| entry.currently_callable())
.map(|entry| Arc::clone(&entry.tool))
.collect::<Vec<_>>()
.into()
}
fn tool_catalog_capabilities(&self) -> crate::ToolCatalogCapabilities {
crate::ToolCatalogCapabilities {
exact_catalog: true,
may_require_catalog_control_plane: false,
}
}
fn tool_catalog(&self) -> Arc<[crate::ToolCatalogEntry]> {
Arc::clone(&self.catalog)
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
Ok(ToolResult::new(call.id.to_string(), "ok".to_string(), false).into())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AgentToolDispatcher for HybridExecutionDispatcher {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
self.catalog
.iter()
.filter(|entry| entry.currently_callable())
.map(|entry| Arc::clone(&entry.tool))
.collect::<Vec<_>>()
.into()
}
fn tool_catalog_capabilities(&self) -> crate::ToolCatalogCapabilities {
crate::ToolCatalogCapabilities {
exact_catalog: true,
may_require_catalog_control_plane: false,
}
}
fn tool_catalog(&self) -> Arc<[crate::ToolCatalogEntry]> {
Arc::clone(&self.catalog)
}
fn resolve_execution_plan(
&self,
call: ToolCallView<'_>,
_dispatch_context: &ToolDispatchContext,
resolution_context: &crate::ToolExecutionResolutionContext,
) -> Result<crate::ResolvedToolExecutionPlan, crate::ToolExecutionResolutionError> {
let entry = self
.catalog
.iter()
.find(|entry| entry.tool.name == call.name)
.ok_or_else(|| crate::ToolExecutionResolutionError::NotFound {
tool_name: call.name.to_string(),
})?;
let arguments: serde_json::Value =
serde_json::from_str(call.args.get()).map_err(|error| {
crate::ToolExecutionResolutionError::InvalidArguments {
tool_name: call.name.to_string(),
reason: error.to_string(),
}
})?;
let mode = if arguments["run_detached"] == true {
crate::ToolExecutionMode::Detached
} else {
crate::ToolExecutionMode::Fast
};
entry
.execution
.resolve(mode, resolution_context.deadlines().clone())
.map_err(crate::ToolExecutionResolutionError::from)
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
Ok(ToolResult::new(
call.id.to_string(),
json!({"owner": "filtered-hybrid-owner"}).to_string(),
false,
)
.into())
}
async fn dispatch_resolved_with_context(
&self,
call: ToolCallView<'_>,
_context: &ToolDispatchContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
if plan.mode() != crate::ToolExecutionMode::Detached {
return Err(crate::ToolError::execution_failed(
"test detached owner received the wrong plan",
));
}
self.dispatch(call).await
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AgentToolDispatcher for StreamingExecutionDispatcher {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
self.catalog
.iter()
.map(|entry| Arc::clone(&entry.tool))
.collect::<Vec<_>>()
.into()
}
fn tool_catalog_capabilities(&self) -> crate::ToolCatalogCapabilities {
crate::ToolCatalogCapabilities {
exact_catalog: true,
may_require_catalog_control_plane: false,
}
}
fn tool_catalog(&self) -> Arc<[crate::ToolCatalogEntry]> {
Arc::clone(&self.catalog)
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
Err(crate::ToolError::unavailable(
call.name,
crate::ToolUnavailableReason::ExecutionModeOwnerUnavailable,
))
}
async fn dispatch_resolved_with_context(
&self,
call: ToolCallView<'_>,
context: &ToolDispatchContext,
plan: &crate::ResolvedToolExecutionPlan,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
if plan.mode() != crate::ToolExecutionMode::Streaming {
return Err(crate::ToolError::execution_failed(
"streaming owner received a non-streaming plan",
));
}
let streaming = context.streaming().ok_or_else(|| {
crate::ToolError::unavailable(
call.name,
crate::ToolUnavailableReason::ExecutionModeOwnerUnavailable,
)
})?;
streaming
.progress()
.try_report(
crate::ToolProgressFrame::message("accepted through wrapper")
.map_err(|error| crate::ToolError::other(error.to_string()))?,
)
.map_err(|error| crate::ToolError::other(error.to_string()))?;
self.saw_streaming_context
.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(ToolResult::new(call.id.to_string(), "stream complete".to_string(), false).into())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AgentToolDispatcher for IdenticalMutationDispatcher {
fn tools(&self) -> Arc<[Arc<ToolDef>]> {
Arc::from([Arc::new(self.tool.clone())])
}
fn tool_catalog_capabilities(&self) -> crate::ToolCatalogCapabilities {
crate::ToolCatalogCapabilities {
exact_catalog: true,
may_require_catalog_control_plane: false,
}
}
fn tool_catalog(&self) -> Arc<[crate::ToolCatalogEntry]> {
Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(self.tool.clone()),
true,
)])
}
fn execution_binding_epoch(&self, _tool_name: &str) -> u64 {
self.epoch.load(std::sync::atomic::Ordering::SeqCst)
}
fn resolve_execution_plan(
&self,
_call: ToolCallView<'_>,
_dispatch_context: &ToolDispatchContext,
resolution_context: &crate::ToolExecutionResolutionContext,
) -> Result<crate::ResolvedToolExecutionPlan, crate::ToolExecutionResolutionError> {
let plan = crate::ToolExecutionContract::default()
.resolve_default(resolution_context.deadlines().clone())
.map_err(crate::ToolExecutionResolutionError::from)?;
if self.mutate_on_resolve {
self.epoch.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
Ok(plan)
}
async fn dispatch(
&self,
call: ToolCallView<'_>,
) -> Result<crate::ops::ToolDispatchOutcome, crate::error::ToolError> {
Ok(ToolResult::new(call.id.to_string(), "ok".to_string(), false).into())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl CommsRuntime for NoopCommsRuntime {
async fn drain_messages(&self) -> Vec<String> {
Vec::new()
}
fn inbox_notify(&self) -> std::sync::Arc<Notify> {
self.notify.clone()
}
}
#[tokio::test]
async fn test_comms_runtime_trait_defaults_hide_unimplemented_features() {
let runtime = NoopCommsRuntime {
notify: Arc::new(Notify::new()),
};
assert!(<NoopCommsRuntime as CommsRuntime>::public_key(&runtime).is_none());
// The only mutable trust seam is apply_trust_mutation; without a
// generated handoff it fails closed.
let peer = TrustedPeerDescriptor {
peer_id: PeerId::new(),
name: PeerName::new("peer-a").expect("valid peer name"),
address: PeerAddress::new(PeerTransport::Inproc, "peer-a"),
pubkey: [0u8; 32],
};
let result =
<NoopCommsRuntime as CommsRuntime>::add_private_trusted_peer(&runtime, peer).await;
assert!(matches!(result, Err(SendError::Unsupported(_))));
}
/// T-12: bridge-reply waiter + declared-reply-endpoint trait defaults.
/// `take_bridge_reply_waiter` → None (no registry),
/// `has_bridge_reply_waiter` → false, and
/// `stage_declared_reply_endpoint` fails typed (never a silent no-op) so
/// a caller cannot mistake a dropped security-relevant repair for success.
#[tokio::test]
async fn test_comms_runtime_bridge_reply_defaults() {
let runtime = NoopCommsRuntime {
notify: Arc::new(Notify::new()),
};
let interaction_id = crate::interaction::InteractionId(uuid::Uuid::new_v4());
assert!(
<NoopCommsRuntime as CommsRuntime>::take_bridge_reply_waiter(&runtime, &interaction_id)
.is_none()
);
assert!(
!<NoopCommsRuntime as CommsRuntime>::has_bridge_reply_waiter(&runtime, &interaction_id)
);
let staged = <NoopCommsRuntime as CommsRuntime>::stage_declared_reply_endpoint(
&runtime,
PeerId::new(),
[0x11u8; 32],
"tcp://127.0.0.1:1".to_string(),
)
.await;
assert!(matches!(staged, Err(SendError::Unsupported(_))));
}
#[tokio::test]
async fn filtered_tool_dispatcher_preserves_dispatch_context() {
let dispatcher =
FilteredToolDispatcher::new(Arc::new(ContextAwareToolDispatcher), ["inspect_context"]);
let args = serde_json::value::RawValue::from_string("{}".to_string())
.expect("empty object should be valid JSON");
let call = ToolCallView {
id: "ctx-1",
name: "inspect_context",
args: &args,
};
let context = ToolDispatchContext::from_current_turn_input(&ContentInput::Blocks(vec![
ContentBlock::Image {
media_type: "image/png".to_string(),
data: "abc".into(),
},
]));
let outcome = dispatcher
.dispatch_with_context(call, &context)
.await
.expect("filtered wrapper should dispatch");
let payload: serde_json::Value =
serde_json::from_str(&outcome.result.text_content()).expect("tool result JSON");
assert_eq!(payload["saw_context_image"], true);
}
#[test]
fn default_execution_plan_resolver_uses_exact_catalog_contract() {
use crate::{
DetachedToolExecutionPolicy, IdempotencyScope, RestartClass, RunnerIdentity,
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner, ToolExecutionContract,
ToolExecutionMode, ToolExecutionResolutionContext,
};
use std::collections::BTreeSet;
use std::time::Duration;
let detached = DetachedToolExecutionPolicy::new(
RunnerIdentity::new("homecore.security_scan", "v1").unwrap(),
RestartClass::NonResumable,
IdempotencyScope::InteractionAndArguments,
Duration::from_secs(10),
)
.unwrap();
let contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Detached]),
ToolExecutionMode::Detached,
None,
Some(detached),
)
.unwrap();
let dispatcher = ExactExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"security_scan",
"scan",
json!({"type": "object"}),
)),
true,
)
.with_execution_contract(contract)]),
};
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "call-1",
name: "security_scan",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = dispatcher
.resolve_execution_plan(call, &ToolDispatchContext::default(), &resolution)
.expect("declared plan resolves");
assert_eq!(plan.mode(), ToolExecutionMode::Detached);
assert_eq!(
plan.deadlines().effective_timeout(),
Some(Duration::from_secs(10))
);
assert_eq!(
plan.deadlines().winner().map(|winner| winner.owner()),
Some(ToolDeadlineOwner::DetachedSubmission)
);
}
#[tokio::test]
async fn default_resolved_dispatch_refuses_detached_plan_before_ordinary_dispatch() {
use crate::{
DetachedToolExecutionPolicy, IdempotencyScope, RestartClass, RunnerIdentity,
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner, ToolExecutionContract,
ToolExecutionMode, ToolExecutionResolutionContext,
};
use std::collections::BTreeSet;
use std::time::Duration;
let detached = DetachedToolExecutionPolicy::new(
RunnerIdentity::new("detached.owner", "v1").unwrap(),
RestartClass::NonResumable,
IdempotencyScope::ToolCall,
Duration::from_secs(10),
)
.unwrap();
let contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Detached]),
ToolExecutionMode::Detached,
None,
Some(detached),
)
.unwrap();
let dispatcher = ExactExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"security_scan",
"scan",
json!({"type": "object"}),
)),
true,
)
.with_execution_contract(contract)]),
};
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "detached-call",
name: "security_scan",
args: &args,
};
let context = ToolDispatchContext::default();
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = dispatcher
.resolve_execution_plan(call, &context, &resolution)
.expect("detached plan resolves");
let error = dispatcher
.dispatch_resolved_with_context(call, &context, &plan)
.await
.expect_err("the default dispatcher must not lower detached work to dispatch()");
assert!(matches!(
error,
crate::ToolError::Unavailable {
reason: crate::ToolUnavailableReason::ExecutionModeOwnerUnavailable,
..
}
));
}
#[tokio::test]
async fn fenced_streaming_dispatch_mints_context_and_filtered_wrapper_preserves_it() {
use crate::{
StreamingToolExecutionPolicy, ToolDeadlineChain, ToolDeadlineContributor,
ToolDeadlineOwner, ToolExecutionContract, ToolExecutionMode,
ToolExecutionResolutionContext,
};
use std::collections::BTreeSet;
use std::time::Duration;
let contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Streaming]),
ToolExecutionMode::Streaming,
Some(
StreamingToolExecutionPolicy::new(Duration::from_secs(5), Duration::from_secs(30))
.unwrap(),
),
None,
)
.unwrap();
let saw_streaming_context = Arc::new(std::sync::atomic::AtomicBool::new(false));
let owner = StreamingExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"stream_scan",
"stream scan",
json!({"type": "object"}),
)),
true,
)
.with_execution_contract(contract)]),
saw_streaming_context: Arc::clone(&saw_streaming_context),
};
let dispatcher = Arc::new(FilteredToolDispatcher::new(
Arc::new(owner),
["stream_scan"],
));
let filtered_catalog = dispatcher.tool_catalog();
assert_eq!(
filtered_catalog[0].execution.default_mode(),
ToolExecutionMode::Streaming
);
let filtered_policy = filtered_catalog[0]
.execution
.streaming_policy()
.expect("wrapper preserves the streaming registration");
assert_eq!(filtered_policy.inactivity_timeout(), Duration::from_secs(5));
assert_eq!(filtered_policy.absolute_timeout(), Duration::from_secs(30));
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "stream-call",
name: "stream_scan",
args: &args,
};
let context = ToolDispatchContext::default();
assert!(
context.streaming().is_none(),
"callers cannot pre-mint the supervised streaming context"
);
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(60),
)])
.unwrap(),
);
let plan =
crate::resolve_tool_execution_plan_fenced(&dispatcher, call, &context, &resolution)
.expect("streaming plan resolves through wrapper");
let outcome =
crate::dispatch_tool_execution_plan_fenced(&dispatcher, call, &context, &plan)
.await
.expect("streaming dispatch completes");
assert_eq!(outcome.result.text_content(), "stream complete");
assert!(
saw_streaming_context.load(std::sync::atomic::Ordering::SeqCst),
"the wrapper must preserve the exact supervised context"
);
}
#[tokio::test]
async fn declared_streaming_without_a_mode_owner_fails_closed_before_plain_dispatch() {
use crate::{
StreamingToolExecutionPolicy, ToolDeadlineChain, ToolDeadlineContributor,
ToolDeadlineOwner, ToolExecutionContract, ToolExecutionMode,
ToolExecutionResolutionContext,
};
use std::collections::BTreeSet;
use std::time::Duration;
let contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Streaming]),
ToolExecutionMode::Streaming,
Some(
StreamingToolExecutionPolicy::new(Duration::from_secs(5), Duration::from_secs(30))
.unwrap(),
),
None,
)
.unwrap();
let dispatcher = Arc::new(ExactExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"ownerless_stream",
"ownerless",
json!({"type": "object"}),
)),
true,
)
.with_execution_contract(contract)]),
});
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "ownerless-call",
name: "ownerless_stream",
args: &args,
};
let context = ToolDispatchContext::default();
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(60),
)])
.unwrap(),
);
let plan =
crate::resolve_tool_execution_plan_fenced(&dispatcher, call, &context, &resolution)
.expect("declaration resolves");
let error = crate::dispatch_tool_execution_plan_fenced(&dispatcher, call, &context, &plan)
.await
.expect_err("missing streaming owner must fail closed");
assert!(matches!(
error,
crate::ToolError::Unavailable {
reason: crate::ToolUnavailableReason::ExecutionModeOwnerUnavailable,
..
}
));
}
#[test]
fn filtered_execution_plan_resolver_rejects_policy_denied_tool() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext, ToolExecutionResolutionError,
};
use std::time::Duration;
let dispatcher =
FilteredToolDispatcher::new(Arc::new(ContextAwareToolDispatcher), Vec::<String>::new());
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "call-hidden",
name: "inspect_context",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let error = dispatcher
.resolve_execution_plan(call, &ToolDispatchContext::default(), &resolution)
.expect_err("hidden tools must not resolve");
assert_eq!(
error,
ToolExecutionResolutionError::AccessDenied {
tool_name: "inspect_context".to_string(),
}
);
}
#[tokio::test]
async fn filtered_execution_plan_forwards_hybrid_resolution_to_visible_owner() {
use crate::{
DetachedToolExecutionPolicy, IdempotencyScope, ResolvedExecutionKind, RestartClass,
RunnerIdentity, ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionContract, ToolExecutionMode, ToolExecutionResolutionContext,
};
use std::collections::BTreeSet;
use std::time::Duration;
let detached = DetachedToolExecutionPolicy::new(
RunnerIdentity::new("filtered-hybrid-owner", "v1").unwrap(),
RestartClass::NonResumable,
IdempotencyScope::InteractionAndArguments,
Duration::from_secs(10),
)
.unwrap();
let contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Fast, ToolExecutionMode::Detached]),
ToolExecutionMode::Fast,
None,
Some(detached),
)
.unwrap();
let dispatcher = FilteredToolDispatcher::new(
Arc::new(HybridExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"hybrid_scan",
"filtered-hybrid-owner catalog",
json!({"type": "object"}),
)),
true,
)
.with_execution_contract(contract)]),
}),
["hybrid_scan"],
);
let args = serde_json::value::RawValue::from_string(r#"{"run_detached":true}"#.to_string())
.unwrap();
let call = ToolCallView {
id: "call-hybrid",
name: "hybrid_scan",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let catalog = dispatcher.tool_catalog();
assert_eq!(catalog[0].execution.default_mode(), ToolExecutionMode::Fast);
assert_eq!(catalog[0].tool.description, "filtered-hybrid-owner catalog");
let plan = dispatcher
.resolve_execution_plan(call, &ToolDispatchContext::default(), &resolution)
.expect("visible hybrid tool should delegate plan resolution");
dispatcher
.validate_resolved_execution_plan(call, &resolution, &plan)
.expect("hybrid-selected advertised mode must validate");
let ResolvedExecutionKind::Detached(policy) = plan.kind() else {
panic!("hybrid resolver should select its non-default detached mode");
};
assert_eq!(policy.runner().name(), "filtered-hybrid-owner");
let outcome = dispatcher
.dispatch_resolved_with_context(call, &ToolDispatchContext::default(), &plan)
.await
.expect("visible hybrid tool should preserve resolved dispatch");
let payload: serde_json::Value =
serde_json::from_str(&outcome.result.text_content()).unwrap();
assert_eq!(payload["owner"], "filtered-hybrid-owner");
}
#[test]
fn root_validation_rejects_plan_outside_live_advertised_contract() {
use crate::{
DetachedToolExecutionPolicy, IdempotencyScope, RestartClass, RunnerIdentity,
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner, ToolExecutionContract,
ToolExecutionContractError, ToolExecutionMode, ToolExecutionResolutionContext,
ToolExecutionResolutionError,
};
use std::collections::BTreeSet;
use std::time::Duration;
let dispatcher = ExactExecutionDispatcher {
catalog: Arc::from([crate::ToolCatalogEntry::session_inline(
Arc::new(ToolDef::new(
"fast_only",
"fast only",
json!({"type": "object"}),
)),
true,
)]),
};
let detached = DetachedToolExecutionPolicy::new(
RunnerIdentity::new("dishonest.owner", "v1").unwrap(),
RestartClass::NonResumable,
IdempotencyScope::ToolCall,
Duration::from_secs(10),
)
.unwrap();
let dishonest_contract = ToolExecutionContract::new(
BTreeSet::from([ToolExecutionMode::Detached]),
ToolExecutionMode::Detached,
None,
Some(detached),
)
.unwrap();
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = dishonest_contract
.resolve_default(resolution.deadlines().clone())
.unwrap();
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "dishonest-plan",
name: "fast_only",
args: &args,
};
assert_eq!(
dispatcher.validate_resolved_execution_plan(call, &resolution, &plan),
Err(ToolExecutionResolutionError::Contract(
ToolExecutionContractError::RequestedModeUnsupported {
requested_mode: ToolExecutionMode::Detached,
}
))
);
}
#[tokio::test]
async fn universal_root_fence_accepts_rebuilt_equivalent_catalog_arcs() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext,
};
use std::time::Duration;
let dispatcher: Arc<dyn AgentToolDispatcher> = Arc::new(IdenticalMutationDispatcher {
tool: ToolDef::new("rebuilt", "rebuilt", json!({"type": "object"})),
epoch: std::sync::atomic::AtomicU64::new(0),
mutate_on_resolve: false,
});
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "rebuilt-arcs",
name: "rebuilt",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = crate::resolve_tool_execution_plan_fenced(
&dispatcher,
call,
&ToolDispatchContext::default(),
&resolution,
)
.expect("equivalent rebuilt catalog projections resolve");
crate::dispatch_tool_execution_plan_fenced(
&dispatcher,
call,
&ToolDispatchContext::default(),
&plan,
)
.await
.expect("equivalent rebuilt catalog projections dispatch");
}
#[tokio::test]
async fn universal_root_fence_binds_canonical_call_identity() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext, ToolUnavailableReason,
};
use std::time::Duration;
let dispatcher: Arc<dyn AgentToolDispatcher> = Arc::new(IdenticalMutationDispatcher {
tool: ToolDef::new("bound", "bound", json!({"type": "object"})),
epoch: std::sync::atomic::AtomicU64::new(0),
mutate_on_resolve: false,
});
let resolved_args =
serde_json::value::RawValue::from_string(r#"{"a":1,"b":2}"#.to_string()).unwrap();
let equivalent_args =
serde_json::value::RawValue::from_string(r#"{ "b": 2, "a": 1 }"#.to_string()).unwrap();
let changed_args =
serde_json::value::RawValue::from_string(r#"{"a":1,"b":3}"#.to_string()).unwrap();
let resolved_call = ToolCallView {
id: "bound-call",
name: "bound",
args: &resolved_args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = crate::resolve_tool_execution_plan_fenced(
&dispatcher,
resolved_call,
&ToolDispatchContext::default(),
&resolution,
)
.unwrap();
crate::dispatch_tool_execution_plan_fenced(
&dispatcher,
ToolCallView {
args: &equivalent_args,
..resolved_call
},
&ToolDispatchContext::default(),
&plan,
)
.await
.expect("canonical JSON-equivalent arguments preserve call identity");
let error = crate::dispatch_tool_execution_plan_fenced(
&dispatcher,
ToolCallView {
args: &changed_args,
..resolved_call
},
&ToolDispatchContext::default(),
&plan,
)
.await
.expect_err("different arguments must not dispatch under the old plan");
assert!(matches!(
error,
crate::ToolError::Unavailable {
reason: ToolUnavailableReason::ExecutionOwnerChanged,
..
}
));
}
#[tokio::test]
async fn universal_root_fence_rejects_fresh_dispatcher_reconstruction() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext, ToolUnavailableReason,
};
use std::time::Duration;
let make_dispatcher = || -> Arc<dyn AgentToolDispatcher> {
Arc::new(IdenticalMutationDispatcher {
tool: ToolDef::new("bound", "bound", json!({"type": "object"})),
epoch: std::sync::atomic::AtomicU64::new(0),
mutate_on_resolve: false,
})
};
let original = make_dispatcher();
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "reconstructed",
name: "bound",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
let plan = crate::resolve_tool_execution_plan_fenced(
&original,
call,
&ToolDispatchContext::default(),
&resolution,
)
.unwrap();
let reconstructed = make_dispatcher();
let error = crate::dispatch_tool_execution_plan_fenced(
&reconstructed,
call,
&ToolDispatchContext::default(),
&plan,
)
.await
.expect_err("fresh reconstruction must never reproduce ephemeral root authority");
assert!(matches!(
error,
crate::ToolError::Unavailable {
reason: ToolUnavailableReason::ExecutionOwnerChanged,
..
}
));
}
#[test]
fn universal_root_fence_rejects_direct_identical_metadata_replacement() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext, ToolExecutionResolutionError, ToolUnavailableReason,
};
use std::time::Duration;
let dispatcher: Arc<dyn AgentToolDispatcher> = Arc::new(IdenticalMutationDispatcher {
tool: ToolDef::new("moving", "identical metadata", json!({"type": "object"})),
epoch: std::sync::atomic::AtomicU64::new(0),
mutate_on_resolve: true,
});
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "direct-identical-replacement",
name: "moving",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
assert!(matches!(
crate::resolve_tool_execution_plan_fenced(
&dispatcher,
call,
&ToolDispatchContext::default(),
&resolution,
),
Err(ToolExecutionResolutionError::Unavailable {
reason: ToolUnavailableReason::ExecutionOwnerChanged,
..
})
));
}
#[test]
fn filtered_wrapper_composes_inner_live_binding_epoch() {
use crate::{
ToolDeadlineChain, ToolDeadlineContributor, ToolDeadlineOwner,
ToolExecutionResolutionContext, ToolExecutionResolutionError, ToolUnavailableReason,
};
use std::time::Duration;
let dispatcher: Arc<dyn AgentToolDispatcher> = Arc::new(FilteredToolDispatcher::new(
Arc::new(IdenticalMutationDispatcher {
tool: ToolDef::new("moving", "identical metadata", json!({"type": "object"})),
epoch: std::sync::atomic::AtomicU64::new(0),
mutate_on_resolve: true,
}),
["moving"],
));
let args = serde_json::value::RawValue::from_string("{}".to_string()).unwrap();
let call = ToolCallView {
id: "filtered-identical-replacement",
name: "moving",
args: &args,
};
let resolution = ToolExecutionResolutionContext::new(
ToolDeadlineChain::new(vec![ToolDeadlineContributor::finite(
ToolDeadlineOwner::CoreToolDispatch,
Duration::from_secs(600),
)])
.unwrap(),
);
assert!(matches!(
crate::resolve_tool_execution_plan_fenced(
&dispatcher,
call,
&ToolDispatchContext::default(),
&resolution,
),
Err(ToolExecutionResolutionError::Unavailable {
reason: ToolUnavailableReason::ExecutionOwnerChanged,
..
})
));
}
#[test]
fn test_inline_peer_notification_policy_from_raw() {
assert_eq!(
InlinePeerNotificationPolicy::try_from_raw(None),
Ok(InlinePeerNotificationPolicy::AtMost(
DEFAULT_MAX_INLINE_PEER_NOTIFICATIONS
))
);
assert_eq!(
InlinePeerNotificationPolicy::try_from_raw(Some(-1)),
Ok(InlinePeerNotificationPolicy::Always)
);
assert_eq!(
InlinePeerNotificationPolicy::try_from_raw(Some(0)),
Ok(InlinePeerNotificationPolicy::Never)
);
assert_eq!(
InlinePeerNotificationPolicy::try_from_raw(Some(25)),
Ok(InlinePeerNotificationPolicy::AtMost(25))
);
assert_eq!(
InlinePeerNotificationPolicy::try_from_raw(Some(-42)),
Err(-42)
);
}
/// UNIT-002: DetachedOpCompletion serializes without operation_id.
/// The app-facing control noun is job_id (CONTRACT-003).
#[test]
fn unit_002_detached_op_completion_has_no_operation_id() {
use crate::agent::DetachedOpCompletion;
use crate::ops_lifecycle::{OperationKind, OperationStatus};
let completion = DetachedOpCompletion {
job_id: "j_test".into(),
kind: OperationKind::BackgroundToolOp,
status: OperationStatus::Completed,
terminal_outcome: None,
display_name: "test cmd".into(),
detail: "ok".into(),
elapsed_ms: None,
};
#[allow(clippy::unwrap_used)]
let json = serde_json::to_value(&completion).unwrap();
assert!(
json.get("operation_id").is_none(),
"operation_id must not appear in serialized DetachedOpCompletion (CONTRACT-003)"
);
assert!(
json.get("job_id").is_some(),
"job_id must be the app-facing control noun"
);
}
}