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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
"""
MACPRunner β€” executor of Multi-Agent Communication Protocol.

Supports both simple sequential execution and adaptive mode
with conditional edges, pruning, fallback, and parallel execution.

Also supports:
- Stratified memory (working/long-term)
- Hidden channels (hidden_state, embeddings)
- Exchange protocol separating visible/hidden data
- Typed errors and handling policies
- Token/request budgets at graph and node levels
- Structured execution event logging
- **Multi-model**: each agent can use its own LLM

Multi-model support:
    MACPRunner supports three ways to specify LLMs:

    1. A single llm_caller for all agents (legacy)
    2. A dict of llm_callers: dict[agent_id, Callable] for different models
    3. LLMCallerFactory that creates callers based on AgentLLMConfig

    Priority: agent-specific caller > factory > default caller
"""

import asyncio
import time
import uuid
from collections import deque
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from datetime import UTC, datetime
from typing import Any, NamedTuple

import torch
from pydantic import BaseModel, ConfigDict, Field

from callbacks import (
    CallbackManager,
    Handler,
    get_callback_manager,
)
from core.agent import AgentLLMConfig
from utils.memory import AgentMemory, MemoryConfig, SharedMemoryPool

from .budget import BudgetConfig, BudgetTracker
from .errors import (
    ErrorPolicy,
    ExecutionError,
    ExecutionMetrics,
)
from .scheduler import (
    AdaptiveScheduler,
    ConditionContext,
    ExecutionPlan,
    PruningConfig,
    RoutingPolicy,
    StepResult,
    build_execution_order,
    extract_agent_adjacency,
    filter_reachable_agents,
    get_incoming_agents,
    get_parallel_groups,
)
from .streaming import (
    AgentErrorEvent,
    AgentOutputEvent,
    AgentStartEvent,
    AnyStreamEvent,
    AsyncStreamCallback,
    FallbackEvent,
    ParallelEndEvent,
    ParallelStartEvent,
    PruneEvent,
    RunEndEvent,
    RunStartEvent,
    StreamCallback,
    StreamEvent,
    StreamEventType,
    TokenEvent,
    TopologyChangedEvent,
)

# Tools support (optional import)
try:
    from tools import ToolRegistry

    TOOLS_AVAILABLE = True
except ImportError:
    TOOLS_AVAILABLE = False

# ---------------------------------------------------------------------------
# Module-level constants
# ---------------------------------------------------------------------------
#: Minimum edge weight below which the edge is considered absent (BFS).
_MIN_EDGE_WEIGHT: float = 1e-6

__all__ = [
    "AgentMemory",
    "AsyncStreamCallback",
    "AsyncStructuredLLMCallerProtocol",
    "AsyncTopologyHook",
    "BudgetConfig",
    "EarlyStopCondition",
    "ErrorPolicy",
    "ExecutionMetrics",
    "HiddenState",
    # Multi-model support
    "LLMCallerFactory",
    "LLMCallerProtocol",
    "MACPResult",
    "MACPRunner",
    "MemoryConfig",
    "RunnerConfig",
    "SharedMemoryPool",
    # Dynamic topology
    "StepContext",
    "StreamCallback",
    # Streaming types
    "StreamEvent",
    "StreamEventType",
    # Structured prompt support
    "StructuredLLMCallerProtocol",
    "StructuredPrompt",
    "ToolRegistry",
    "TopologyAction",
    "TopologyHook",
    "create_openai_async_structured_caller",
    "create_openai_caller",
    "create_openai_structured_caller",
]


# Type aliases for LLM callers
LLMCallerProtocol = Callable[[str], str]
AsyncLLMCallerProtocol = Callable[[str], Awaitable[str]]

# Structured prompt: allows callers to receive proper system/user roles
# instead of a flat string.  This is the modern way to call chat LLMs.
StructuredLLMCallerProtocol = Callable[[list[dict[str, str]]], str]
AsyncStructuredLLMCallerProtocol = Callable[[list[dict[str, str]]], Awaitable[str]]


class StructuredPrompt:
    """
    Prompt that carries both a flat string (legacy) and structured messages.

    When a ``structured_llm_caller`` is available the runner sends
    ``messages`` (a list of ``{"role": ..., "content": ...}`` dicts)
    so the LLM receives proper system / user roles.  Otherwise the
    runner falls back to the flat ``text`` representation β€” full
    backward compatibility with ``Callable[[str], str]`` callers.
    """

    __slots__ = ("messages", "text")

    def __init__(self, text: str, messages: list[dict[str, str]]) -> None:
        self.text = text
        self.messages = messages

    # Allow `len()`, logging, and anywhere a plain str was expected
    def __str__(self) -> str:
        return self.text

    def __repr__(self) -> str:
        return f"StructuredPrompt(text='{self.text[:80]}…', messages={len(self.messages)})"


class LLMCallerFactory:
    """
    Factory for creating LLM callers based on agent configuration.

    Supports:
    - OpenAI-compatible APIs (OpenAI, Azure, Ollama, vLLM, LiteLLM)
    - Caching created callers by (base_url, api_key, model_name)
    - Fallback to default caller if configuration is not set

    Example:
        factory = LLMCallerFactory(
            default_caller=my_default_caller,
            default_config=LLMConfig(model_name="gpt-4", base_url="...")
        )

        # Automatically creates a caller for the agent
        caller = factory.get_caller(agent.get_llm_config())
        response = caller(prompt)

        # Or with OpenAI
        factory = LLMCallerFactory.create_openai_factory(
            default_api_key="sk-...",
            default_model="gpt-4"
        )

    """

    def __init__(
        self,
        default_caller: LLMCallerProtocol | None = None,
        default_async_caller: AsyncLLMCallerProtocol | None = None,
        default_config: AgentLLMConfig | None = None,
        caller_builder: Callable[[AgentLLMConfig], LLMCallerProtocol] | None = None,
        async_caller_builder: Callable[[AgentLLMConfig], AsyncLLMCallerProtocol] | None = None,
    ):
        """
        Create an LLM caller factory.

        Args:
            default_caller: Default caller (for agents without custom configuration).
            default_async_caller: Default async caller.
            default_config: Default configuration (merged with agent config).
            caller_builder: Function for creating a sync caller from configuration.
            async_caller_builder: Function for creating an async caller from configuration.

        """
        self.default_caller = default_caller
        self.default_async_caller = default_async_caller
        self.default_config = default_config
        self.caller_builder = caller_builder
        self.async_caller_builder = async_caller_builder

        # Cache callers by config hash
        self._caller_cache: dict[str, LLMCallerProtocol] = {}
        self._async_caller_cache: dict[str, AsyncLLMCallerProtocol] = {}

    def _config_key(self, config: AgentLLMConfig) -> str:
        """Create a cache key for the configuration."""
        return f"{config.base_url}|{config.model_name}|{config.api_key}"

    def _merge_config(self, config: AgentLLMConfig) -> AgentLLMConfig:
        """Merge the agent configuration with the default configuration."""
        if not self.default_config:
            return config
        return AgentLLMConfig(
            model_name=config.model_name or self.default_config.model_name,
            base_url=config.base_url or self.default_config.base_url,
            api_key=config.api_key or self.default_config.api_key,
            max_tokens=config.max_tokens if config.max_tokens is not None else self.default_config.max_tokens,
            temperature=config.temperature if config.temperature is not None else self.default_config.temperature,
            timeout=config.timeout if config.timeout is not None else self.default_config.timeout,
            top_p=config.top_p if config.top_p is not None else self.default_config.top_p,
            stop_sequences=config.stop_sequences or self.default_config.stop_sequences,
            extra_params={**self.default_config.extra_params, **config.extra_params},
        )

    def get_caller(
        self,
        config: AgentLLMConfig | None = None,
        _agent_id: str | None = None,
    ) -> LLMCallerProtocol | None:
        """
        Get sync caller for the given configuration.

        Args:
            config: Agent LLM configuration.
            _agent_id: Agent ID (reserved for future use).

        Returns:
            LLM caller or None if creation failed.

        """
        if config is None or not config.is_configured():
            return self.default_caller

        config = self._merge_config(config)

        cache_key = self._config_key(config)

        if cache_key in self._caller_cache:
            return self._caller_cache[cache_key]

        if self.caller_builder:
            caller = self.caller_builder(config)
            self._caller_cache[cache_key] = caller
            return caller

        return self.default_caller

    def get_async_caller(
        self,
        config: AgentLLMConfig | None = None,
        _agent_id: str | None = None,
    ) -> AsyncLLMCallerProtocol | None:
        """Get async caller for the given configuration."""
        if config is None or not config.is_configured():
            return self.default_async_caller

        config = self._merge_config(config)

        cache_key = self._config_key(config)

        if cache_key in self._async_caller_cache:
            return self._async_caller_cache[cache_key]

        if self.async_caller_builder:
            caller = self.async_caller_builder(config)
            self._async_caller_cache[cache_key] = caller
            return caller

        return self.default_async_caller

    @classmethod
    def create_openai_factory(
        cls,
        default_api_key: str | None = None,
        default_model: str = "gpt-4",
        default_base_url: str = "https://api.openai.com/v1",
        default_temperature: float = 0.7,
        default_max_tokens: int = 2000,
    ) -> "LLMCallerFactory":
        """
        Create a factory for OpenAI-compatible APIs.

        Automatically creates callers using the openai library.

        Args:
            default_api_key: Default API key (or $OPENAI_API_KEY).
            default_model: Default model name.
            default_base_url: Default API URL.
            default_temperature: Default temperature.
            default_max_tokens: Default maximum tokens.

        Example:
            factory = LLMCallerFactory.create_openai_factory(
                default_api_key="$OPENAI_API_KEY"
            )
            runner = MACPRunner(llm_factory=factory)

        """
        import os

        # Resolve default API key
        if default_api_key and default_api_key.startswith("$"):
            default_api_key = os.environ.get(default_api_key[1:])

        default_config = AgentLLMConfig(
            model_name=default_model,
            base_url=default_base_url,
            api_key=default_api_key,
            temperature=default_temperature,
            max_tokens=default_max_tokens,
        )

        def build_sync_caller(config: AgentLLMConfig) -> LLMCallerProtocol:
            return _create_openai_caller_from_config(config)

        def build_async_caller(config: AgentLLMConfig) -> AsyncLLMCallerProtocol:
            return _create_async_openai_caller_from_config(config)

        return cls(
            default_config=default_config,
            caller_builder=build_sync_caller,
            async_caller_builder=build_async_caller,
        )


def _create_openai_caller_from_config(config: AgentLLMConfig) -> LLMCallerProtocol:
    """Create an OpenAI-compatible sync caller from configuration."""
    try:
        from openai import OpenAI
    except ImportError as e:
        msg = "openai package required. Install with: pip install openai"
        raise ImportError(msg) from e

    api_key = config.resolve_api_key()
    client = OpenAI(
        api_key=api_key,
        base_url=config.base_url,
        timeout=config.timeout or 60.0,
    )

    gen_params = config.to_generation_params()
    model = config.model_name or "gpt-4"

    def caller(prompt: str) -> str:
        response = client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            **gen_params,
        )
        return response.choices[0].message.content or ""

    return caller


def _create_async_openai_caller_from_config(config: AgentLLMConfig) -> AsyncLLMCallerProtocol:
    """Create an OpenAI-compatible async caller from configuration."""
    try:
        from openai import AsyncOpenAI
    except ImportError as e:
        msg = "openai package required. Install with: pip install openai"
        raise ImportError(msg) from e

    api_key = config.resolve_api_key()
    client = AsyncOpenAI(
        api_key=api_key,
        base_url=config.base_url,
        timeout=config.timeout or 60.0,
    )

    gen_params = config.to_generation_params()
    model = config.model_name or "gpt-4"

    async def caller(prompt: str) -> str:
        response = await client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            **gen_params,
        )
        return response.choices[0].message.content or ""

    return caller


def create_openai_caller(
    api_key: str | None = None,
    model: str = "gpt-4",
    base_url: str = "https://api.openai.com/v1",
    temperature: float = 0.7,
    max_tokens: int = 2000,
) -> LLMCallerProtocol:
    """
    Create a simple OpenAI caller (convenience function).

    Returns a ``llm_caller``-compatible callable: ``(str) -> str``.

    Example:
        caller = create_openai_caller(api_key="sk-...", model="gpt-4")
        runner = MACPRunner(llm_caller=caller)

    """
    config = AgentLLMConfig(
        model_name=model,
        base_url=base_url,
        api_key=api_key,
        temperature=temperature,
        max_tokens=max_tokens,
    )
    return _create_openai_caller_from_config(config)


def create_openai_structured_caller(
    api_key: str | None = None,
    model: str = "gpt-4",
    base_url: str = "https://api.openai.com/v1",
    temperature: float = 0.7,
    max_tokens: int = 2000,
) -> StructuredLLMCallerProtocol:
    """
    Create an OpenAI structured caller (recommended for chat LLMs).

    Returns a ``structured_llm_caller``-compatible callable that receives
    a list of ``{"role": ..., "content": ...}`` dicts and returns a string.
    This gives the LLM proper system/user role separation β€” shorter,
    more focused responses and fewer tokens in long chains.

    Example:
        caller = create_openai_structured_caller(api_key="sk-...", model="gpt-4o")
        runner = MACPRunner(structured_llm_caller=caller)

    """
    try:
        from openai import OpenAI
    except ImportError as e:
        msg = "openai package required. Install with: pip install openai"
        raise ImportError(msg) from e

    client = OpenAI(api_key=api_key, base_url=base_url)

    def caller(messages: list[dict[str, str]]) -> str:
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            max_tokens=max_tokens,
        )
        return response.choices[0].message.content or ""

    return caller


def create_openai_async_structured_caller(
    api_key: str | None = None,
    model: str = "gpt-4",
    base_url: str = "https://api.openai.com/v1",
    temperature: float = 0.7,
    max_tokens: int = 2000,
) -> AsyncStructuredLLMCallerProtocol:
    """
    Create an async OpenAI structured caller.

    Returns an ``async_structured_llm_caller``-compatible callable.
    Required for parallel execution via ``astream()`` with
    ``enable_parallel=True``.

    Example:
        sync_caller = create_openai_structured_caller(api_key="sk-...")
        async_caller = create_openai_async_structured_caller(api_key="sk-...")
        runner = MACPRunner(
            structured_llm_caller=sync_caller,
            async_structured_llm_caller=async_caller,
            config=RunnerConfig(enable_parallel=True),
        )

        # Sequential topologies β€” use stream()
        for event in runner.stream(graph):
            ...

        # Parallel topologies β€” use astream()
        async for event in runner.astream(graph):
            ...

    """
    try:
        from openai import AsyncOpenAI
    except ImportError as e:
        msg = "openai package required. Install with: pip install openai"
        raise ImportError(msg) from e

    client = AsyncOpenAI(api_key=api_key, base_url=base_url)

    async def caller(messages: list[dict[str, str]]) -> str:
        response = await client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            max_tokens=max_tokens,
        )
        return response.choices[0].message.content or ""

    return caller


class HiddenState(BaseModel):
    """Agent hidden state/embeddings passed via hidden channels."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

    tensor: torch.Tensor | None = None
    embedding: torch.Tensor | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)


# =============================================================================
# DYNAMIC TOPOLOGY (runtime graph modification)
# =============================================================================


class StepContext(BaseModel):
    """
    Context of the current execution step for making graph modification decisions.

    Passed to hooks for dynamic topology modification at runtime.

    Attributes:
        agent_id: ID of the current agent.
        response: Agent response (if already received).
        messages: All agent responses so far.
        step_result: Result of the current step.
        execution_order: Execution order up to the current moment.
        remaining_agents: Agents that have not yet been executed.
        query: Original query.
        total_tokens: Tokens used.
        metadata: Arbitrary metadata.

    """

    model_config = ConfigDict(arbitrary_types_allowed=True)

    agent_id: str
    response: str | None = None
    messages: dict[str, str] = Field(default_factory=dict)
    step_result: StepResult | None = None
    execution_order: list[str] = Field(default_factory=list)
    remaining_agents: list[str] = Field(default_factory=list)
    query: str = ""
    total_tokens: int = 0
    metadata: dict[str, Any] = Field(default_factory=dict)


class TopologyAction(BaseModel):
    """
    Action for modifying the graph/plan topology at runtime.

    Returned from hooks for dynamic graph and ExecutionPlan modification.

    Supports two levels of modification:
    - Graph (add_edges, remove_edges) β€” for non-adaptive mode.
    - Plan (skip_agents, force_agents, condition_skip/unskip) β€” for adaptive mode.
    """

    # Early stopping
    early_stop: bool = False
    early_stop_reason: str | None = None

    # Adding/removing edges (graph modification)
    add_edges: list[tuple[str, str, float]] = Field(default_factory=list)  # (src, tgt, weight)
    remove_edges: list[tuple[str, str]] = Field(default_factory=list)

    # Skip agents (skipped β€” permanently excluded from the plan)
    skip_agents: list[str] = Field(default_factory=list)

    # Force agent execution (even if not in the plan β€” added to the plan)
    force_agents: list[str] = Field(default_factory=list)

    # Conditional skip (condition_skipped β€” can be restored when conditions change)
    condition_skip_agents: list[str] = Field(default_factory=list)
    condition_unskip_agents: list[str] = Field(default_factory=list)

    # Add agents to the plan with their unconditional chains
    insert_chains: list[tuple[str, str]] = Field(default_factory=list)

    # Change the end agent
    new_end_agent: str | None = None

    # Reserved for future use
    trigger_rebuild: bool = False


# Type aliases for hooks
TopologyHook = Callable[[StepContext, Any], TopologyAction | None]
AsyncTopologyHook = Callable[[StepContext, Any], Awaitable[TopologyAction | None]]


class EarlyStopCondition:
    """
    Condition for early stopping of execution.

    Allows stopping graph execution based on an arbitrary condition.
    The condition is any function (ctx: StepContext) -> bool.

    Attributes:
        condition: Condition evaluation function.
        reason: Stop reason (for logging/debugging).
        after_agents: List of agents after which to check the condition.
        min_agents_executed: Minimum number of agents that must execute before checking.

    Example:
        # Arbitrary condition β€” any logic
        stop_condition = EarlyStopCondition(
            condition=lambda ctx: my_complex_check(ctx.messages, ctx.metadata),
            reason="Custom condition met"
        )

        # Condition based on metrics
        stop_condition = EarlyStopCondition(
            condition=lambda ctx: ctx.metadata.get("quality_score", 0) > 0.9,
            reason="Quality threshold reached"
        )

        # Stop after reaching a token limit
        stop_condition = EarlyStopCondition(
            condition=lambda ctx: ctx.total_tokens > 5000,
            reason="Token limit reached"
        )

        runner = MACPRunner(
            llm_caller=my_llm,
            config=RunnerConfig(early_stop_conditions=[stop_condition])
        )

    """

    def __init__(
        self,
        condition: Callable[[StepContext], bool],
        reason: str = "Early stop condition met",
        after_agents: list[str] | None = None,
        min_agents_executed: int = 0,
    ):
        """
        Create an early stop condition.

        Args:
            condition: Arbitrary condition function (ctx -> bool).
            reason: Stop reason (for logging).
            after_agents: List of agents after which to check the condition
                         (if None β€” check after every agent).
            min_agents_executed: Minimum number of agents that must execute
                                before checking the condition.

        """
        self.condition = condition
        self.reason = reason
        self.after_agents = after_agents
        self.min_agents_executed = min_agents_executed

    def should_stop(self, ctx: StepContext) -> tuple[bool, str]:
        """Check whether execution should stop."""
        # Check minimum number of executed agents
        if len(ctx.execution_order) < self.min_agents_executed:
            return False, ""

        # Check whether the current agent matches
        if self.after_agents and ctx.agent_id not in self.after_agents:
            return False, ""

        try:
            if self.condition(ctx):
                return True, self.reason
        except (ValueError, TypeError, KeyError, AttributeError, RuntimeError):
            # Condition evaluation failed, treat as not met
            return False, ""

        return False, ""

    # =========================================================================
    # FACTORY METHODS for common conditions
    # =========================================================================

    @classmethod
    def on_keyword(
        cls,
        keyword: str,
        reason: str | None = None,
        *,
        case_sensitive: bool = False,
        in_last_response: bool = True,
    ) -> "EarlyStopCondition":
        """
        Stop if the response contains a keyword.

        Args:
            keyword: Keyword to search for.
            reason: Stop reason.
            case_sensitive: Whether to perform a case-sensitive match.
            in_last_response: Search only in the last response (otherwise in all).

        Example:
            stop = EarlyStopCondition.on_keyword("FINAL ANSWER")

        """

        def check(ctx: StepContext) -> bool:
            text = ctx.response or "" if in_last_response else " ".join(ctx.messages.values())

            if case_sensitive:
                return keyword in text
            return keyword.lower() in text.lower()

        return cls(condition=check, reason=reason or f"Keyword '{keyword}' found")

    @classmethod
    def on_token_limit(
        cls,
        max_tokens: int,
        reason: str | None = None,
    ) -> "EarlyStopCondition":
        """
        Stop when the token limit is reached.

        Args:
            max_tokens: Maximum number of tokens.
            reason: Stop reason.

        Example:
            stop = EarlyStopCondition.on_token_limit(5000)

        """
        return cls(
            condition=lambda ctx: ctx.total_tokens >= max_tokens,
            reason=reason or f"Token limit {max_tokens} reached",
        )

    @classmethod
    def on_agent_count(
        cls,
        max_agents: int,
        reason: str | None = None,
    ) -> "EarlyStopCondition":
        """
        Stop after N agents have been executed.

        Args:
            max_agents: Maximum number of agents.
            reason: Stop reason.

        Example:
            stop = EarlyStopCondition.on_agent_count(3)

        """
        return cls(
            condition=lambda ctx: len(ctx.execution_order) >= max_agents,
            reason=reason or f"Agent count limit {max_agents} reached",
        )

    @classmethod
    def on_metadata(
        cls,
        key: str,
        value: Any = None,
        comparator: Callable[[Any, Any], bool] | None = None,
        reason: str | None = None,
    ) -> "EarlyStopCondition":
        """
        Stop based on a value in metadata.

        Args:
            key: Key in metadata.
            value: Expected value (if None β€” only presence is checked).
            comparator: Comparison function (default: ==).
            reason: Stop reason.

        Example:
            # Stop if quality > 0.9
            stop = EarlyStopCondition.on_metadata(
                "quality", 0.9,
                comparator=lambda v, threshold: v > threshold
            )

        """

        def check(ctx: StepContext) -> bool:
            if key not in ctx.metadata:
                return False
            actual = ctx.metadata[key]
            if value is None:
                return True
            if comparator:
                return comparator(actual, value)
            return actual == value

        return cls(condition=check, reason=reason or f"Metadata condition met: {key}")

    @classmethod
    def on_custom(
        cls,
        condition: Callable[[StepContext], bool],
        reason: str = "Custom condition met",
        **kwargs,
    ) -> "EarlyStopCondition":
        """
        Create a condition with an arbitrary function (constructor alias).

        Args:
            condition: Arbitrary evaluation function.
            reason: Stop reason.
            **kwargs: Additional parameters (after_agents, min_agents_executed).

        Example:
            stop = EarlyStopCondition.on_custom(
                lambda ctx: my_rl_agent.should_stop(ctx.messages),
                reason="RL agent decided to stop"
            )

        """
        return cls(condition=condition, reason=reason, **kwargs)

    @classmethod
    def combine_any(
        cls,
        conditions: list["EarlyStopCondition"],
        reason: str = "One of conditions met",
    ) -> "EarlyStopCondition":
        """
        Combine conditions with OR (stop if at least one is met).

        Args:
            conditions: List of conditions.
            reason: Stop reason.

        Example:
            stop = EarlyStopCondition.combine_any([
                EarlyStopCondition.on_keyword("DONE"),
                EarlyStopCondition.on_token_limit(10000),
            ])

        """

        def check(ctx: StepContext) -> bool:
            for cond in conditions:
                should_stop, _ = cond.should_stop(ctx)
                if should_stop:
                    return True
            return False

        return cls(condition=check, reason=reason)

    @classmethod
    def combine_all(
        cls,
        conditions: list["EarlyStopCondition"],
        reason: str = "All conditions met",
    ) -> "EarlyStopCondition":
        """
        Combine conditions with AND (stop if all are met).

        Args:
            conditions: List of conditions.
            reason: Stop reason.

        Example:
            stop = EarlyStopCondition.combine_all([
                EarlyStopCondition.on_keyword("answer"),
                EarlyStopCondition.on_metadata("confidence", 0.8, lambda v, t: v > t),
            ])

        """

        def check(ctx: StepContext) -> bool:
            for cond in conditions:
                should_stop, _ = cond.should_stop(ctx)
                if not should_stop:
                    return False
            return True

        return cls(condition=check, reason=reason)


class MACPResult(NamedTuple):
    """MACP execution result with messages, metrics, and states."""

    messages: dict[str, str]
    final_answer: str
    final_agent_id: str
    execution_order: list[str]
    agent_states: dict[str, list[dict[str, Any]]] | None = None
    step_results: dict[str, StepResult] | None = None
    total_tokens: int = 0
    total_time: float = 0.0
    topology_changed_count: int = 0
    fallback_count: int = 0
    pruned_agents: list[str] | None = None
    errors: list[ExecutionError] | None = None
    hidden_states: dict[str, HiddenState] | None = None
    metrics: ExecutionMetrics | None = None
    budget_summary: dict[str, Any] | None = None
    # Dynamic topology
    early_stopped: bool = False
    early_stop_reason: str | None = None
    topology_modifications: int = 0  # Number of topology modifications


class ExecutionContext(NamedTuple):
    """
    Common initialization context for all execution methods.

    Assembled by ``MACPRunner._prepare_base_context`` and contains
    parsed graph data: indices, agent identifiers, and lookups.
    """

    task_idx: int
    a_agents: Any  # torch.Tensor adjacency matrix
    agent_ids: list[str]
    query: str
    agent_lookup: dict[str, Any]
    agent_names: dict[str, str]


class RunnerConfig(BaseModel):
    """Runner configuration: timeouts, adaptivity, parallelism, budgets, and logging."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

    timeout: float = 60.0
    adaptive: bool = False
    enable_parallel: bool = True
    max_parallel_size: int = 5
    max_retries: int = 2
    retry_delay: float = 1.0
    retry_backoff: float = 2.0
    update_states: bool = True

    routing_policy: RoutingPolicy = RoutingPolicy.TOPOLOGICAL
    pruning_config: PruningConfig | None = None

    enable_hidden_channels: bool = False
    hidden_combine_strategy: str = "mean"
    pass_embeddings: bool = True

    error_policy: ErrorPolicy = Field(default_factory=ErrorPolicy)

    budget_config: BudgetConfig | None = None

    callbacks: list[Handler] = Field(default_factory=list)

    # Memory integration
    enable_memory: bool = False
    memory_config: MemoryConfig | None = None
    memory_context_limit: int = 5  # number of memory entries to include in the prompt

    # Streaming configuration
    enable_token_streaming: bool = False  # Enable token-level streaming if LLM supports it
    stream_callbacks: list[StreamCallback] = Field(default_factory=list)
    async_stream_callbacks: list[AsyncStreamCallback] = Field(default_factory=list)
    prompt_preview_length: int = 100  # How many chars of prompt to include in events

    # Task query broadcast mode
    broadcast_task_to_all: bool = True  # True: task query is broadcast to all agents
    # False: only to agents directly connected to the task node

    # Dynamic topology (graph modification at runtime)
    enable_dynamic_topology: bool = False  # Enable dynamic topology support
    topology_hooks: list[Any] = Field(default_factory=list)  # TopologyHook callbacks
    async_topology_hooks: list[Any] = Field(default_factory=list)  # AsyncTopologyHook callbacks
    early_stop_conditions: list[Any] = Field(default_factory=list)  # EarlyStopCondition list

    # Tools support - if an agent has tools, they are used AUTOMATICALLY
    max_tool_iterations: int = 3  # Maximum tool calling iterations per agent
    tool_registry: Any | None = None  # ToolRegistry (optional, can use global registry)


class MACPRunner:
    """
    MACP protocol executor for RoleGraph with sync/async and adaptive mode.

    Supports three execution modes:
    - Batch: run_round() / arun_round() - returns complete result
    - Streaming: stream() / astream() - yields events during execution

    Multi-model support:
        Each agent can use its own LLM. Three ways to specify models:

        1. A single llm_caller for all agents (legacy)
        2. llm_callers: dict[agent_id, Callable] β€” different models for different agents
        3. llm_factory: LLMCallerFactory β€” dynamic caller creation

        Priority: llm_callers[agent_id] > factory > default llm_caller

    Streaming Example:
        runner = MACPRunner(llm_caller=my_llm)

        # Sync streaming
        for event in runner.stream(graph):
            if event.event_type == StreamEventType.AGENT_OUTPUT:
                print(f"{event.agent_id}: {event.content}")

        # Async streaming
        async for event in runner.astream(graph):
            print(event)

    Multi-model Example:
        # Option 1: Different callers for different agents
        runner = MACPRunner(
            llm_caller=default_caller,
            llm_callers={
                "solver": gpt4_caller,
                "reviewer": claude_caller,
                "analyzer": local_llama_caller,
            }
        )

        # Option 2: Factory (automatically creates callers from agent LLM configurations)
        factory = LLMCallerFactory.create_openai_factory(default_api_key="...")
        runner = MACPRunner(llm_factory=factory)

        # Agents with llm_config will automatically receive their callers:
        builder.add_agent("solver", llm_backbone="gpt-4", temperature=0.7)
        builder.add_agent("analyzer", llm_backbone="gpt-4o-mini", temperature=0.0)

    Structured Prompt (recommended for modern chat LLMs):
        Instead of the legacy ``llm_caller(str) -> str`` interface, use
        ``structured_llm_caller`` to send proper system/user roles to the LLM.
        This avoids the "prompt as one string" problem where the model has to
        re-parse a flat blob, and typically results in shorter, more focused
        responses with fewer tokens β€” especially in long agent chains.

        from openai import OpenAI

        client = OpenAI(api_key="sk-...")

        def my_structured_caller(messages: list[dict[str, str]]) -> str:
            resp = client.chat.completions.create(
                model="gpt-4o",
                messages=messages,
                max_tokens=1024,
            )
            return resp.choices[0].message.content or ""

        runner = MACPRunner(structured_llm_caller=my_structured_caller)
        result = runner.run_round(graph)

        # The runner automatically builds StructuredPrompt with:
        #   {"role": "system",    "content": "<persona + description + tools hint + output_schema>"}
        #   {"role": "assistant", "content": "<state[0] assistant turn>"}  # replayed from agent.state
        #   {"role": "user",      "content": "<state[1] user turn>"}       # replayed from agent.state
        #   ...
        #   {"role": "user",      "content": "<task + input_schema hint + memory + incoming messages>"}
        # and passes prompt.messages to your structured_llm_caller.
    """

    def __init__(
        self,
        llm_caller: Callable[[str], str] | None = None,
        async_llm_caller: Callable[[str], Awaitable[str]] | None = None,
        streaming_llm_caller: Callable[[str], Iterator[str]] | None = None,
        async_streaming_llm_caller: Callable[[str], AsyncIterator[str]] | None = None,
        token_counter: Callable[[str], int] | None = None,
        config: RunnerConfig | None = None,
        timeout: int = 60,
        memory_pool: SharedMemoryPool | None = None,
        # Multi-model support
        llm_callers: dict[str, Callable[[str], str]] | None = None,
        async_llm_callers: dict[str, Callable[[str], Awaitable[str]]] | None = None,
        llm_factory: LLMCallerFactory | None = None,
        # Tools support
        tool_registry: Any | None = None,
        # Structured prompt support (modern chat LLMs)
        structured_llm_caller: StructuredLLMCallerProtocol | None = None,
        async_structured_llm_caller: AsyncStructuredLLMCallerProtocol | None = None,
    ):
        """
        Create a MACP runner with multi-model and tools support.

        Args:
            llm_caller: Default synchronous LLM call (returns full response).
            async_llm_caller: Default asynchronous LLM call (returns full response).
            streaming_llm_caller: Synchronous streaming LLM (yields tokens).
            async_streaming_llm_caller: Asynchronous streaming LLM (async yields tokens).
            token_counter: Function to estimate tokens in text.
            config: Runner configuration (otherwise created with the given timeout).
            timeout: Default timeout (seconds), used if not specified in config.
            memory_pool: External SharedMemoryPool (if None β€” created automatically).

            # Multi-model support:
            llm_callers: Dict agent_id -> sync caller. Has highest priority.
            async_llm_callers: Dict agent_id -> async caller.
            llm_factory: Factory for creating callers based on agent LLM configurations.
                        Used if no explicit caller is set in llm_callers for the agent.

            # Tools support:
            tool_registry: Tool registry (ToolRegistry). Optional.
                          If an agent has tools, they are used automatically.

            # Structured prompt support:
            structured_llm_caller: Callable that receives a list of
                ``{"role": "system"|"user", "content": "..."}`` dicts
                and returns a string.  When provided the runner sends
                proper system/user roles to the LLM instead of a flat
                string β€” this typically produces shorter, more focused
                responses and saves tokens in long chains.
            async_structured_llm_caller: Async version of the above.

        Example:
            # Multi-model via caller dictionary
            runner = MACPRunner(
                llm_caller=default_gpt4_caller,
                llm_callers={
                    "analyzer": create_openai_caller(model="gpt-4o-mini"),
                    "expert": create_openai_caller(model="gpt-4-turbo"),
                }
            )

            # Multi-model via factory
            factory = LLMCallerFactory.create_openai_factory()
            runner = MACPRunner(llm_factory=factory)

            # Structured prompt (modern chat LLMs)
            def my_chat(messages: list[dict[str, str]]) -> str:
                return openai_client.chat.completions.create(
                    model="gpt-4", messages=messages
                ).choices[0].message.content

            runner = MACPRunner(structured_llm_caller=my_chat)

        """
        self.structured_llm_caller = structured_llm_caller
        self.async_structured_llm_caller = async_structured_llm_caller

        # When only a structured caller is provided, create a thin
        # str->str wrapper so all existing code paths that check
        # ``self.llm_caller is not None`` keep working.
        if llm_caller is None and structured_llm_caller is not None:
            _sc = structured_llm_caller  # capture for closure

            def _str_wrapper(prompt: str) -> str:
                return _sc([{"role": "user", "content": prompt}])

            llm_caller = _str_wrapper

        self.llm_caller = llm_caller
        self.async_llm_caller = async_llm_caller
        self.streaming_llm_caller = streaming_llm_caller
        self.async_streaming_llm_caller = async_streaming_llm_caller
        self.token_counter = token_counter or self._default_token_counter
        self.config = config or RunnerConfig(timeout=float(timeout))

        # Multi-model support
        self.llm_callers = llm_callers or {}
        self.async_llm_callers = async_llm_callers or {}
        self.llm_factory = llm_factory

        # Tools support
        self.tool_registry = tool_registry

        self._scheduler = (
            AdaptiveScheduler(
                policy=self.config.routing_policy,
                pruning_config=self.config.pruning_config,
            )
            if self.config.adaptive
            else None
        )

        self._callback_manager: CallbackManager | None = None
        self._budget_tracker: BudgetTracker | None = None
        self._metrics: ExecutionMetrics | None = None

        # Memory integration
        self._memory_pool: SharedMemoryPool | None = memory_pool
        self._agent_memories: dict[str, AgentMemory] = {}

    def _init_run(
        self,
        graph_name: str | None = None,  # noqa: ARG002
        num_agents: int = 0,
        query: str = "",
        execution_order: list[str] | None = None,
        callbacks: list[Handler] | None = None,
    ) -> uuid.UUID:
        """Initialize callbacks, budgets and metrics before running. Returns run_id."""
        # Merge config callbacks with per-run callbacks and context callbacks
        all_callbacks = list(self.config.callbacks)
        if callbacks:
            all_callbacks.extend(callbacks)

        # Check for context callback manager
        context_manager = get_callback_manager()
        if context_manager:
            all_callbacks.extend(context_manager.handlers)

        self._callback_manager = CallbackManager.configure(handlers=all_callbacks)

        if self.config.budget_config:
            self._budget_tracker = BudgetTracker(self.config.budget_config)
            self._budget_tracker.start()
        else:
            self._budget_tracker = None

        self._metrics = ExecutionMetrics(
            start_time=datetime.now(tz=UTC),
            total_agents=num_agents,
        )

        return self._callback_manager.on_run_start(
            query=query,
            num_agents=num_agents,
            execution_order=execution_order or [],
        )

    def _prepare_base_context(self, role_graph: Any) -> "ExecutionContext | None":
        """
        Assemble the common initialization context from role_graph.

        Extracts task_idx, adjacency matrix, agent_ids list, query,
        and lookup dictionaries. Does not call ``_init_memory`` β€” each execution
        method does so itself (accounting for possible agent filtering).

        Returns:
            ``ExecutionContext`` with graph data, or ``None`` if there are no agents.

        """
        task_idx = self._get_task_index(role_graph)
        a_agents = extract_agent_adjacency(role_graph.A_com, task_idx)
        agent_ids, _ = self._get_agent_ids(role_graph, task_idx)

        if not agent_ids:
            return None

        query = role_graph.query or ""
        agent_lookup = {a.agent_id: a for a in role_graph.agents}
        agent_names = self._build_agent_names(role_graph)

        return ExecutionContext(
            task_idx=task_idx,
            a_agents=a_agents,
            agent_ids=agent_ids,
            query=query,
            agent_lookup=agent_lookup,
            agent_names=agent_names,
        )

    def _init_memory(self, agent_ids: list[str]) -> None:
        """Initialize memory for agents before execution."""
        if not self.config.enable_memory:
            return

        if self._memory_pool is None:
            self._memory_pool = SharedMemoryPool()

        mem_config = self.config.memory_config or MemoryConfig()

        for agent_id in agent_ids:
            if agent_id not in self._agent_memories:
                memory = AgentMemory(agent_id, mem_config)
                self._agent_memories[agent_id] = memory
                self._memory_pool.register(memory)

    def _get_memory_context(self, agent_id: str) -> list[dict[str, Any]]:
        """Get the latest entries from the agent's memory for context."""
        if not self.config.enable_memory or agent_id not in self._agent_memories:
            return []

        memory = self._agent_memories[agent_id]
        return memory.get_messages(limit=self.config.memory_context_limit)

    def _save_to_memory(
        self,
        agent_id: str,
        response: str,
        incoming_ids: list[str] | None = None,
    ) -> None:
        """Save the agent's response to its memory and share with neighbors."""
        if not self.config.enable_memory or agent_id not in self._agent_memories:
            return

        memory = self._agent_memories[agent_id]
        entry = memory.add_message(role="assistant", content=response)

        # Share with incoming agents (graph neighbors)
        if self._memory_pool and incoming_ids:
            self._memory_pool.share(agent_id, entry, to_agents=incoming_ids)

    def get_agent_memory(self, agent_id: str) -> AgentMemory | None:
        """Get the agent's memory by id (for external access)."""
        return self._agent_memories.get(agent_id)

    @property
    def memory_pool(self) -> SharedMemoryPool | None:
        """Access to the SharedMemoryPool."""
        return self._memory_pool

    # =========================================================================
    # DYNAMIC TOPOLOGY METHODS
    # =========================================================================

    def _check_early_stop(
        self,
        agent_id: str,
        response: str | None,
        messages: dict[str, str],
        execution_order: list[str],
        remaining_agents: list[str],
        query: str,
        total_tokens: int,
    ) -> tuple[bool, str]:
        """
        Check early stop conditions.

        Returns:
            (should_stop, reason)

        """
        if not self.config.early_stop_conditions:
            return False, ""

        ctx = StepContext(
            agent_id=agent_id,
            response=response,
            messages=messages,
            execution_order=execution_order,
            remaining_agents=remaining_agents,
            query=query,
            total_tokens=total_tokens,
        )

        for condition in self.config.early_stop_conditions:
            if isinstance(condition, EarlyStopCondition):
                should_stop, reason = condition.should_stop(ctx)
                if should_stop:
                    return True, reason

        return False, ""

    def _apply_topology_hooks(
        self,
        agent_id: str,
        response: str | None,
        step_result: StepResult | None,
        messages: dict[str, str],
        execution_order: list[str],
        remaining_agents: list[str],
        query: str,
        total_tokens: int,
        role_graph: Any,
    ) -> TopologyAction | None:
        """
        Apply sync topology hooks and collect actions.

        Returns:
            Combined TopologyAction or None.

        """
        if not self.config.enable_dynamic_topology or not self.config.topology_hooks:
            return None

        ctx = StepContext(
            agent_id=agent_id,
            response=response,
            step_result=step_result,
            messages=messages,
            execution_order=execution_order,
            remaining_agents=remaining_agents,
            query=query,
            total_tokens=total_tokens,
        )

        combined_action = TopologyAction()

        for hook in self.config.topology_hooks:
            try:
                action = hook(ctx, role_graph)
                if action is not None:
                    combined_action = self._merge_topology_actions(combined_action, action)
            except (ValueError, TypeError, KeyError, RuntimeError):
                pass  # Ignore hook errors

        if self._has_topology_action(combined_action):
            return combined_action

        return None

    async def _apply_async_topology_hooks(
        self,
        agent_id: str,
        response: str | None,
        step_result: StepResult | None,
        messages: dict[str, str],
        execution_order: list[str],
        remaining_agents: list[str],
        query: str,
        total_tokens: int,
        role_graph: Any,
    ) -> TopologyAction | None:
        """Apply async topology hooks and collect actions."""
        if not self.config.enable_dynamic_topology or not self.config.async_topology_hooks:
            return None

        ctx = StepContext(
            agent_id=agent_id,
            response=response,
            step_result=step_result,
            messages=messages,
            execution_order=execution_order,
            remaining_agents=remaining_agents,
            query=query,
            total_tokens=total_tokens,
        )

        combined_action = TopologyAction()

        for hook in self.config.async_topology_hooks:
            try:
                action = await hook(ctx, role_graph)
                if action is not None:
                    combined_action = self._merge_topology_actions(combined_action, action)
            except (ValueError, TypeError, KeyError, RuntimeError):
                pass  # Ignore async hook errors

        if self._has_topology_action(combined_action):
            return combined_action

        return None

    def _merge_topology_actions(
        self,
        base: TopologyAction,
        new: TopologyAction,
    ) -> TopologyAction:
        """Merge two TopologyAction objects."""
        return TopologyAction(
            early_stop=base.early_stop or new.early_stop,
            early_stop_reason=new.early_stop_reason or base.early_stop_reason,
            add_edges=base.add_edges + new.add_edges,
            remove_edges=base.remove_edges + new.remove_edges,
            skip_agents=list(set(base.skip_agents + new.skip_agents)),
            force_agents=list(set(base.force_agents + new.force_agents)),
            condition_skip_agents=list(set(base.condition_skip_agents + new.condition_skip_agents)),
            condition_unskip_agents=list(set(base.condition_unskip_agents + new.condition_unskip_agents)),
            insert_chains=base.insert_chains + new.insert_chains,
            new_end_agent=new.new_end_agent or base.new_end_agent,
            trigger_rebuild=base.trigger_rebuild or new.trigger_rebuild,
        )

    def _apply_graph_modifications(
        self,
        role_graph: Any,
        action: TopologyAction,
    ) -> int:
        """Apply modifications to the graph and return the number of changes."""
        modifications = 0

        # Remove edges
        for src, tgt in action.remove_edges:
            if role_graph.remove_edge(src, tgt):
                modifications += 1

        # Add edges
        for src, tgt, weight in action.add_edges:
            if role_graph.add_edge(src, tgt, weight):
                modifications += 1

        return modifications

    @staticmethod
    def _has_topology_action(action: TopologyAction) -> bool:
        """Check whether the TopologyAction contains any actions."""
        return bool(
            action.early_stop
            or action.add_edges
            or action.remove_edges
            or action.skip_agents
            or action.force_agents
            or action.condition_skip_agents
            or action.condition_unskip_agents
            or action.insert_chains
            or action.new_end_agent
            or action.trigger_rebuild
        )

    def _build_conditional_edge_action(  # noqa: PLR0912
        self,
        last_agent: str,
        agent_ids: list[str],
        step_results: dict[str, StepResult],
        messages: dict[str, str],
        query: str,
        remaining_ids: set[str],
    ) -> TopologyAction | None:
        """
        Built-in topology hook: evaluate conditional edges and return TopologyAction.

        Checks outgoing conditional edges of the agent and builds an action:
        - condition_skip_agents: agents whose conditions are not met
          (only if there are no other unevaluated incoming conditional edges).
        - condition_unskip_agents + insert_chains: agents whose conditions are met.

        With multiple incoming conditional edges (A→B, C→B):
        - If A→B is not met but C has not yet run — B is NOT skipped.
        - If C→B is met — B is unskipped.
        - B is skipped only if ALL incoming conditional edges have been evaluated and ALL are not met.

        Complexity: O(E_cond) β€” only conditional edges are checked.

        """
        if self._scheduler is None:
            return None

        edge_conditions = self._scheduler._last_edge_conditions  # noqa: SLF001
        if not edge_conditions or not messages:
            return None

        evaluator = self._scheduler.condition_evaluator
        executed_agents = set(step_results.keys())

        skip: list[str] = []
        unskip: list[str] = []
        chains: list[tuple[str, str]] = []

        for (source, target), condition in edge_conditions.items():
            if source != last_agent:
                continue
            if target not in agent_ids:
                continue

            ctx = ConditionContext(
                source_agent=source,
                target_agent=target,
                messages=messages,
                step_results=step_results,
                query=query,
            )

            if evaluator.evaluate(condition, ctx):
                unskip.append(target)
                if target not in remaining_ids:
                    chains.append((target, last_agent))
            elif target in remaining_ids:
                # Skip only if:
                # 1. No other unevaluated incoming conditional edges (waiting for them).
                # 2. No other already-evaluated incoming conditional edge has passed.
                has_pending_incoming = False
                has_passed_incoming = False
                for (src, tgt), cond in edge_conditions.items():
                    if tgt != target or src == source:
                        continue
                    if src not in executed_agents:
                        has_pending_incoming = True
                        break
                    # Source was already executed β€” check its condition
                    other_ctx = ConditionContext(
                        source_agent=src,
                        target_agent=target,
                        messages=messages,
                        step_results=step_results,
                        query=query,
                    )
                    if evaluator.evaluate(cond, other_ctx):
                        has_passed_incoming = True
                        break

                if not has_pending_incoming and not has_passed_incoming:
                    skip.append(target)

        if not skip and not unskip and not chains:
            return None

        return TopologyAction(
            condition_skip_agents=skip,
            condition_unskip_agents=unskip,
            insert_chains=chains,
        )

    def _apply_topology_to_plan(
        self,
        plan: ExecutionPlan,
        action: TopologyAction,
        a_agents: Any,
        agent_ids: list[str],
    ) -> bool:
        """
        Apply a TopologyAction to the ExecutionPlan.

        Single method for modifying the plan from any source:
        user hooks, built-in conditional edge hook, etc.

        Args:
            plan: Current execution plan.
            action: Action to apply.
            a_agents: Adjacency matrix (for BFS chains).
            agent_ids: List of agent IDs.

        Returns:
            True if the plan was modified.

        """
        changed = False
        edge_conditions = self._scheduler._last_edge_conditions if self._scheduler else {}  # noqa: SLF001

        # 1. Condition skip + cascade skip of unconditional descendants
        for agent_id in action.condition_skip_agents:
            plan.condition_skipped.add(agent_id)
            changed = True
            # Cascading condition_skip of unconditional descendants (BFS)
            self._cascade_condition_skip(
                plan,
                agent_id,
                a_agents,
                agent_ids,
                edge_conditions,
            )

        # 2. Condition unskip
        for agent_id in action.condition_unskip_agents:
            plan.condition_skipped.discard(agent_id)
            changed = True

        # 3. Skip (permanent skip)
        remaining_ids = {s.agent_id for s in plan.steps[plan.current_index :]}
        for agent_id in action.skip_agents:
            if agent_id in remaining_ids:
                plan.condition_skipped.add(agent_id)
                changed = True

        # 4. Force agents β€” add to the plan if not already there
        for agent_id in action.force_agents:
            if agent_id not in remaining_ids and agent_id in agent_ids:
                plan.condition_skipped.discard(agent_id)
                added = plan.insert_conditional_step(agent_id=agent_id, predecessors=[])
                if added:
                    remaining_ids.add(agent_id)
                    changed = True

        # 5. Insert chains β€” add the agent + its unconditional chain
        for target, predecessor in action.insert_chains:
            plan.condition_skipped.discard(target)
            if target not in remaining_ids:
                added = plan.insert_conditional_step(
                    agent_id=target,
                    predecessors=[predecessor],
                )
                if added:
                    remaining_ids.add(target)
                    changed = True
                    # BFS β€” add the unconditional chain after target
                    self._insert_unconditional_chain(
                        plan,
                        target,
                        a_agents,
                        agent_ids,
                        edge_conditions,
                        remaining_ids,
                    )
            else:
                changed = True

        return changed

    @staticmethod
    def _cascade_condition_skip(
        plan: ExecutionPlan,
        skipped_agent: str,
        a_agents: Any,
        agent_ids: list[str],
        edge_conditions: dict[tuple[str, str], Any],
    ) -> None:
        """
        BFS: cascading condition_skip of unconditional descendants of skipped_agent.

        If an agent is condition_skipped, its unconditional descendants should also be
        skipped (if they have no other incoming data paths).
        """
        queue = deque([skipped_agent])
        visited = {skipped_agent}
        remaining_ids = {s.agent_id for s in plan.steps[plan.current_index :]}

        while queue:
            current = queue.popleft()
            if current not in agent_ids:
                continue

            current_idx = agent_ids.index(current)
            for j, aid in enumerate(agent_ids):
                if aid in visited or aid not in remaining_ids:
                    continue

                weight = a_agents[current_idx, j]
                if hasattr(weight, "item"):
                    weight = weight.item()
                if weight <= _MIN_EDGE_WEIGHT:
                    continue

                # Skip conditional edges β€” they are handled separately
                if (current, aid) in edge_conditions:
                    continue

                # Check: does aid have other incoming unconditional edges
                # from agents that are NOT condition_skipped?
                has_other_source = False
                for k, src in enumerate(agent_ids):
                    if src == current or src in plan.condition_skipped:
                        continue
                    w = a_agents[k, j]
                    if hasattr(w, "item"):
                        w = w.item()
                    if w > _MIN_EDGE_WEIGHT and (src, aid) not in edge_conditions:
                        has_other_source = True
                        break

                if not has_other_source:
                    visited.add(aid)
                    plan.condition_skipped.add(aid)
                    queue.append(aid)

    @staticmethod
    def _insert_unconditional_chain(
        plan: ExecutionPlan,
        start_agent: str,
        a_agents: Any,
        agent_ids: list[str],
        edge_conditions: dict[tuple[str, str], Any],
        remaining_ids: set[str],
    ) -> None:
        """
        BFS: add a chain of unconditionally linked agents to the plan after start_agent.

        Traverses edges without conditions and adds all subsequent agents to the plan.
        """
        queue = deque([start_agent])
        visited = {start_agent}

        while queue:
            current = queue.popleft()
            if current not in agent_ids:
                continue

            current_idx = agent_ids.index(current)
            for j, aid in enumerate(agent_ids):
                if aid in visited:
                    continue

                weight = a_agents[current_idx, j]
                if hasattr(weight, "item"):
                    weight = weight.item()
                if weight <= _MIN_EDGE_WEIGHT:
                    continue

                # Skip conditional edges β€” they are handled separately
                if (current, aid) in edge_conditions:
                    continue

                visited.add(aid)
                if aid not in remaining_ids:
                    plan.condition_skipped.discard(aid)
                    added = plan.insert_conditional_step(agent_id=aid, predecessors=[current])
                    if added:
                        remaining_ids.add(aid)

                queue.append(aid)

    def _run_topology_pipeline(
        self,
        plan: ExecutionPlan,
        last_agent: str,
        a_agents: Any,
        agent_ids: list[str],
        step_results: dict[str, StepResult],
        messages: dict[str, str],
        query: str,
        execution_order: list[str],
        total_tokens: int,
        role_graph: Any,
    ) -> bool:
        """
        Unified sync pipeline: built-in conditional hook + user hooks β†’ plan.

        Called after each step in adaptive methods.
        Combines all TopologyAction objects and applies them to the plan.

        Returns:
            True if the plan was modified.

        """
        remaining = [s.agent_id for s in plan.remaining_steps]

        # 1. Built-in hook: conditional edges
        remaining_ids = {s.agent_id for s in plan.steps[plan.current_index :]}
        cond_action = self._build_conditional_edge_action(
            last_agent,
            agent_ids,
            step_results,
            messages,
            query,
            remaining_ids,
        )

        # 2. User topology hooks
        user_action = self._apply_topology_hooks(
            last_agent,
            messages.get(last_agent),
            step_results.get(last_agent),
            messages,
            execution_order,
            remaining,
            query,
            total_tokens,
            role_graph,
        )

        # 3. Combine actions
        combined = TopologyAction()
        if cond_action is not None:
            combined = self._merge_topology_actions(combined, cond_action)
        if user_action is not None:
            combined = self._merge_topology_actions(combined, user_action)

        if not self._has_topology_action(combined):
            return False

        # 4. Graph modification (add_edges / remove_edges)
        if combined.add_edges or combined.remove_edges:
            self._apply_graph_modifications(role_graph, combined)

        # 5. Plan modification
        return self._apply_topology_to_plan(plan, combined, a_agents, agent_ids)

    async def _arun_topology_pipeline(
        self,
        plan: ExecutionPlan,
        last_agent: str,
        a_agents: Any,
        agent_ids: list[str],
        step_results: dict[str, StepResult],
        messages: dict[str, str],
        query: str,
        execution_order: list[str],
        total_tokens: int,
        role_graph: Any,
    ) -> bool:
        """
        Unified async pipeline: built-in conditional hook + async user hooks β†’ plan.

        Returns:
            True if the plan was modified.

        """
        remaining = [s.agent_id for s in plan.remaining_steps]

        # 1. Built-in hook: conditional edges (sync β€” fast)
        remaining_ids = {s.agent_id for s in plan.steps[plan.current_index :]}
        cond_action = self._build_conditional_edge_action(
            last_agent,
            agent_ids,
            step_results,
            messages,
            query,
            remaining_ids,
        )

        # 2. User async topology hooks
        user_action = await self._apply_async_topology_hooks(
            last_agent,
            messages.get(last_agent),
            step_results.get(last_agent),
            messages,
            execution_order,
            remaining,
            query,
            total_tokens,
            role_graph,
        )

        # 3. Combine actions
        combined = TopologyAction()
        if cond_action is not None:
            combined = self._merge_topology_actions(combined, cond_action)
        if user_action is not None:
            combined = self._merge_topology_actions(combined, user_action)

        if not self._has_topology_action(combined):
            return False

        # 4. Graph modification
        if combined.add_edges or combined.remove_edges:
            self._apply_graph_modifications(role_graph, combined)

        # 5. Plan modification
        return self._apply_topology_to_plan(plan, combined, a_agents, agent_ids)

    def _finalize_run(
        self,
        run_id: uuid.UUID,
        *,
        success: bool,
        executed_agents: int,
        final_answer: str = "",
        error: BaseException | None = None,
        executed_agent_ids: list[str] | None = None,
    ) -> None:
        """Finalize metrics and notify callbacks after execution."""
        if self._metrics:
            self._metrics.end_time = datetime.now(tz=UTC)
            self._metrics.executed_agents = executed_agents

        if self._callback_manager:
            self._callback_manager.on_run_end(
                run_id=run_id,
                output=final_answer,
                success=success,
                error=error,
                total_tokens=self._metrics.total_tokens if self._metrics else 0,
                total_time_ms=self._metrics.duration_seconds * 1000 if self._metrics else 0,
                executed_agents=executed_agent_ids or [],
            )

    @staticmethod
    def _default_token_counter(text: str) -> int:
        """Simple token estimate: 4/3 of the number of words."""
        return len(text.split()) * 4 // 3

    def _get_caller_for_agent(
        self,
        agent_id: str,
        agent: Any,
    ) -> Callable[[str], str] | None:
        """
        Get sync LLM caller for a specific agent.

        Priority:
        1. llm_callers[agent_id] β€” explicitly specified caller for the agent
        2. llm_factory.get_caller(agent.llm_config) β€” from the factory by configuration
        3. self.llm_caller β€” default caller

        Returns:
            LLM caller or None if none is available.

        """
        # 1. Check explicit per-agent caller
        if agent_id in self.llm_callers:
            return self.llm_callers[agent_id]

        # 2. Try factory if agent has LLM config
        if self.llm_factory and hasattr(agent, "get_llm_config"):
            llm_config = agent.get_llm_config()
            if llm_config and llm_config.is_configured():
                caller = self.llm_factory.get_caller(llm_config, agent_id)
                if caller:
                    return caller
        elif self.llm_factory and hasattr(agent, "llm_config") and agent.llm_config:
            caller = self.llm_factory.get_caller(agent.llm_config, agent_id)
            if caller:
                return caller

        # 3. Fallback to default caller
        return self.llm_caller

    def _get_async_caller_for_agent(
        self,
        agent_id: str,
        agent: Any,
    ) -> Callable[[str], Awaitable[str]] | None:
        """
        Get async LLM caller for a specific agent.

        Priority:
        1. async_llm_callers[agent_id] β€” explicitly specified async caller
        2. llm_factory.get_async_caller(agent.llm_config) β€” from the factory
        3. self.async_llm_caller β€” default async caller

        Note:
            May return ``None`` even when ``async_structured_llm_caller`` is
            set.  Callers must check ``self.async_structured_llm_caller``
            separately before treating ``None`` as a fatal error β€” see
            :meth:`_acall_llm` which dispatches to the structured path first.

        """
        # 1. Check explicit per-agent async caller
        if agent_id in self.async_llm_callers:
            return self.async_llm_callers[agent_id]

        # 2. Try factory if agent has LLM config
        if self.llm_factory and hasattr(agent, "get_llm_config"):
            llm_config = agent.get_llm_config()
            if llm_config and llm_config.is_configured():
                caller = self.llm_factory.get_async_caller(llm_config, agent_id)
                if caller:
                    return caller
        elif self.llm_factory and hasattr(agent, "llm_config") and agent.llm_config:
            caller = self.llm_factory.get_async_caller(agent.llm_config, agent_id)
            if caller:
                return caller

        # 3. Fallback to default async caller
        return self.async_llm_caller

    # ------------------------------------------------------------------
    # Structured prompt dispatch
    # ------------------------------------------------------------------

    def _call_llm(self, caller: Callable, prompt: StructuredPrompt) -> str:
        """
        Call the LLM using the best available interface.

        If a ``structured_llm_caller`` is registered, sends
        ``prompt.messages`` (proper system/user roles).
        Otherwise falls back to ``caller(prompt.text)`` (flat string).
        """
        if self.structured_llm_caller is not None:
            return self.structured_llm_caller(prompt.messages)
        return caller(prompt.text)

    async def _acall_llm(self, async_caller: Callable | None, prompt: StructuredPrompt) -> str:
        """Async version of :meth:`_call_llm`."""
        if self.async_structured_llm_caller is not None:
            return await self.async_structured_llm_caller(prompt.messages)
        if async_caller is None:
            msg = "No async LLM caller available"
            raise ValueError(msg)
        return await async_caller(prompt.text)

    def _has_any_caller(self) -> bool:
        """Check whether at least one LLM caller is available."""
        return bool(
            self.llm_caller
            or self.llm_callers
            or self.structured_llm_caller
            or (self.llm_factory and (self.llm_factory.default_caller or self.llm_factory.caller_builder))
        )

    def _has_any_async_caller(self) -> bool:
        """Check whether at least one async LLM caller is available."""
        return bool(
            self.async_llm_caller
            or self.async_llm_callers
            or self.async_structured_llm_caller
            or (self.llm_factory and (self.llm_factory.default_async_caller or self.llm_factory.async_caller_builder))
        )

    def run_round(
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        start_agent_id: str | None = None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = False,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Run a synchronous round (simple or adaptive strategy).

        Args:
            role_graph: Role graph to execute.
            final_agent_id: ID of final agent (overrides role_graph.end_node).
            start_agent_id: ID of start agent (overrides role_graph.start_node).
            update_states: Whether to update agent states.
            filter_unreachable: Exclude isolated nodes from execution.
            callbacks: Per-run callback handlers (merged with config.callbacks).

        Returns:
            MACPResult with execution results.

        """
        if not self._has_any_caller():
            msg = "llm_caller, llm_callers, or llm_factory is required for synchronous execution"
            raise ValueError(msg)

        # Get start/end from params or graph
        effective_start = start_agent_id or getattr(role_graph, "start_node", None)
        effective_end = final_agent_id or getattr(role_graph, "end_node", None)

        if self.config.adaptive:
            return self._run_adaptive(
                role_graph,
                effective_end,
                effective_start,
                update_states=update_states,
                filter_unreachable=filter_unreachable,
                callbacks=callbacks,
            )
        return self._run_simple(
            role_graph,
            effective_end,
            effective_start,
            update_states=update_states,
            filter_unreachable=filter_unreachable,
            callbacks=callbacks,
        )

    async def arun_round(
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        start_agent_id: str | None = None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = False,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Run an async round (simple or adaptive strategy).

        Args:
            role_graph: Role graph to execute.
            final_agent_id: ID of final agent (overrides role_graph.end_node).
            start_agent_id: ID of start agent (overrides role_graph.start_node).
            update_states: Whether to update agent states.
            filter_unreachable: Exclude isolated nodes from execution.
            callbacks: Per-run callback handlers (merged with config.callbacks).

        Returns:
            MACPResult with execution results.

        """
        if not self._has_any_async_caller():
            msg = "async_llm_caller, async_llm_callers, or llm_factory is required for async execution"
            raise ValueError(msg)

        # Get start/end from params or graph
        effective_start = start_agent_id or getattr(role_graph, "start_node", None)
        effective_end = final_agent_id or getattr(role_graph, "end_node", None)

        if self.config.adaptive:
            return await self._arun_adaptive(
                role_graph,
                effective_end,
                effective_start,
                update_states=update_states,
                filter_unreachable=filter_unreachable,
                callbacks=callbacks,
            )
        return await self._arun_simple(
            role_graph,
            effective_end,
            effective_start,
            update_states=update_states,
            filter_unreachable=filter_unreachable,
            callbacks=callbacks,
        )

    def _run_simple(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        start_agent_id: str | None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = True,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Sequential execution in topological order without adaptation.

        Supports multi-model: each agent uses its own LLM caller.
        Supports filtering of isolated nodes to save tokens.
        """
        if not self._has_any_caller():
            msg = "llm_caller, llm_callers, or llm_factory is required for synchronous execution"
            raise ValueError(msg)

        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            return MACPResult(messages={}, final_answer="", final_agent_id="", execution_order=[])
        _task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        # Filter isolated nodes
        excluded_agents: list[str] = []
        effective_agent_ids = agent_ids
        effective_a = a_agents

        if filter_unreachable and (start_agent_id is not None or final_agent_id is not None):
            relevant, excluded_agents = filter_reachable_agents(a_agents, agent_ids, start_agent_id, final_agent_id)
            if relevant and len(relevant) < len(agent_ids):
                indices = [agent_ids.index(aid) for aid in relevant]
                indices_t = torch.tensor(indices, dtype=torch.long)
                effective_a = a_agents[indices_t][:, indices_t]
                effective_agent_ids = relevant

        exec_order = build_execution_order(effective_a, effective_agent_ids, role_graph.role_sequence)

        # Initialize memory (with effective agents after filtering)
        self._init_memory(effective_agent_ids)

        # Initialize callbacks
        run_id = self._init_run(
            graph_name=getattr(role_graph, "name", None),
            num_agents=len(effective_agent_ids),
            query=query,
            execution_order=exec_order,
            callbacks=callbacks,
        )

        task_connected = self._get_task_connected_agents(role_graph)

        messages: dict[str, str] = {}
        total_tokens = 0
        actual_exec_order: list[str] = []
        early_stopped = False
        early_stop_reason: str | None = None
        topology_modifications = 0
        skipped_by_hooks: set[str] = set()
        run_error: BaseException | None = None

        # Get disabled nodes from graph
        disabled_nodes: set[str] = getattr(role_graph, "disabled_nodes", set())

        try:
            for step_idx, agent_id in enumerate(exec_order):
                # Check if agent was skipped by hooks
                if agent_id in skipped_by_hooks:
                    continue

                # Check if node is disabled
                if agent_id in disabled_nodes:
                    if agent_id not in excluded_agents:
                        excluded_agents.append(agent_id)
                    continue

                agent = agent_lookup.get(agent_id)
                if agent is None:
                    continue

                incoming_ids = get_incoming_agents(agent_id, effective_a, effective_agent_ids)
                incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}

                include_query = self._should_include_query(agent_id, task_connected)
                memory_context = self._get_memory_context(agent_id)
                prompt = self._build_prompt(
                    agent, query, incoming_messages, agent_names, memory_context, include_query=include_query
                )
                prompt_text = prompt.text

                # Notify callbacks of agent start
                if self._callback_manager:
                    self._callback_manager.on_agent_start(
                        run_id=run_id,
                        agent_id=agent_id,
                        agent_name=agent_names.get(agent_id, agent_id),
                        step_index=step_idx,
                        prompt=prompt_text[: self.config.prompt_preview_length],
                        predecessors=incoming_ids,
                    )

                agent_start_time = time.time()
                try:
                    # Get caller for this specific agent (multi-model support)
                    caller = self._get_caller_for_agent(agent_id, agent)
                    if caller is None:
                        error_msg = f"No LLM caller available for agent {agent_id}"
                        messages[agent_id] = f"[Error: {error_msg}]"
                        actual_exec_order.append(agent_id)
                        if self._callback_manager:
                            self._callback_manager.on_agent_error(
                                run_id=run_id,
                                error=ValueError(error_msg),
                                agent_id=agent_id,
                                error_type="NoCallerError",
                            )
                        continue

                    # Execute LLM caller with tools support
                    response, agent_tokens = self._run_agent_with_tools(
                        caller=caller,
                        prompt=prompt,
                        agent=agent,
                    )

                    agent_duration_ms = (time.time() - agent_start_time) * 1000

                    messages[agent_id] = response
                    total_tokens += agent_tokens
                    self._save_to_memory(agent_id, response, incoming_ids)
                    actual_exec_order.append(agent_id)

                    # Notify callbacks of agent end
                    if self._callback_manager:
                        is_final = agent_id == final_agent_id or (final_agent_id is None and agent_id == exec_order[-1])
                        self._callback_manager.on_agent_end(
                            run_id=run_id,
                            agent_id=agent_id,
                            output=response,
                            agent_name=agent_names.get(agent_id, agent_id),
                            step_index=step_idx,
                            tokens_used=agent_tokens,
                            duration_ms=agent_duration_ms,
                            is_final=is_final,
                        )

                except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                    messages[agent_id] = f"[Error: {e}]"
                    actual_exec_order.append(agent_id)
                    if self._callback_manager:
                        self._callback_manager.on_agent_error(
                            run_id=run_id,
                            error=e,
                            agent_id=agent_id,
                            error_type=type(e).__name__,
                        )

                # Check early stopping
                remaining = [a for a in exec_order if a not in messages and a not in skipped_by_hooks]
                should_stop, reason = self._check_early_stop(
                    agent_id,
                    messages.get(agent_id),
                    messages,
                    actual_exec_order,
                    remaining,
                    query,
                    total_tokens,
                )
                if should_stop:
                    early_stopped = True
                    early_stop_reason = reason
                    break

                # Apply topology hooks
                if self.config.enable_dynamic_topology:
                    action = self._apply_topology_hooks(
                        agent_id,
                        messages.get(agent_id),
                        None,
                        messages,
                        actual_exec_order,
                        remaining,
                        query,
                        total_tokens,
                        role_graph,
                    )
                    if action is not None:
                        if action.early_stop:
                            early_stopped = True
                            early_stop_reason = action.early_stop_reason
                            break
                        if action.skip_agents:
                            skipped_by_hooks.update(action.skip_agents)
                        topology_modifications += self._apply_graph_modifications(role_graph, action)

        except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
            run_error = e

        final_id = self._determine_final_agent(final_agent_id, actual_exec_order, messages)
        final_answer = messages.get(final_id, "")

        # Finalize callbacks
        self._finalize_run(
            run_id=run_id,
            success=run_error is None,
            executed_agents=len(actual_exec_order),
            final_answer=final_answer,
            error=run_error,
            executed_agent_ids=actual_exec_order,
        )

        if run_error:
            raise run_error

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        return MACPResult(
            messages=messages,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            execution_order=actual_exec_order,
            agent_states=agent_states,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            pruned_agents=excluded_agents if excluded_agents else None,
            early_stopped=early_stopped,
            early_stop_reason=early_stop_reason,
            topology_modifications=topology_modifications,
        )

    async def _arun_simple(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        start_agent_id: str | None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = True,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Async sequential execution without adaptation.

        Supports multi-model: each agent uses its own LLM caller.
        Supports filtering of isolated nodes to save tokens.
        """
        if not self._has_any_async_caller():
            msg = "async_llm_caller, async_llm_callers, or llm_factory is required for async execution"
            raise ValueError(msg)

        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            return MACPResult(messages={}, final_answer="", final_agent_id="", execution_order=[])
        _task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        # Filter isolated nodes
        excluded_agents: list[str] = []
        effective_agent_ids = agent_ids
        effective_a = a_agents

        if filter_unreachable and (start_agent_id is not None or final_agent_id is not None):
            relevant, excluded_agents = filter_reachable_agents(a_agents, agent_ids, start_agent_id, final_agent_id)
            if relevant and len(relevant) < len(agent_ids):
                indices = [agent_ids.index(aid) for aid in relevant]
                indices_t = torch.tensor(indices, dtype=torch.long)
                effective_a = a_agents[indices_t][:, indices_t]
                effective_agent_ids = relevant

        exec_order = build_execution_order(effective_a, effective_agent_ids, role_graph.role_sequence)

        # Initialize memory (with effective agents after filtering)
        self._init_memory(effective_agent_ids)

        # Initialize callbacks
        run_id = self._init_run(
            graph_name=getattr(role_graph, "name", None),
            num_agents=len(effective_agent_ids),
            query=query,
            execution_order=exec_order,
            callbacks=callbacks,
        )

        task_connected = self._get_task_connected_agents(role_graph)

        messages: dict[str, str] = {}
        total_tokens = 0
        actual_exec_order: list[str] = []
        early_stopped = False
        early_stop_reason: str | None = None
        topology_modifications = 0
        skipped_by_hooks: set[str] = set()
        run_error: BaseException | None = None

        # Get disabled nodes from graph
        disabled_nodes: set[str] = getattr(role_graph, "disabled_nodes", set())

        try:
            for step_idx, agent_id in enumerate(exec_order):
                # Check if agent was skipped by hooks
                if agent_id in skipped_by_hooks:
                    continue

                # Check if node is disabled
                if agent_id in disabled_nodes:
                    if agent_id not in excluded_agents:
                        excluded_agents.append(agent_id)
                    continue

                agent = agent_lookup.get(agent_id)
                if agent is None:
                    continue

                incoming_ids = get_incoming_agents(agent_id, effective_a, effective_agent_ids)
                incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}

                include_query = self._should_include_query(agent_id, task_connected)
                memory_context = self._get_memory_context(agent_id)
                prompt = self._build_prompt(
                    agent, query, incoming_messages, agent_names, memory_context, include_query=include_query
                )

                # Notify callbacks of agent start
                # prompt is now a StructuredPrompt
                prompt_text = prompt.text

                if self._callback_manager:
                    self._callback_manager.on_agent_start(
                        run_id=run_id,
                        agent_id=agent_id,
                        agent_name=agent_names.get(agent_id, agent_id),
                        step_index=step_idx,
                        prompt=prompt_text[:100],
                        predecessors=incoming_ids,
                    )

                agent_start_time = time.time()
                try:
                    # Get async caller for this specific agent (multi-model support).
                    # When only async_structured_llm_caller is configured,
                    # async_caller may be None β€” _acall_llm handles that.
                    async_caller = self._get_async_caller_for_agent(agent_id, agent)
                    if async_caller is None and self.async_structured_llm_caller is None:
                        error_msg = f"No async LLM caller available for agent {agent_id}"
                        messages[agent_id] = f"[Error: {error_msg}]"
                        actual_exec_order.append(agent_id)
                        if self._callback_manager:
                            self._callback_manager.on_agent_error(
                                run_id=run_id,
                                error=ValueError(error_msg),
                                agent_id=agent_id,
                                error_type="NoCallerError",
                            )
                        continue

                    response = await asyncio.wait_for(
                        self._acall_llm(async_caller, prompt),
                        timeout=self.config.timeout,
                    )
                    agent_tokens = self.token_counter(prompt_text) + self.token_counter(response)
                    agent_duration_ms = (time.time() - agent_start_time) * 1000

                    messages[agent_id] = response
                    total_tokens += agent_tokens
                    self._save_to_memory(agent_id, response, incoming_ids)
                    actual_exec_order.append(agent_id)

                    # Notify callbacks of agent end
                    if self._callback_manager:
                        is_final = agent_id == final_agent_id or (final_agent_id is None and agent_id == exec_order[-1])
                        self._callback_manager.on_agent_end(
                            run_id=run_id,
                            agent_id=agent_id,
                            output=response,
                            agent_name=agent_names.get(agent_id, agent_id),
                            step_index=step_idx,
                            tokens_used=agent_tokens,
                            duration_ms=agent_duration_ms,
                            is_final=is_final,
                        )

                except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                    messages[agent_id] = f"[Error: {e}]"
                    actual_exec_order.append(agent_id)
                    if self._callback_manager:
                        self._callback_manager.on_agent_error(
                            run_id=run_id,
                            error=e,
                            agent_id=agent_id,
                            error_type=type(e).__name__,
                        )

                # Check early stopping
                remaining = [a for a in exec_order if a not in messages and a not in skipped_by_hooks]
                should_stop, reason = self._check_early_stop(
                    agent_id,
                    messages.get(agent_id),
                    messages,
                    actual_exec_order,
                    remaining,
                    query,
                    total_tokens,
                )
                if should_stop:
                    early_stopped = True
                    early_stop_reason = reason
                    break

                # Apply async topology hooks
                if self.config.enable_dynamic_topology:
                    action = await self._apply_async_topology_hooks(
                        agent_id,
                        messages.get(agent_id),
                        None,
                        messages,
                        actual_exec_order,
                        remaining,
                        query,
                        total_tokens,
                        role_graph,
                    )
                    if action is not None:
                        if action.early_stop:
                            early_stopped = True
                            early_stop_reason = action.early_stop_reason
                            break
                        if action.skip_agents:
                            skipped_by_hooks.update(action.skip_agents)
                        topology_modifications += self._apply_graph_modifications(role_graph, action)

        except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
            run_error = e

        final_id = self._determine_final_agent(final_agent_id, actual_exec_order, messages)
        final_answer = messages.get(final_id, "")

        # Finalize callbacks
        self._finalize_run(
            run_id=run_id,
            success=run_error is None,
            executed_agents=len(actual_exec_order),
            final_answer=final_answer,
            error=run_error,
            executed_agent_ids=actual_exec_order,
        )

        if run_error:
            raise run_error

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        return MACPResult(
            messages=messages,
            final_answer=final_answer,
            final_agent_id=final_id,
            execution_order=actual_exec_order,
            agent_states=agent_states,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            pruned_agents=excluded_agents if excluded_agents else None,
            early_stopped=early_stopped,
            early_stop_reason=early_stop_reason,
            topology_modifications=topology_modifications,
        )

    def _run_adaptive(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        start_agent_id: str | None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = True,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Adaptive sync execution with conditional edges and fallback.

        Supports multi-model: each agent uses its own LLM caller.
        Supports filtering of isolated nodes to save tokens.
        Per-call ``callbacks`` are merged with ``RunnerConfig.callbacks``
        and context-manager callbacks (similar to ``_run_simple``).
        """
        if not self._has_any_caller():
            msg = "llm_caller, llm_callers, or llm_factory is required for synchronous execution"
            raise ValueError(msg)
        if self._scheduler is None:
            msg = "Scheduler not initialized for adaptive mode"
            raise ValueError(msg)

        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            return MACPResult(messages={}, final_answer="", final_agent_id="", execution_order=[])
        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        # Initialize memory
        self._init_memory(agent_ids)

        p_matrix = self._extract_p_matrix(role_graph, task_idx)

        # Get conditions from graph for conditional routing
        edge_conditions = self._get_edge_conditions(role_graph)

        # Initial context for conditions
        condition_ctx = ConditionContext(
            source_agent="",
            target_agent="",
            messages={},
            step_results={},
            query=query,
        )

        plan = self._scheduler.build_plan(
            a_agents,
            agent_ids,
            p_matrix,
            start_agent=start_agent_id,
            end_agent=final_agent_id,
            edge_conditions=edge_conditions,
            condition_context=condition_ctx,
            filter_unreachable=filter_unreachable,
        )

        # Initialize callbacks (per-call + config + context-manager)
        run_id = self._init_run(
            graph_name=getattr(role_graph, "name", None),
            num_agents=len(agent_ids),
            query=query,
            execution_order=plan.execution_order,
            callbacks=callbacks,
        )

        messages: dict[str, str] = {}
        step_results: dict[str, StepResult] = {}
        execution_order: list[str] = []
        fallback_attempts: dict[str, int] = {}
        topology_changed_count = 0
        fallback_count = 0
        pruned_agents: list[str] = []
        errors: list[ExecutionError] = []
        step_idx = 0
        run_error: BaseException | None = None

        try:
            while not plan.is_complete:
                step = plan.get_current_step()
                if step is None:
                    break

                # Skip agents whose conditions were not met
                if step.agent_id in plan.condition_skipped:
                    plan.advance()
                    continue

                should_prune, reason = self._scheduler.should_prune(
                    step, plan, step_results.get(execution_order[-1]) if execution_order else None
                )

                if should_prune:
                    plan.mark_skipped(step.agent_id)
                    pruned_agents.append(step.agent_id)
                    errors.append(
                        ExecutionError(
                            message=f"Pruned: {reason}",
                            agent_id=step.agent_id,
                            recoverable=False,
                        )
                    )
                    continue

                # Notify callbacks of agent start
                agent_name = agent_names.get(step.agent_id, step.agent_id)
                if self._callback_manager:
                    _agent_obj = agent_lookup.get(step.agent_id)
                    _prompt_preview_text = ""
                    if _agent_obj is not None:
                        _inc = {p: messages[p] for p in step.predecessors if p in messages}
                        _mem = self._get_memory_context(step.agent_id)
                        _sp = self._build_prompt(_agent_obj, query, _inc, agent_names, _mem)
                        _prompt_preview_text = _sp.text
                    self._callback_manager.on_agent_start(
                        run_id=run_id,
                        agent_id=step.agent_id,
                        agent_name=agent_name,
                        step_index=step_idx,
                        prompt=_prompt_preview_text[: self.config.prompt_preview_length],
                        predecessors=step.predecessors,
                    )

                agent_start_time = time.time()
                result = self._execute_step(step, messages, agent_lookup, agent_names, query)

                step_results[step.agent_id] = result
                execution_order.append(step.agent_id)

                if result.success:
                    messages[step.agent_id] = result.response or ""
                    plan.mark_completed(step.agent_id, result.tokens_used)
                    self._save_to_memory(step.agent_id, result.response or "", step.predecessors)

                    # Notify callbacks of agent end
                    if self._callback_manager:
                        self._callback_manager.on_agent_end(
                            run_id=run_id,
                            agent_id=step.agent_id,
                            output=result.response or "",
                            agent_name=agent_name,
                            step_index=step_idx,
                            tokens_used=result.tokens_used,
                            duration_ms=(time.time() - agent_start_time) * 1000,
                            is_final=False,
                        )
                else:
                    plan.mark_failed(step.agent_id)
                    errors.append(
                        ExecutionError(
                            message=result.error or "Unknown error",
                            agent_id=step.agent_id,
                            recoverable=True,
                        )
                    )

                    # Notify callbacks of agent error
                    if self._callback_manager:
                        self._callback_manager.on_agent_error(
                            run_id=run_id,
                            error=Exception(result.error or "Unknown error"),
                            agent_id=step.agent_id,
                            error_type="ExecutionError",
                        )

                    attempts = fallback_attempts.get(step.agent_id, 0)
                    if self._scheduler.should_use_fallback(step, result, attempts):
                        for fb_agent in step.fallback_agents:
                            if fb_agent not in plan.completed and fb_agent not in plan.failed:
                                plan.insert_fallback(fb_agent, plan.current_index - 1)
                                fallback_count += 1
                                break
                        fallback_attempts[step.agent_id] = attempts + 1

                # Topology pipeline: conditional edges + user hooks β†’ plan
                if self._run_topology_pipeline(
                    plan,
                    step.agent_id,
                    a_agents,
                    agent_ids,
                    step_results,
                    messages,
                    query,
                    execution_order,
                    plan.tokens_used,
                    role_graph,
                ):
                    topology_changed_count += 1

                step_idx += 1

        except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
            run_error = e

        final_id = self._determine_final_agent(final_agent_id, execution_order, messages)
        final_answer = messages.get(final_id, "")

        # Finalize callbacks
        self._finalize_run(
            run_id=run_id,
            success=run_error is None,
            executed_agents=len(execution_order),
            final_answer=final_answer,
            error=run_error,
            executed_agent_ids=execution_order,
        )

        if run_error:
            raise run_error

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        return MACPResult(
            messages=messages,
            final_answer=final_answer,
            final_agent_id=final_id,
            execution_order=execution_order,
            agent_states=agent_states,
            step_results=step_results,
            total_tokens=plan.tokens_used,
            total_time=time.time() - start_time,
            topology_changed_count=topology_changed_count,
            fallback_count=fallback_count,
            pruned_agents=pruned_agents,
            errors=errors if errors else None,
        )

    async def _arun_adaptive(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        start_agent_id: str | None,
        *,
        update_states: bool | None = None,
        filter_unreachable: bool = True,
        callbacks: list[Handler] | None = None,
    ) -> MACPResult:
        """
        Adaptive async execution with parallelism and conditional edges.

        Supports multi-model: each agent uses its own LLM caller.
        Supports filtering of isolated nodes to save tokens.
        Per-call ``callbacks`` are merged with ``RunnerConfig.callbacks``
        and context-manager callbacks (similar to ``_arun_simple``).
        """
        if not self._has_any_async_caller():
            msg = "async_llm_caller, async_llm_callers, or llm_factory is required for async execution"
            raise ValueError(msg)
        if self._scheduler is None:
            msg = "Scheduler not initialized for adaptive mode"
            raise ValueError(msg)

        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            return MACPResult(messages={}, final_answer="", final_agent_id="", execution_order=[])
        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        # Initialize memory
        self._init_memory(agent_ids)

        p_matrix = self._extract_p_matrix(role_graph, task_idx)

        # Get conditions from graph for conditional routing
        edge_conditions = self._get_edge_conditions(role_graph)

        # Context for conditions
        condition_ctx = ConditionContext(
            source_agent="",
            target_agent="",
            messages={},
            step_results={},
            query=query,
        )

        plan = self._scheduler.build_plan(
            a_agents,
            agent_ids,
            p_matrix,
            start_agent=start_agent_id,
            end_agent=final_agent_id,
            edge_conditions=edge_conditions,
            condition_context=condition_ctx,
            filter_unreachable=filter_unreachable,
        )

        # Initialize callbacks (per-call + config + context-manager)
        run_id = self._init_run(
            graph_name=getattr(role_graph, "name", None),
            num_agents=len(agent_ids),
            query=query,
            execution_order=plan.execution_order,
            callbacks=callbacks,
        )

        messages: dict[str, str] = {}
        step_results: dict[str, StepResult] = {}
        execution_order: list[str] = []
        fallback_attempts: dict[str, int] = {}
        topology_changed_count = 0
        fallback_count = 0
        pruned_agents: list[str] = []
        errors: list[ExecutionError] = []
        step_idx = 0
        run_error: BaseException | None = None

        try:
            while not plan.is_complete:
                parallel_group = self._get_parallel_group(plan, messages.keys())

                if not parallel_group:
                    break

                valid_steps = []
                for step in parallel_group:
                    # Skip agents whose conditions were not met
                    if step.agent_id in plan.condition_skipped:
                        plan.advance()
                        continue

                    should_prune, reason = self._scheduler.should_prune(step, plan, None)
                    if should_prune:
                        plan.mark_skipped(step.agent_id)
                        pruned_agents.append(step.agent_id)
                        errors.append(
                            ExecutionError(
                                message=f"Pruned: {reason}",
                                agent_id=step.agent_id,
                                recoverable=False,
                            )
                        )
                    else:
                        valid_steps.append(step)

                if not valid_steps:
                    # All steps in the group were skipped or pruned β€” plan may stall.
                    # If plan.is_complete is already True β€” we'll exit on the next iteration;
                    # otherwise explicitly break to avoid an infinite loop.
                    break

                # Notify callbacks of agent start for all steps in group
                group_start_times: dict[str, float] = {}
                for step in valid_steps:
                    agent_name = agent_names.get(step.agent_id, step.agent_id)
                    if self._callback_manager:
                        _agent_obj = agent_lookup.get(step.agent_id)
                        _prompt_preview_text = ""
                        if _agent_obj is not None:
                            _inc = {p: messages[p] for p in step.predecessors if p in messages}
                            _mem = self._get_memory_context(step.agent_id)
                            _sp = self._build_prompt(_agent_obj, query, _inc, agent_names, _mem)
                            _prompt_preview_text = _sp.text
                        self._callback_manager.on_agent_start(
                            run_id=run_id,
                            agent_id=step.agent_id,
                            agent_name=agent_name,
                            step_index=step_idx,
                            prompt=_prompt_preview_text[: self.config.prompt_preview_length],
                            predecessors=step.predecessors,
                        )
                    group_start_times[step.agent_id] = time.time()
                    step_idx += 1

                if self.config.enable_parallel and len(valid_steps) > 1:
                    results = await self._execute_parallel(valid_steps, messages, agent_lookup, agent_names, query)
                else:
                    results = []
                    for step in valid_steps:
                        r = await self._execute_step_async(step, messages, agent_lookup, agent_names, query)
                        results.append((step, r))

                for step, result in results:
                    step_results[step.agent_id] = result
                    execution_order.append(step.agent_id)
                    agent_name = agent_names.get(step.agent_id, step.agent_id)
                    agent_start_time = group_start_times.get(step.agent_id, time.time())

                    if result.success:
                        messages[step.agent_id] = result.response or ""
                        plan.mark_completed(step.agent_id, result.tokens_used)
                        self._save_to_memory(step.agent_id, result.response or "", step.predecessors)

                        # Notify callbacks of agent end
                        if self._callback_manager:
                            self._callback_manager.on_agent_end(
                                run_id=run_id,
                                agent_id=step.agent_id,
                                output=result.response or "",
                                agent_name=agent_name,
                                step_index=execution_order.index(step.agent_id),
                                tokens_used=result.tokens_used,
                                duration_ms=(time.time() - agent_start_time) * 1000,
                                is_final=False,
                            )
                    else:
                        plan.mark_failed(step.agent_id)
                        errors.append(
                            ExecutionError(
                                message=result.error or "Unknown error",
                                agent_id=step.agent_id,
                                recoverable=True,
                            )
                        )

                        # Notify callbacks of agent error
                        if self._callback_manager:
                            self._callback_manager.on_agent_error(
                                run_id=run_id,
                                error=Exception(result.error or "Unknown error"),
                                agent_id=step.agent_id,
                                error_type="ExecutionError",
                            )

                        attempts = fallback_attempts.get(step.agent_id, 0)
                        if self._scheduler.should_use_fallback(step, result, attempts):
                            for fb_agent in step.fallback_agents:
                                if fb_agent not in plan.completed and fb_agent not in plan.failed:
                                    plan.insert_fallback(fb_agent, plan.current_index - 1)
                                    fallback_count += 1
                                    break
                            fallback_attempts[step.agent_id] = attempts + 1

                # Topology pipeline for each executed agent in the group
                for step, _result in results:
                    if await self._arun_topology_pipeline(
                        plan,
                        step.agent_id,
                        a_agents,
                        agent_ids,
                        step_results,
                        messages,
                        query,
                        execution_order,
                        plan.tokens_used,
                        role_graph,
                    ):
                        topology_changed_count += 1

        except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
            run_error = e

        final_id = self._determine_final_agent(final_agent_id, execution_order, messages)
        final_answer = messages.get(final_id, "")

        # Finalize callbacks
        self._finalize_run(
            run_id=run_id,
            success=run_error is None,
            executed_agents=len(execution_order),
            final_answer=final_answer,
            error=run_error,
            executed_agent_ids=execution_order,
        )

        if run_error:
            raise run_error

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        return MACPResult(
            messages=messages,
            final_answer=final_answer,
            final_agent_id=final_id,
            execution_order=execution_order,
            agent_states=agent_states,
            step_results=step_results,
            total_tokens=plan.tokens_used,
            total_time=time.time() - start_time,
            topology_changed_count=topology_changed_count,
            fallback_count=fallback_count,
            pruned_agents=pruned_agents,
            errors=errors if errors else None,
        )

    def _get_task_index(self, role_graph: Any) -> int:
        """Get the rustworkx index of the task node or raise an error."""
        if role_graph.task_node is None:
            msg = "RoleGraph has no task_node set"
            raise ValueError(msg)

        task_idx = role_graph.get_node_index(role_graph.task_node)
        if task_idx is None:
            msg = f"Task node '{role_graph.task_node}' not found"
            raise ValueError(msg)
        return task_idx

    def _get_agent_ids(
        self,
        role_graph: Any,
        task_idx: int,
    ) -> tuple[list[str], dict[str, int]]:
        """Return the list of agent_ids (excluding task) and the id->adjacency index map."""
        agent_ids = []
        id_to_idx = {}

        adj_idx = 0
        for agent in role_graph.agents:
            graph_idx = role_graph.get_node_index(agent.agent_id)
            if graph_idx == task_idx:
                continue

            agent_ids.append(agent.agent_id)
            id_to_idx[agent.agent_id] = adj_idx
            adj_idx += 1

        return agent_ids, id_to_idx

    def _extract_p_matrix(self, role_graph: Any, task_idx: int) -> torch.Tensor | None:
        """Return the probability matrix without the task row/column."""
        if role_graph.p_matrix is None:
            return None

        n_nodes = role_graph.p_matrix.shape[0]
        mask = torch.ones(n_nodes, dtype=torch.bool)
        mask[task_idx] = False
        return role_graph.p_matrix[mask][:, mask]

    def _get_edge_conditions(self, role_graph: Any) -> dict[tuple[str, str], Any]:
        """Get all edge conditions from the graph."""
        if hasattr(role_graph, "get_all_edge_conditions"):
            return role_graph.get_all_edge_conditions()
        # Fallback: check individual attributes
        conditions: dict[tuple[str, str], Any] = {}
        if hasattr(role_graph, "edge_condition_names"):
            conditions.update(role_graph.edge_condition_names)
        if hasattr(role_graph, "edge_conditions"):
            conditions.update(role_graph.edge_conditions)
        return conditions

    def _build_agent_names(self, role_graph: Any) -> dict[str, str]:
        """Map id -> display_name/role for building the prompt."""
        return {a.agent_id: a.display_name or getattr(a, "role", a.agent_id) for a in role_graph.agents}

    def _get_task_connected_agents(self, role_graph: Any) -> set[str]:
        """Get the set of agents directly connected to the task node."""
        if role_graph.task_node is None:
            return set()

        task_idx = role_graph.get_node_index(role_graph.task_node)
        if task_idx is None or role_graph.A_com is None:
            return set()

        connected = set()
        for agent in role_graph.agents:
            agent_idx = role_graph.get_node_index(agent.agent_id)
            if agent_idx is not None and agent_idx != task_idx and role_graph.A_com[task_idx, agent_idx] > 0:
                connected.add(agent.agent_id)
        return connected

    def _should_include_query(self, agent_id: str, task_connected: set[str]) -> bool:
        """Determine whether to include the query in the agent's prompt."""
        if self.config.broadcast_task_to_all:
            return True
        return agent_id in task_connected

    def _run_agent_with_tools(  # noqa: PLR0912, PLR0915
        self,
        caller: Any,
        prompt: "str | StructuredPrompt",
        agent: Any,
    ) -> tuple[str, int]:
        """
        Execute an agent with automatic tools support.

        If the agent has tools, they are ALWAYS used via native function calling.
        Tools are obtained from:
        1. BaseTool objects directly in agent.tools
        2. Tool names registered in the global registry or config.tool_registry

        ``prompt`` may be a plain ``str`` (legacy) or a
        ``StructuredPrompt`` (modern).  For plain LLM calls the method
        dispatches via :meth:`_call_llm` which picks the structured
        caller when available.

        When a ``structured_llm_caller`` is registered the tool-calling
        loop also uses structured messages (system/user/tool roles) so
        the LLM receives proper role separation throughout the entire
        tool-calling conversation.

        Args:
            caller: LLM caller (must support the tools parameter)
            prompt: Agent prompt (str or StructuredPrompt)
            agent: Agent profile (AgentProfile with tools)

        Returns:
            tuple[str, int]: (response, number of tokens)

        """
        import inspect
        import logging

        logger = logging.getLogger(__name__)

        # Normalise prompt β€” always have both flat text and structured form
        prompt_text = prompt.text if isinstance(prompt, StructuredPrompt) else prompt

        # Check if the agent has tools
        if not TOOLS_AVAILABLE:
            response = self._call_llm(caller, prompt) if isinstance(prompt, StructuredPrompt) else caller(prompt)
            return response, self.token_counter(prompt_text) + self.token_counter(response)

        # Get agent tools (method from AgentProfile)
        agent_tools = []
        if hasattr(agent, "get_tool_objects"):
            agent_tools = agent.get_tool_objects()
        elif hasattr(agent, "tools") and agent.tools:
            # Fallback for old format (names only)
            from tools import get_registry

            registry = self.config.tool_registry or get_registry()
            tool_names = agent.tools
            agent_tools = registry.get_tools(tool_names)

        if not agent_tools:
            # Agent has no tools β€” plain call (use structured dispatch)
            response = self._call_llm(caller, prompt) if isinstance(prompt, StructuredPrompt) else caller(prompt)
            return response, self.token_counter(prompt_text) + self.token_counter(response)

        # Check that caller supports tools
        sig = inspect.signature(caller)
        supports_tools = "tools" in sig.parameters

        if not supports_tools:
            # Caller does not support tools β€” plain call
            response = self._call_llm(caller, prompt) if isinstance(prompt, StructuredPrompt) else caller(prompt)
            return response, self.token_counter(prompt_text) + self.token_counter(response)

        # Get schemas for tools
        tool_schemas = [t.to_openai_schema() for t in agent_tools]
        if not tool_schemas:
            response = self._call_llm(caller, prompt) if isinstance(prompt, StructuredPrompt) else caller(prompt)
            return response, self.token_counter(prompt_text) + self.token_counter(response)

        # Get registry for executing tools
        from tools import ToolCall, get_registry

        registry = self.config.tool_registry or get_registry()

        # Register all agent tools in the registry (for BaseTool objects)
        for t in agent_tools:
            if not registry.has(t.name):
                registry.register(t)

        # Execute tool calling loop
        total_tokens = 0

        # Build the conversation for the tool-calling loop.
        # When structured messages are available we keep a proper
        # multi-turn conversation; otherwise we accumulate flat text.
        if isinstance(prompt, StructuredPrompt):
            tool_messages: list[dict[str, str]] = list(prompt.messages)
        else:
            tool_messages = [{"role": "user", "content": prompt}]

        current_prompt = prompt_text  # flat fallback

        # Cache for tool calls: (tool_name, args_json) -> result
        # Prevents repeated execution of identical calls
        tool_cache: dict[str, str] = {}

        logger.debug("Agent has tools: %s", [s["function"]["name"] for s in tool_schemas])

        llm_response: Any = None
        use_structured_tools = isinstance(prompt, StructuredPrompt) and self.structured_llm_caller is not None

        for iteration in range(self.config.max_tool_iterations):
            # Call LLM with tools
            logger.debug("Tool calling iteration %d", iteration + 1)

            # Prefer structured messages when a structured caller is available;
            # this gives the LLM proper system/user/assistant/tool role separation
            # throughout the entire tool-calling conversation.
            if use_structured_tools:
                llm_response = caller(tool_messages, tools=tool_schemas)
            else:
                llm_response = caller(current_prompt, tools=tool_schemas)

            if isinstance(llm_response, str):
                # Caller returned a string, not an LLMResponse
                return llm_response, self.token_counter(current_prompt) + self.token_counter(llm_response)

            # Token counting: use the actual prompt content sent to the LLM
            if use_structured_tools:
                prompt_tokens = sum(self.token_counter(m.get("content", "")) for m in tool_messages)
            else:
                prompt_tokens = self.token_counter(current_prompt)
            total_tokens += prompt_tokens
            if llm_response.content:
                total_tokens += self.token_counter(llm_response.content)

            # If there are no tool_calls β€” return the response
            if not llm_response.has_tool_calls:
                content = llm_response.content or ""
                if content:
                    logger.debug("No tool calls, returning content: %s...", content[:50])
                return content, total_tokens

            # Execute tool_calls with caching
            tool_results: list[str] = []
            for tc in llm_response.tool_calls:
                # Create a cache key from the name and arguments
                import json as json_module

                cache_key = f"{tc.name}:{json_module.dumps(tc.arguments, sort_keys=True)}"

                if cache_key in tool_cache:
                    # Already called with these arguments β€” use cache
                    output = tool_cache[cache_key]
                    logger.debug("Tool cache hit: %s(%s) -> %s...", tc.name, tc.arguments, output[:50])
                else:
                    # New call β€” execute and cache
                    logger.debug("Executing tool: %s(%s)", tc.name, tc.arguments)
                    tool_call = ToolCall(name=tc.name, arguments=tc.arguments)
                    result = registry.execute(tool_call)
                    output = result.output if result.success else f"Error: {result.error}"
                    tool_cache[cache_key] = output
                    logger.debug("Tool result: %s...", output[:100])

                tool_results.append(f"[{tc.name}]: {output}")

            # Add results to the conversation for the next iteration.
            # Structured path: append assistant + tool messages to the
            # conversation so the LLM sees the full multi-turn history.
            tool_results_text = "\n".join(tool_results)

            if isinstance(prompt, StructuredPrompt):
                # Append the assistant's tool-call reply
                if llm_response.content:
                    tool_messages.append({"role": "assistant", "content": llm_response.content})
                # Append tool results as a user message (compatible with
                # all providers; some accept role="tool" but "user" is universal)
                tool_messages.append({"role": "user", "content": f"Tool results:\n{tool_results_text}"})

            # Flat text fallback (used by legacy callers)
            current_prompt = f"{prompt_text}\n\nTool results:\n{tool_results_text}"

        # Reached max_iterations, return the last content
        return llm_response.content if llm_response else "", total_tokens

    def _build_system_prompt_parts(self, agent: Any) -> list[str]:
        """Build system prompt parts: persona, description, tools, output_schema."""
        import json as _json

        parts: list[str] = []
        if hasattr(agent, "persona") and agent.persona:
            parts.append(f"You are {agent.persona}.")
        elif hasattr(agent, "role") and agent.role:
            parts.append(f"You are a {agent.role}.")

        if hasattr(agent, "description") and agent.description:
            parts.append(agent.description.strip())

        # ── tools β†’ brief mention so the agent is aware of its capabilities
        tool_names: list[str] = []
        if hasattr(agent, "get_tool_names"):
            tool_names = agent.get_tool_names()
        elif hasattr(agent, "tools") and agent.tools:
            tool_names = [t if isinstance(t, str) else getattr(t, "name", str(t)) for t in agent.tools]
        if tool_names:
            parts.append(f"Available tools: {', '.join(tool_names)}.")

        # ── output_schema β†’ compact format instruction ───────────────
        output_schema_json = self._extract_schema_json(agent, "output_schema")
        if output_schema_json:
            schema_text = _json.dumps(output_schema_json, ensure_ascii=False, separators=(",", ":"))
            parts.append(f"Respond with JSON matching: {schema_text}")

        return parts

    def _build_user_prompt_parts(
        self,
        agent: Any,
        query: str,
        incoming_messages: dict[str, str],
        agent_names: dict[str, str],
        memory_context: list[dict[str, Any]] | None,
        *,
        include_query: bool,
    ) -> list[str]:
        """Build user prompt parts: query, input_schema, memory, incoming messages."""
        import json as _json

        user_parts: list[str] = []

        # Task query is added only if include_query=True
        if include_query and query:
            user_parts.append(f"Task: {query}")

        # ── input_schema hint (compact) ──────────────────────────────
        input_schema_json = self._extract_schema_json(agent, "input_schema")
        if input_schema_json:
            schema_text = _json.dumps(input_schema_json, ensure_ascii=False, separators=(",", ":"))
            user_parts.append(f"\nInput format: {schema_text}")

        # Include memory context from SharedMemoryPool
        if memory_context:
            user_parts.append("\nPrevious context:")
            for msg in memory_context:
                role = msg.get("role", "unknown")
                content = msg.get("content", "")
                user_parts.append(f"[{role}]: {content}")

        if incoming_messages:
            user_parts.append("\nMessages from other agents:")
            for sender_id, message in incoming_messages.items():
                sender_name = agent_names.get(sender_id, sender_id)
                user_parts.append(f"\n[{sender_name}]:\n{message}")
        user_parts.append("\nProvide your response:")

        return user_parts

    def _build_state_text_parts(self, agent: Any) -> list[str]:
        """Build state text parts for flat string representation."""
        agent_state: list[dict[str, Any]] = []
        if hasattr(agent, "state"):
            agent_state = list(agent.state) if agent.state else []

        state_text_parts: list[str] = []
        if agent_state:
            state_text_parts.append("\nConversation history:")
            for entry in agent_state:
                entry_role = entry.get("role", "unknown")
                entry_content = entry.get("content", "")
                if entry_content:
                    state_text_parts.append(f"[{entry_role}]: {entry_content}")

        return state_text_parts

    def _build_structured_messages(
        self,
        system_prompt: str,
        agent_state: list[dict[str, Any]],
        user_content: str,
        flat_user: str,
        use_structured_state: bool,
    ) -> list[dict[str, str]]:
        """Build structured messages list for modern chat LLMs."""
        messages: list[dict[str, str]] = [
            {"role": "system", "content": system_prompt},
        ]

        if use_structured_state:
            # Replay agent.state as proper assistant/user turns so the
            # LLM sees real conversation history with correct roles.
            for entry in agent_state:
                entry_role = entry.get("role", "user")
                entry_content = entry.get("content", "")
                if entry_content:
                    # Map roles: "agent"/"assistant" β†’ "assistant", everything else β†’ "user"
                    msg_role = "assistant" if entry_role in ("agent", "assistant") else "user"
                    messages.append({"role": msg_role, "content": entry_content})
            # user_content does NOT contain state (it's in separate messages above)
            messages.append({"role": "user", "content": user_content})
        else:
            # Legacy path or no state: state is inlined in user_content
            messages.append({"role": "user", "content": flat_user})

        return messages

    def _build_prompt(
        self,
        agent: Any,
        query: str,
        incoming_messages: dict[str, str],
        agent_names: dict[str, str],
        memory_context: list[dict[str, Any]] | None = None,
        *,
        include_query: bool = True,
    ) -> StructuredPrompt:
        """
        Build the agent prompt with persona/description, state, schemas, memory, and messages.

        Returns a ``StructuredPrompt`` that carries **both** representations:

        * ``prompt.text``     β€” legacy flat string (backward-compatible)
        * ``prompt.messages`` β€” ``[{"role": "system", ...}, {"role": "user", ...}]``

        The system message includes:
        - persona / role identity
        - description
        - output_schema instructions (expected response format)

        The user message includes:
        - task query
        - agent conversation state (previous turns)
        - memory context from SharedMemoryPool
        - incoming messages from other agents
        - input_schema hint (expected input structure)

        When a ``structured_llm_caller`` is registered the runner sends
        ``prompt.messages`` directly to the LLM, giving it proper
        system/user role separation.  Otherwise ``prompt.text`` is used
        with the legacy ``llm_caller(str) -> str`` interface.

        Args:
            agent: Agent object with description/persona
            query: User query string
            incoming_messages: Messages from other agents
            agent_names: Mapping of agent IDs to names
            memory_context: Optional list of memory entries
            include_query: Whether to include the task query in the prompt.
                          Controlled via config.broadcast_task_to_all.

        """
        # Build system prompt
        system_parts = self._build_system_prompt_parts(agent)
        system_prompt = "\n\n".join(system_parts) if system_parts else "You are a helpful assistant."

        # Build user prompt parts
        user_parts = self._build_user_prompt_parts(
            agent, query, incoming_messages, agent_names, memory_context, include_query=include_query
        )
        user_content = "".join(user_parts)

        # Build state text parts
        agent_state: list[dict[str, Any]] = []
        if hasattr(agent, "state"):
            agent_state = list(agent.state) if agent.state else []

        use_structured_state = bool(agent_state) and self.structured_llm_caller is not None
        state_text_parts = self._build_state_text_parts(agent)

        # Build flat string (legacy)
        flat_user = "".join(state_text_parts) + user_content if state_text_parts else user_content
        flat = f"{system_prompt}\n\n{flat_user}"

        # Build structured messages (modern)
        messages = self._build_structured_messages(
            system_prompt, agent_state, user_content, flat_user, use_structured_state
        )

        return StructuredPrompt(text=flat, messages=messages)

    @staticmethod
    def _extract_schema_json(agent: Any, attr: str) -> dict[str, Any] | None:
        """
        Extract a JSON Schema dict from an agent's schema attribute.

        Supports:
        - ``dict`` β€” returned as-is (already a JSON Schema)
        - Pydantic ``BaseModel`` subclass β€” converted via ``model_json_schema()``
        - ``None`` / missing β€” returns ``None``
        """
        schema = getattr(agent, attr, None)
        if schema is None:
            return None
        if isinstance(schema, dict):
            return schema
        # Pydantic model class
        try:
            from pydantic import BaseModel

            if isinstance(schema, type) and issubclass(schema, BaseModel):
                return schema.model_json_schema()
        except Exception as exc:  # noqa: BLE001
            # Pydantic may not be available or schema may not be a BaseModel
            # This is expected in some cases, so we silently continue
            _ = exc  # Suppress unused variable warning
        return None

    def _execute_step(
        self,
        step: Any,
        messages: dict[str, str],
        agent_lookup: dict[str, Any],
        agent_names: dict[str, str],
        query: str,
    ) -> StepResult:
        """
        Execute a step synchronously with retries and token counting.

        Supports multi-model: uses the caller for the specific agent.
        """
        agent = agent_lookup.get(step.agent_id)
        if agent is None:
            return StepResult(
                agent_id=step.agent_id,
                success=False,
                error=f"Agent '{step.agent_id}' not found",
            )

        # Get caller for this specific agent (multi-model support)
        caller = self._get_caller_for_agent(step.agent_id, agent)
        if caller is None:
            return StepResult(
                agent_id=step.agent_id,
                success=False,
                error=f"No LLM caller available for agent '{step.agent_id}'",
            )

        incoming = {p: messages[p] for p in step.predecessors if p in messages}
        memory_context = self._get_memory_context(step.agent_id)
        prompt = self._build_prompt(agent, query, incoming, agent_names, memory_context)

        last_error = None
        delay = self.config.retry_delay

        for attempt in range(self.config.max_retries + 1):
            try:
                # Execute with tools support
                response, tokens = self._run_agent_with_tools(
                    caller=caller,
                    prompt=prompt,
                    agent=agent,
                )

                quality = 1.0
                if self._scheduler and self._scheduler.pruning.quality_scorer:
                    quality = self._scheduler.pruning.quality_scorer(response)

                return StepResult(
                    agent_id=step.agent_id,
                    success=True,
                    response=response,
                    tokens_used=tokens,
                    quality_score=quality,
                )
            except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                last_error = str(e)
                if attempt < self.config.max_retries:
                    time.sleep(delay)
                    delay *= self.config.retry_backoff

        return StepResult(
            agent_id=step.agent_id,
            success=False,
            error=last_error,
        )

    async def _execute_step_async(
        self,
        step: Any,
        messages: dict[str, str],
        agent_lookup: dict[str, Any],
        agent_names: dict[str, str],
        query: str,
    ) -> StepResult:
        """
        Execute a step asynchronously with retries and timeout.

        Supports multi-model: uses the async caller for the specific agent.
        """
        agent = agent_lookup.get(step.agent_id)
        if agent is None:
            return StepResult(
                agent_id=step.agent_id,
                success=False,
                error=f"Agent '{step.agent_id}' not found",
            )

        # Get async caller for this specific agent (multi-model support).
        # _get_async_caller_for_agent may return None when only
        # async_structured_llm_caller is configured β€” _acall_llm handles
        # that case internally, so we only error when *neither* is available.
        async_caller = self._get_async_caller_for_agent(step.agent_id, agent)
        if async_caller is None and self.async_structured_llm_caller is None:
            return StepResult(
                agent_id=step.agent_id,
                success=False,
                error=f"No async LLM caller available for agent '{step.agent_id}'",
            )

        incoming = {p: messages[p] for p in step.predecessors if p in messages}
        memory_context = self._get_memory_context(step.agent_id)
        prompt = self._build_prompt(agent, query, incoming, agent_names, memory_context)

        last_error = None
        delay = self.config.retry_delay

        for attempt in range(self.config.max_retries + 1):
            try:
                response = await asyncio.wait_for(
                    self._acall_llm(async_caller, prompt),
                    timeout=self.config.timeout,
                )
                tokens = self.token_counter(prompt.text) + self.token_counter(response)

                quality = 1.0
                if self._scheduler and self._scheduler.pruning.quality_scorer:
                    quality = self._scheduler.pruning.quality_scorer(response)

                return StepResult(
                    agent_id=step.agent_id,
                    success=True,
                    response=response,
                    tokens_used=tokens,
                    quality_score=quality,
                )
            except TimeoutError:
                last_error = f"Timeout after {self.config.timeout}s"
            except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                last_error = str(e)

            if attempt < self.config.max_retries:
                await asyncio.sleep(delay)
                delay *= self.config.retry_backoff

        return StepResult(
            agent_id=step.agent_id,
            success=False,
            error=last_error,
        )

    async def _execute_parallel(
        self,
        steps: list[Any],
        messages: dict[str, str],
        agent_lookup: dict[str, Any],
        agent_names: dict[str, str],
        query: str,
    ) -> list[tuple[Any, StepResult]]:
        """Execute a group of steps in parallel asynchronously."""
        tasks = [self._execute_step_async(step, messages, agent_lookup, agent_names, query) for step in steps]

        results = await asyncio.gather(*tasks, return_exceptions=True)

        output = []
        for step, result in zip(steps, results, strict=False):
            if isinstance(result, Exception):
                sr = StepResult(
                    agent_id=step.agent_id,
                    success=False,
                    error=str(result),
                )
            else:
                sr = result
            output.append((step, sr))

        return output

    def _get_parallel_group(
        self,
        plan: ExecutionPlan,
        completed_agents: Any,
    ) -> list[Any]:
        """Return a group of steps ready for parallel execution."""
        completed = set(completed_agents)
        group: list[Any] = []

        for step in plan.remaining_steps:
            if (
                step.agent_id in plan.completed
                or step.agent_id in plan.skipped
                or step.agent_id in plan.condition_skipped
            ):
                continue

            predecessors_done = all(
                p in completed or p in plan.skipped or p in plan.condition_skipped for p in step.predecessors
            )

            if predecessors_done:
                group.append(step)
                if len(group) >= self.config.max_parallel_size:
                    break

        return group

    def _determine_final_agent(
        self,
        requested: str | None,
        exec_order: list[str],
        messages: dict[str, str],
    ) -> str:
        """Select the final agent: the requested one or the last in execution order."""
        if requested and requested in messages:
            return requested
        if exec_order:
            return exec_order[-1]
        return ""

    def _build_agent_states(
        self,
        messages: dict[str, str],
        agent_lookup: dict[str, Any],
    ) -> dict[str, list[dict[str, Any]]]:
        """Build updated agent states by appending responses to history."""
        states: dict[str, list[dict[str, Any]]] = {}
        for agent_id, response in messages.items():
            agent = agent_lookup.get(agent_id)
            if agent is not None:
                new_state = list(getattr(agent, "state", []))
                new_state.append({"role": "assistant", "content": response})
                states[agent_id] = new_state
        return states

    def _collect_hidden_states(
        self,
        agent_lookup: dict[str, Any],
    ) -> dict[str, HiddenState]:
        """Collect the current hidden_state/embedding of agents into a dictionary."""
        hidden_states: dict[str, HiddenState] = {}
        for agent_id, agent in agent_lookup.items():
            hs = HiddenState()
            if hasattr(agent, "hidden_state") and agent.hidden_state is not None:
                hs.tensor = agent.hidden_state
            if hasattr(agent, "embedding") and agent.embedding is not None:
                hs.embedding = agent.embedding
            if hs.tensor is not None or hs.embedding is not None:
                hidden_states[agent_id] = hs
        return hidden_states

    def _combine_hidden_states(
        self,
        states: list[HiddenState],
    ) -> HiddenState | None:
        """Combine a list of hidden states according to the hidden_combine_strategy."""
        if not states:
            return None

        tensors = [s.tensor for s in states if s.tensor is not None]
        embeddings = [s.embedding for s in states if s.embedding is not None]

        combined = HiddenState()

        if tensors:
            combined.tensor = self._combine_tensors(tensors)

        if embeddings:
            combined.embedding = self._combine_tensors(embeddings)

        return combined if (combined.tensor is not None or combined.embedding is not None) else None

    def _combine_tensors(self, tensors: list[torch.Tensor]) -> torch.Tensor:
        """Combine a list of tensors according to the strategy (mean/sum/concat/attention)."""
        if len(tensors) == 1:
            return tensors[0]

        stacked = torch.stack(tensors)

        if self.config.hidden_combine_strategy == "mean":
            return stacked.mean(dim=0)
        if self.config.hidden_combine_strategy == "sum":
            return stacked.sum(dim=0)
        if self.config.hidden_combine_strategy == "concat":
            return torch.cat(tensors, dim=-1)
        if self.config.hidden_combine_strategy == "attention":
            weights = torch.softmax(torch.ones(len(tensors)), dim=0)
            return (stacked * weights.view(-1, *([1] * (stacked.dim() - 1)))).sum(dim=0)
        return stacked.mean(dim=0)

    def _get_incoming_hidden(
        self,
        _agent_id: str,
        incoming_ids: list[str],
        hidden_states: dict[str, HiddenState],
    ) -> HiddenState | None:
        """Get the combined hidden state of predecessors."""
        if not self.config.enable_hidden_channels:
            return None

        incoming_states = [hidden_states[aid] for aid in incoming_ids if aid in hidden_states]

        return self._combine_hidden_states(incoming_states)

    def _update_agent_hidden_state(
        self,
        agent: Any,
        response: str,
        incoming_hidden: HiddenState | None,
        hidden_encoder: Any | None = None,
    ) -> HiddenState:
        """Update the agent's hidden_state based on the response and incoming hidden state."""
        new_hidden = HiddenState()

        if hasattr(agent, "embedding") and agent.embedding is not None:
            new_hidden.embedding = agent.embedding

        if hidden_encoder is not None:
            try:
                encoded = hidden_encoder.encode([response])
                if isinstance(encoded, torch.Tensor) and encoded.numel() > 0:
                    new_hidden.tensor = encoded[0]
            except (ValueError, TypeError, RuntimeError):
                pass  # Ignore encoding errors

        if new_hidden.tensor is None and incoming_hidden is not None:
            new_hidden.tensor = incoming_hidden.tensor

        new_hidden.metadata = {
            "last_response_length": len(response),
            "has_incoming": incoming_hidden is not None,
        }

        return new_hidden

    def run_round_with_hidden(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        hidden_encoder: Any | None = None,
    ) -> MACPResult:
        """
        Synchronous round with hidden state transfer between agents.

        Supports multi-model: each agent uses its own LLM caller.
        Supports conditional edge evaluation.
        """
        if not self._has_any_caller():
            msg = "llm_caller, llm_callers, or llm_factory is required"
            raise ValueError(msg)

        original_hidden_setting = self.config.enable_hidden_channels
        self.config.enable_hidden_channels = True

        start_time = time.time()

        try:
            base = self._prepare_base_context(role_graph)
        except Exception:
            self.config.enable_hidden_channels = original_hidden_setting
            raise

        if base is None:
            self.config.enable_hidden_channels = original_hidden_setting
            return MACPResult(messages={}, final_answer="", final_agent_id="", execution_order=[])

        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        # Initialize memory
        self._init_memory(agent_ids)

        hidden_states = self._collect_hidden_states(agent_lookup)

        messages: dict[str, str] = {}
        step_results: dict[str, StepResult] = {}
        execution_order: list[str] = []
        fallback_attempts: dict[str, int] = {}
        topology_changed_count = 0
        fallback_count = 0
        pruned_agents: list[str] = []
        errors: list[ExecutionError] = []
        total_tokens = 0

        # Adaptive mode: plan + conditional edge evaluation after each step
        if self.config.adaptive and self._scheduler is not None:
            p_matrix = self._extract_p_matrix(role_graph, task_idx)
            edge_conditions = self._get_edge_conditions(role_graph)

            condition_ctx = ConditionContext(
                source_agent="",
                target_agent="",
                messages={},
                step_results={},
                query=query,
            )

            plan = self._scheduler.build_plan(
                a_agents,
                agent_ids,
                p_matrix,
                start_agent=None,
                end_agent=final_agent_id,
                edge_conditions=edge_conditions,
                condition_context=condition_ctx,
                filter_unreachable=True,
            )

            while not plan.is_complete:
                step = plan.get_current_step()

                if step is None:
                    break

                if step.agent_id in plan.condition_skipped:
                    plan.advance()
                    continue

                should_prune, reason = self._scheduler.should_prune(
                    step, plan, step_results.get(execution_order[-1]) if execution_order else None
                )

                if should_prune:
                    plan.mark_skipped(step.agent_id)
                    pruned_agents.append(step.agent_id)
                    errors.append(
                        ExecutionError(
                            message=f"Pruned: {reason}",
                            agent_id=step.agent_id,
                            recoverable=False,
                        )
                    )
                    continue

                agent_id = step.agent_id
                agent = agent_lookup.get(agent_id)

                if agent is None:
                    plan.advance()
                    continue

                incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
                incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}
                incoming_hidden = self._get_incoming_hidden(agent_id, incoming_ids, hidden_states)

                memory_context = self._get_memory_context(agent_id)
                prompt = self._build_prompt(agent, query, incoming_messages, agent_names, memory_context)

                if incoming_hidden and incoming_hidden.metadata:
                    context_hint = self._format_hidden_context(incoming_hidden)

                    if context_hint:
                        suffix = f"\n\n[Context: {context_hint}]"
                        prompt = StructuredPrompt(
                            text=prompt.text + suffix,
                            messages=[
                                *prompt.messages[:-1],
                                {"role": "user", "content": prompt.messages[-1]["content"] + suffix},
                            ],
                        )

                try:
                    caller = self._get_caller_for_agent(agent_id, agent)

                    if caller is None:
                        error_msg = f"No LLM caller available for agent {agent_id}"
                        messages[agent_id] = f"[Error: {error_msg}]"
                        result = StepResult(agent_id=agent_id, success=False, error=error_msg)
                        step_results[agent_id] = result
                        execution_order.append(agent_id)
                        plan.mark_failed(agent_id)
                        errors.append(
                            ExecutionError(
                                message=error_msg,
                                agent_id=agent_id,
                                recoverable=True,
                            )
                        )

                        # Fallback when caller is missing
                        attempts = fallback_attempts.get(agent_id, 0)
                        if self._scheduler.should_use_fallback(step, result, attempts):
                            for fb_agent in step.fallback_agents:
                                if fb_agent not in plan.completed and fb_agent not in plan.failed:
                                    plan.insert_fallback(fb_agent, plan.current_index - 1)
                                    fallback_count += 1
                                    break
                            fallback_attempts[agent_id] = attempts + 1
                        continue

                    response, tokens = self._run_agent_with_tools(
                        caller=caller,
                        prompt=prompt,
                        agent=agent,
                    )
                    messages[agent_id] = response
                    total_tokens += tokens
                    execution_order.append(agent_id)
                    self._save_to_memory(agent_id, response, incoming_ids)

                    hidden_states[agent_id] = self._update_agent_hidden_state(
                        agent, response, incoming_hidden, hidden_encoder
                    )

                    result = StepResult(
                        agent_id=agent_id,
                        success=True,
                        response=response,
                        tokens_used=tokens,
                    )
                    step_results[agent_id] = result
                    plan.mark_completed(agent_id, tokens)

                except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                    messages[agent_id] = f"[Error: {e}]"
                    result = StepResult(agent_id=agent_id, success=False, error=str(e))
                    step_results[agent_id] = result
                    execution_order.append(agent_id)
                    plan.mark_failed(agent_id)
                    errors.append(
                        ExecutionError(
                            message=str(e),
                            agent_id=agent_id,
                            recoverable=True,
                        )
                    )

                    # Fallback on execution error
                    attempts = fallback_attempts.get(agent_id, 0)
                    if self._scheduler.should_use_fallback(step, result, attempts):
                        for fb_agent in step.fallback_agents:
                            if fb_agent not in plan.completed and fb_agent not in plan.failed:
                                plan.insert_fallback(fb_agent, plan.current_index - 1)
                                fallback_count += 1
                                break
                        fallback_attempts[agent_id] = attempts + 1

                # Topology pipeline: conditional edges + user hooks β†’ plan
                if self._run_topology_pipeline(
                    plan,
                    agent_id,
                    a_agents,
                    agent_ids,
                    step_results,
                    messages,
                    query,
                    execution_order,
                    total_tokens,
                    role_graph,
                ):
                    topology_changed_count += 1

        else:
            # Non-adaptive mode: execute the plan linearly
            exec_order = build_execution_order(a_agents, agent_ids, role_graph.role_sequence)

            for agent_id in exec_order:
                agent = agent_lookup.get(agent_id)
                if agent is None:
                    continue

                incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
                incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}
                incoming_hidden = self._get_incoming_hidden(agent_id, incoming_ids, hidden_states)

                memory_context = self._get_memory_context(agent_id)
                prompt = self._build_prompt(agent, query, incoming_messages, agent_names, memory_context)

                if incoming_hidden and incoming_hidden.metadata:
                    context_hint = self._format_hidden_context(incoming_hidden)

                    if context_hint:
                        suffix = f"\n\n[Context: {context_hint}]"
                        prompt = StructuredPrompt(
                            text=prompt.text + suffix,
                            messages=[
                                *prompt.messages[:-1],
                                {"role": "user", "content": prompt.messages[-1]["content"] + suffix},
                            ],
                        )

                try:
                    caller = self._get_caller_for_agent(agent_id, agent)

                    if caller is None:
                        error_msg = f"No LLM caller available for agent {agent_id}"
                        messages[agent_id] = f"[Error: {error_msg}]"
                        result = StepResult(agent_id=agent_id, success=False, error=error_msg)
                        step_results[agent_id] = result
                        execution_order.append(agent_id)
                        errors.append(
                            ExecutionError(
                                message=error_msg,
                                agent_id=agent_id,
                                recoverable=True,
                            )
                        )
                        continue

                    response, tokens = self._run_agent_with_tools(
                        caller=caller,
                        prompt=prompt,
                        agent=agent,
                    )
                    messages[agent_id] = response
                    total_tokens += tokens
                    execution_order.append(agent_id)
                    self._save_to_memory(agent_id, response, incoming_ids)

                    hidden_states[agent_id] = self._update_agent_hidden_state(
                        agent, response, incoming_hidden, hidden_encoder
                    )
                    result = StepResult(
                        agent_id=agent_id,
                        success=True,
                        response=response,
                        tokens_used=tokens,
                    )
                    step_results[agent_id] = result
                except (ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                    messages[agent_id] = f"[Error: {e}]"
                    result = StepResult(agent_id=agent_id, success=False, error=str(e))
                    step_results[agent_id] = result
                    execution_order.append(agent_id)
                    errors.append(
                        ExecutionError(
                            message=str(e),
                            agent_id=agent_id,
                            recoverable=True,
                        )
                    )

        final_id = self._determine_final_agent(final_agent_id, execution_order, messages)
        agent_states = self._build_agent_states(messages, agent_lookup)

        result = MACPResult(
            messages=messages,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            execution_order=execution_order,
            topology_changed_count=topology_changed_count,
            fallback_count=fallback_count,
            agent_states=agent_states,
            step_results=step_results,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            pruned_agents=pruned_agents,
            errors=errors if errors else None,
            hidden_states=hidden_states,
        )
        self.config.enable_hidden_channels = original_hidden_setting
        return result

    def _format_hidden_context(self, hidden: HiddenState) -> str:
        """Format hidden state metadata for inclusion in the prompt."""
        parts = []
        if hidden.metadata and "last_response_length" in hidden.metadata:
            parts.append(f"previous response length: {hidden.metadata['last_response_length']}")
        return ", ".join(parts) if parts else ""

    # =========================================================================
    # STREAMING EXECUTION METHODS
    # =========================================================================

    def stream(
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        *,
        update_states: bool | None = None,
    ) -> Iterator[AnyStreamEvent]:
        """
        Stream execution events for real-time output.

        Yields events as agents are executed, allowing real-time monitoring
        and display of intermediate results.

        Args:
            role_graph: The RoleGraph to execute
            final_agent_id: Override which agent produces final answer
            update_states: Whether to update agent states after execution

        Yields:
            StreamEvent instances for each execution phase

        Example:
            for event in runner.stream(graph):
                if event.event_type == StreamEventType.AGENT_OUTPUT:
                    print(f"{event.agent_id}: {event.content}")
                elif event.event_type == StreamEventType.TOKEN:
                    print(event.token, end="", flush=True)

        """
        if not self._has_any_caller() and self.streaming_llm_caller is None:
            msg = "llm_caller, llm_callers, llm_factory, or streaming_llm_caller required for streaming"
            raise ValueError(msg)

        if self.config.adaptive:
            yield from self._stream_adaptive(role_graph, final_agent_id, update_states=update_states)
        else:
            yield from self._stream_simple(role_graph, final_agent_id, update_states=update_states)

    async def astream(
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        *,
        update_states: bool | None = None,
    ) -> AsyncIterator[AnyStreamEvent]:
        """
        Async streaming execution for real-time output.

        Async version of stream() for use in async contexts.

        Args:
            role_graph: The RoleGraph to execute
            final_agent_id: Override which agent produces final answer
            update_states: Whether to update agent states after execution

        Yields:
            StreamEvent instances for each execution phase

        Example:
            async for event in runner.astream(graph):
                match event.event_type:
                    case StreamEventType.AGENT_START:
                        print(f"Agent {event.agent_id} started")
                    case StreamEventType.AGENT_OUTPUT:
                        print(f"Output: {event.content}")

        """
        if not self._has_any_async_caller() and self.async_streaming_llm_caller is None:
            msg = "async_llm_caller, async_llm_callers, llm_factory, or async_streaming_llm_caller required"
            raise ValueError(msg)

        if self.config.adaptive:
            async for event in self._astream_adaptive(role_graph, final_agent_id, update_states=update_states):
                yield event
        else:
            async for event in self._astream_simple(role_graph, final_agent_id, update_states=update_states):
                yield event

    def _stream_simple(  # noqa: PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        *,
        update_states: bool | None,
    ) -> Iterator[StreamEvent]:
        """Simple sequential streaming execution."""
        run_id = str(uuid.uuid4())[:8]
        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            yield RunEndEvent(
                run_id=run_id, success=True, final_answer="", final_agent_id="", total_time=time.time() - start_time
            )
            return

        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base
        del task_idx  # not used directly in simple streaming

        exec_order = build_execution_order(a_agents, agent_ids, role_graph.role_sequence)
        self._init_memory(agent_ids)

        task_connected = self._get_task_connected_agents(role_graph)

        # Emit run start
        yield RunStartEvent(
            run_id=run_id,
            query=query,
            num_agents=len(exec_order),
            execution_order=exec_order,
            config_summary={
                "adaptive": False,
                "timeout": self.config.timeout,
                "enable_memory": self.config.enable_memory,
                "broadcast_task_to_all": self.config.broadcast_task_to_all,
            },
        )

        messages: dict[str, str] = {}
        total_tokens = 0
        errors: list[str] = []

        for step_idx, agent_id in enumerate(exec_order):
            agent = agent_lookup.get(agent_id)
            if agent is None:
                continue

            agent_name = agent_names.get(agent_id, agent_id)
            incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
            incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}

            include_query = self._should_include_query(agent_id, task_connected)
            memory_context = self._get_memory_context(agent_id)
            prompt = self._build_prompt(
                agent, query, incoming_messages, agent_names, memory_context, include_query=include_query
            )

            # prompt is now a StructuredPrompt β€” use .text for preview/streaming
            prompt_text = prompt.text

            # Emit agent start
            yield AgentStartEvent(
                run_id=run_id,
                agent_id=agent_id,
                agent_name=agent_name,
                step_index=step_idx,
                predecessors=incoming_ids,
                prompt_preview=prompt_text[: self.config.prompt_preview_length],
            )

            step_start = time.time()

            try:
                # Get caller for this specific agent (multi-model support)
                caller = self._get_caller_for_agent(agent_id, agent)
                if caller is None:
                    error_msg = f"No LLM caller available for agent {agent_id}"
                    errors.append(f"{agent_id}: {error_msg}")
                    messages[agent_id] = f"[Error: {error_msg}]"
                    yield AgentErrorEvent(
                        run_id=run_id,
                        agent_id=agent_id,
                        error_type="ValueError",
                        error_message=error_msg,
                        will_retry=False,
                    )
                    continue

                # Use streaming LLM if available and enabled
                if self.streaming_llm_caller and self.config.enable_token_streaming:
                    response_parts: list[str] = []
                    token_idx = 0

                    for token in self.streaming_llm_caller(prompt_text):
                        response_parts.append(token)
                        yield TokenEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            token=token,
                            token_index=token_idx,
                            is_first=(token_idx == 0),
                            is_last=False,
                        )
                        token_idx += 1

                    # Mark last token
                    if response_parts:
                        yield TokenEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            token="",
                            token_index=token_idx,
                            is_first=False,
                            is_last=True,
                        )

                    response = "".join(response_parts)
                    tokens = self.token_counter(prompt_text) + self.token_counter(response)
                else:
                    # Use regular LLM caller for this agent (with tools support)
                    # prompt (StructuredPrompt) is passed through β€” _run_agent_with_tools
                    # dispatches via _call_llm when structured_llm_caller is available
                    response, tokens = self._run_agent_with_tools(
                        caller=caller,
                        prompt=prompt,
                        agent=agent,
                    )

                messages[agent_id] = response
                total_tokens += tokens
                self._save_to_memory(agent_id, response, incoming_ids)

                is_final = (step_idx == len(exec_order) - 1) or (agent_id == final_agent_id)

                yield AgentOutputEvent(
                    run_id=run_id,
                    agent_id=agent_id,
                    agent_name=agent_name,
                    content=response,
                    tokens_used=tokens,
                    duration_ms=(time.time() - step_start) * 1000,
                    is_final=is_final,
                )

            except (TimeoutError, ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                error_msg = str(e)
                errors.append(f"{agent_id}: {error_msg}")
                messages[agent_id] = f"[Error: {e}]"

                yield AgentErrorEvent(
                    run_id=run_id,
                    agent_id=agent_id,
                    error_type=type(e).__name__,
                    error_message=error_msg,
                    will_retry=False,
                )

        final_id = self._determine_final_agent(final_agent_id, exec_order, messages)

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        yield RunEndEvent(
            run_id=run_id,
            success=len(errors) == 0,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            executed_agents=list(messages.keys()),
            errors=errors,
            agent_states=agent_states,
        )

    async def _astream_simple(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        *,
        update_states: bool | None,
    ) -> AsyncIterator[StreamEvent]:
        """
        Async streaming execution with optional parallel support.

        When ``config.enable_parallel`` is ``True``, independent agents
        (those whose predecessors have all completed) are executed
        concurrently via ``asyncio.gather``.  This is determined by
        :func:`get_parallel_groups` which partitions the topological
        order into dependency-based levels.

        When ``enable_parallel`` is ``False`` (or the graph is purely
        sequential), agents are executed one-by-one β€” identical to the
        synchronous ``_stream_simple`` but using async I/O.
        """
        run_id = str(uuid.uuid4())[:8]
        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            yield RunEndEvent(
                run_id=run_id, success=True, final_answer="", final_agent_id="", total_time=time.time() - start_time
            )
            return

        _task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        exec_order = build_execution_order(a_agents, agent_ids, role_graph.role_sequence)
        self._init_memory(agent_ids)

        # When parallel execution is enabled, partition agents into
        # dependency-based groups so independent agents run concurrently.
        if self.config.enable_parallel:
            groups = get_parallel_groups(a_agents, agent_ids)
        else:
            # Each agent is its own group β€” strictly sequential.
            groups = [[aid] for aid in exec_order]

        yield RunStartEvent(
            run_id=run_id,
            query=query,
            num_agents=len(exec_order),
            execution_order=exec_order,
            config_summary={
                "parallel": self.config.enable_parallel,
            },
        )

        messages: dict[str, str] = {}
        total_tokens = 0
        errors: list[str] = []
        step_idx = 0

        for group_idx, group in enumerate(groups):
            # Filter out unknown agents
            group_agents = [aid for aid in group if agent_lookup.get(aid) is not None]
            if not group_agents:
                continue

            # Emit ParallelStartEvent when the group has >1 agent
            is_parallel_group = self.config.enable_parallel and len(group_agents) > 1
            if is_parallel_group:
                yield ParallelStartEvent(
                    run_id=run_id,
                    agent_ids=group_agents,
                    group_index=group_idx,
                )

            # Emit AgentStartEvent for every agent in the group
            agent_prompts: dict[str, StructuredPrompt] = {}
            for agent_id in group_agents:
                agent = agent_lookup[agent_id]
                agent_name = agent_names.get(agent_id, agent_id)
                incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
                incoming_messages = {aid: messages[aid] for aid in incoming_ids if aid in messages}
                memory_context = self._get_memory_context(agent_id)
                prompt = self._build_prompt(agent, query, incoming_messages, agent_names, memory_context)
                agent_prompts[agent_id] = prompt

                yield AgentStartEvent(
                    run_id=run_id,
                    agent_id=agent_id,
                    agent_name=agent_name,
                    step_index=step_idx,
                    predecessors=incoming_ids,
                    prompt_preview=prompt.text[: self.config.prompt_preview_length],
                )
                step_idx += 1

            # ── Execute the group ─────────────────────────────────────
            if is_parallel_group:
                # Run all agents in the group concurrently
                async def _call_agent(aid: str, prompt: StructuredPrompt) -> tuple[str, str | None, str | None]:
                    """Returns (agent_id, response, error)."""
                    try:
                        resp = await asyncio.wait_for(
                            self._acall_llm(self.async_llm_caller, prompt),
                            timeout=self.config.timeout,
                        )
                    except (
                        TimeoutError,
                        ExecutionError,
                        ValueError,
                        TypeError,
                        KeyError,
                        RuntimeError,
                        OSError,
                    ) as exc:
                        return (aid, None, str(exc))
                    else:
                        return (aid, resp, None)

                results = await asyncio.gather(*[_call_agent(aid, agent_prompts[aid]) for aid in group_agents])

                successful: list[str] = []
                failed: list[str] = []
                for agent_id, response, error in results:
                    agent_name = agent_names.get(agent_id, agent_id)
                    if error is None and response is not None:
                        messages[agent_id] = response
                        prompt = agent_prompts[agent_id]
                        tokens = self.token_counter(prompt.text) + self.token_counter(response)
                        total_tokens += tokens
                        incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
                        self._save_to_memory(agent_id, response, incoming_ids)
                        successful.append(agent_id)

                        yield AgentOutputEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            agent_name=agent_name,
                            content=response,
                            tokens_used=tokens,
                            is_final=(agent_id == final_agent_id),
                        )
                    else:
                        errors.append(f"{agent_id}: {error}")
                        messages[agent_id] = f"[Error: {error}]"
                        failed.append(agent_id)

                        yield AgentErrorEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            error_type="ExecutionError",
                            error_message=error or "Unknown error",
                        )

                yield ParallelEndEvent(
                    run_id=run_id,
                    agent_ids=group_agents,
                    group_index=group_idx,
                    successful=successful,
                    failed=failed,
                )
            else:
                # Sequential execution β€” one agent at a time
                for agent_id in group_agents:
                    agent_name = agent_names.get(agent_id, agent_id)
                    prompt = agent_prompts[agent_id]
                    step_start = time.time()

                    try:
                        # Use async streaming LLM if available
                        if self.async_streaming_llm_caller and self.config.enable_token_streaming:
                            response_parts: list[str] = []
                            token_idx = 0

                            async for token in self.async_streaming_llm_caller(prompt.text):
                                response_parts.append(token)
                                yield TokenEvent(
                                    run_id=run_id,
                                    agent_id=agent_id,
                                    token=token,
                                    token_index=token_idx,
                                    is_first=(token_idx == 0),
                                    is_last=False,
                                )
                                token_idx += 1

                            if response_parts:
                                yield TokenEvent(
                                    run_id=run_id,
                                    agent_id=agent_id,
                                    token="",
                                    token_index=token_idx,
                                    is_first=False,
                                    is_last=True,
                                )

                            response = "".join(response_parts)
                        else:
                            if self.async_llm_caller is None and self.async_structured_llm_caller is None:
                                error_msg = f"No async LLM caller available for agent {agent_id}"
                                errors.append(f"{agent_id}: {error_msg}")
                                messages[agent_id] = f"[Error: {error_msg}]"
                                yield AgentErrorEvent(
                                    run_id=run_id,
                                    agent_id=agent_id,
                                    error_type="ValueError",
                                    error_message=error_msg,
                                )
                                continue
                            response = await asyncio.wait_for(
                                self._acall_llm(self.async_llm_caller, prompt),
                                timeout=self.config.timeout,
                            )

                        messages[agent_id] = response
                        tokens = self.token_counter(prompt.text) + self.token_counter(response)
                        total_tokens += tokens
                        incoming_ids = get_incoming_agents(agent_id, a_agents, agent_ids)
                        self._save_to_memory(agent_id, response, incoming_ids)

                        is_final = (agent_id == final_agent_id) or (
                            group_idx == len(groups) - 1 and agent_id == group_agents[-1]
                        )

                        yield AgentOutputEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            agent_name=agent_name,
                            content=response,
                            tokens_used=tokens,
                            duration_ms=(time.time() - step_start) * 1000,
                            is_final=is_final,
                        )

                    except (TimeoutError, ExecutionError, ValueError, TypeError, KeyError, RuntimeError, OSError) as e:
                        error_msg = str(e)
                        errors.append(f"{agent_id}: {error_msg}")
                        messages[agent_id] = f"[Error: {e}]"

                        yield AgentErrorEvent(
                            run_id=run_id,
                            agent_id=agent_id,
                            error_type=type(e).__name__,
                            error_message=error_msg,
                        )

        final_id = self._determine_final_agent(final_agent_id, exec_order, messages)

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        yield RunEndEvent(
            run_id=run_id,
            success=len(errors) == 0,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            executed_agents=list(messages.keys()),
            errors=errors,
            agent_states=agent_states,
        )

    def _stream_adaptive(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        *,
        update_states: bool | None,
    ) -> Iterator[StreamEvent]:
        """Adaptive streaming execution with conditional edges, pruning, and fallback."""
        if self._scheduler is None:
            msg = "Scheduler not initialized for adaptive mode"
            raise ValueError(msg)

        run_id = str(uuid.uuid4())[:8]
        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            yield RunEndEvent(run_id=run_id, success=True, total_time=0)
            return

        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        self._init_memory(agent_ids)
        p_matrix = self._extract_p_matrix(role_graph, task_idx)

        edge_conditions = self._get_edge_conditions(role_graph)
        condition_ctx = ConditionContext(
            source_agent="",
            target_agent="",
            messages={},
            step_results={},
            query=query,
        )

        plan = self._scheduler.build_plan(
            a_agents,
            agent_ids,
            p_matrix,
            end_agent=final_agent_id,
            edge_conditions=edge_conditions,
            condition_context=condition_ctx,
        )

        yield RunStartEvent(
            run_id=run_id,
            query=query,
            num_agents=len(agent_ids),
            execution_order=plan.execution_order,
            config_summary={"adaptive": True, "policy": self.config.routing_policy.value},
        )

        messages: dict[str, str] = {}
        step_results: dict[str, StepResult] = {}
        execution_order: list[str] = []
        fallback_attempts: dict[str, int] = {}
        topology_changed_count = 0
        errors: list[str] = []
        total_tokens = 0
        step_idx = 0

        while not plan.is_complete:
            step = plan.get_current_step()
            if step is None:
                break

            # Skip agents whose conditions were not met
            if step.agent_id in plan.condition_skipped:
                plan.advance()
                continue

            # Check for pruning
            should_prune, reason = self._scheduler.should_prune(
                step, plan, step_results.get(execution_order[-1]) if execution_order else None
            )

            if should_prune:
                plan.mark_skipped(step.agent_id)

                yield PruneEvent(
                    run_id=run_id,
                    agent_id=step.agent_id,
                    reason=reason,
                )
                continue

            agent = agent_lookup.get(step.agent_id)
            if agent is None:
                plan.advance()
                continue

            agent_name = agent_names.get(step.agent_id, step.agent_id)
            incoming = {p: messages[p] for p in step.predecessors if p in messages}
            memory_context = self._get_memory_context(step.agent_id)
            prompt = self._build_prompt(agent, query, incoming, agent_names, memory_context)

            yield AgentStartEvent(
                run_id=run_id,
                agent_id=step.agent_id,
                agent_name=agent_name,
                step_index=step_idx,
                predecessors=step.predecessors,
                prompt_preview=prompt.text[: self.config.prompt_preview_length],
            )

            step_start = time.time()
            result = self._execute_step(step, messages, agent_lookup, agent_names, query)
            step_results[step.agent_id] = result
            execution_order.append(step.agent_id)

            if result.success:
                messages[step.agent_id] = result.response or ""
                plan.mark_completed(step.agent_id, result.tokens_used)
                total_tokens += result.tokens_used
                self._save_to_memory(step.agent_id, result.response or "", step.predecessors)

                yield AgentOutputEvent(
                    run_id=run_id,
                    agent_id=step.agent_id,
                    agent_name=agent_name,
                    content=result.response or "",
                    tokens_used=result.tokens_used,
                    duration_ms=(time.time() - step_start) * 1000,
                )
            else:
                plan.mark_failed(step.agent_id)
                errors.append(f"{step.agent_id}: {result.error}")

                yield AgentErrorEvent(
                    run_id=run_id,
                    agent_id=step.agent_id,
                    error_type="ExecutionError",
                    error_message=result.error or "Unknown error",
                )

                # Handle fallback
                attempts = fallback_attempts.get(step.agent_id, 0)
                if self._scheduler.should_use_fallback(step, result, attempts):
                    for fb_agent in step.fallback_agents:
                        if fb_agent not in plan.completed and fb_agent not in plan.failed:
                            plan.insert_fallback(fb_agent, plan.current_index - 1)

                            yield FallbackEvent(
                                run_id=run_id,
                                failed_agent_id=step.agent_id,
                                fallback_agent_id=fb_agent,
                                attempt=attempts + 1,
                            )
                            break
                    fallback_attempts[step.agent_id] = attempts + 1

            # Topology pipeline: conditional edges + user hooks β†’ plan
            old_remaining = [s.agent_id for s in plan.remaining_steps]
            if self._run_topology_pipeline(
                plan,
                step.agent_id,
                a_agents,
                agent_ids,
                step_results,
                messages,
                query,
                execution_order,
                total_tokens,
                role_graph,
            ):
                topology_changed_count += 1
                new_remaining = [s.agent_id for s in plan.remaining_steps]
                if old_remaining != new_remaining:
                    yield TopologyChangedEvent(
                        run_id=run_id,
                        reason="Topology pipeline: conditional edges",
                        old_remaining=old_remaining,
                        new_remaining=new_remaining,
                        change_count=topology_changed_count,
                    )

            step_idx += 1

        final_id = self._determine_final_agent(final_agent_id, execution_order, messages)

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        yield RunEndEvent(
            run_id=run_id,
            success=len(errors) == 0,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            executed_agents=execution_order,
            errors=errors,
            agent_states=agent_states,
        )

    async def _astream_adaptive(  # noqa: PLR0912, PLR0915
        self,
        role_graph: Any,
        final_agent_id: str | None,
        *,
        update_states: bool | None,
    ) -> AsyncIterator[StreamEvent]:
        """Async adaptive streaming with parallel execution support."""
        if self._scheduler is None:
            msg = "Scheduler not initialized for adaptive mode"
            raise ValueError(msg)

        run_id = str(uuid.uuid4())[:8]
        start_time = time.time()

        base = self._prepare_base_context(role_graph)
        if base is None:
            yield RunEndEvent(run_id=run_id, success=True, total_time=0)
            return

        task_idx, a_agents, agent_ids, query, agent_lookup, agent_names = base

        self._init_memory(agent_ids)
        p_matrix = self._extract_p_matrix(role_graph, task_idx)

        edge_conditions = self._get_edge_conditions(role_graph)
        condition_ctx = ConditionContext(
            source_agent="",
            target_agent="",
            messages={},
            step_results={},
            query=query,
        )

        plan = self._scheduler.build_plan(
            a_agents,
            agent_ids,
            p_matrix,
            end_agent=final_agent_id,
            edge_conditions=edge_conditions,
            condition_context=condition_ctx,
        )

        yield RunStartEvent(
            run_id=run_id,
            query=query,
            num_agents=len(agent_ids),
            execution_order=plan.execution_order,
            config_summary={
                "adaptive": True,
                "parallel": self.config.enable_parallel,
                "policy": self.config.routing_policy.value,
            },
        )

        messages: dict[str, str] = {}
        step_results: dict[str, StepResult] = {}
        execution_order: list[str] = []
        fallback_attempts: dict[str, int] = {}
        topology_changed_count = 0
        errors: list[str] = []
        total_tokens = 0
        group_idx = 0

        while not plan.is_complete:
            parallel_group = self._get_parallel_group(plan, messages.keys())
            if not parallel_group:
                break

            # Filter condition-skipped and pruned steps
            valid_steps = []
            for step in parallel_group:
                # Skip agents whose conditions were not met
                if step.agent_id in plan.condition_skipped:
                    plan.advance()
                    continue

                should_prune, reason = self._scheduler.should_prune(step, plan, None)
                if should_prune:
                    plan.mark_skipped(step.agent_id)
                    yield PruneEvent(run_id=run_id, agent_id=step.agent_id, reason=reason)
                else:
                    valid_steps.append(step)

            if not valid_steps:
                # All steps in the group are skipped or pruned β€” break to avoid stalling.
                break

            # Emit parallel start event
            if self.config.enable_parallel and len(valid_steps) > 1:
                yield ParallelStartEvent(
                    run_id=run_id,
                    agent_ids=[s.agent_id for s in valid_steps],
                    group_index=group_idx,
                )

            # Emit agent start events
            for step in valid_steps:
                agent_name = agent_names.get(step.agent_id, step.agent_id)
                incoming = {p: messages[p] for p in step.predecessors if p in messages}
                agent = agent_lookup.get(step.agent_id)
                if agent:
                    memory_context = self._get_memory_context(step.agent_id)
                    prompt = self._build_prompt(agent, query, incoming, agent_names, memory_context)
                    yield AgentStartEvent(
                        run_id=run_id,
                        agent_id=step.agent_id,
                        agent_name=agent_name,
                        predecessors=step.predecessors,
                        prompt_preview=prompt.text[: self.config.prompt_preview_length],
                    )

            # Execute steps (parallel or sequential)
            if self.config.enable_parallel and len(valid_steps) > 1:
                results = await self._execute_parallel(valid_steps, messages, agent_lookup, agent_names, query)
            else:
                results = []
                for step in valid_steps:
                    r = await self._execute_step_async(step, messages, agent_lookup, agent_names, query)
                    results.append((step, r))

            # Process results and emit events
            successful: list[str] = []
            failed: list[str] = []

            for step, result in results:
                step_results[step.agent_id] = result
                execution_order.append(step.agent_id)
                agent_name = agent_names.get(step.agent_id, step.agent_id)

                if result.success:
                    messages[step.agent_id] = result.response or ""
                    plan.mark_completed(step.agent_id, result.tokens_used)
                    total_tokens += result.tokens_used
                    self._save_to_memory(step.agent_id, result.response or "", step.predecessors)
                    successful.append(step.agent_id)

                    yield AgentOutputEvent(
                        run_id=run_id,
                        agent_id=step.agent_id,
                        agent_name=agent_name,
                        content=result.response or "",
                        tokens_used=result.tokens_used,
                    )
                else:
                    plan.mark_failed(step.agent_id)
                    errors.append(f"{step.agent_id}: {result.error}")
                    failed.append(step.agent_id)

                    yield AgentErrorEvent(
                        run_id=run_id,
                        agent_id=step.agent_id,
                        error_message=result.error or "Unknown error",
                    )

                    # Handle fallback
                    attempts = fallback_attempts.get(step.agent_id, 0)
                    if self._scheduler.should_use_fallback(step, result, attempts):
                        for fb_agent in step.fallback_agents:
                            if fb_agent not in plan.completed and fb_agent not in plan.failed:
                                plan.insert_fallback(fb_agent, plan.current_index - 1)
                                yield FallbackEvent(
                                    run_id=run_id,
                                    failed_agent_id=step.agent_id,
                                    fallback_agent_id=fb_agent,
                                    attempt=attempts + 1,
                                )
                                break
                        fallback_attempts[step.agent_id] = attempts + 1

            # Emit parallel end event
            if self.config.enable_parallel and len(valid_steps) > 1:
                yield ParallelEndEvent(
                    run_id=run_id,
                    agent_ids=[s.agent_id for s in valid_steps],
                    group_index=group_idx,
                    successful=successful,
                    failed=failed,
                )

            # Topology pipeline for each executed agent in the group
            old_remaining = [s.agent_id for s in plan.remaining_steps]
            for step, _result in results:
                if await self._arun_topology_pipeline(
                    plan,
                    step.agent_id,
                    a_agents,
                    agent_ids,
                    step_results,
                    messages,
                    query,
                    execution_order,
                    total_tokens,
                    role_graph,
                ):
                    topology_changed_count += 1

            new_remaining = [s.agent_id for s in plan.remaining_steps]
            if old_remaining != new_remaining:
                yield TopologyChangedEvent(
                    run_id=run_id,
                    reason="Topology pipeline: conditional edges",
                    old_remaining=old_remaining,
                    new_remaining=new_remaining,
                    change_count=topology_changed_count,
                )

            group_idx += 1

        final_id = self._determine_final_agent(final_agent_id, execution_order, messages)

        do_update = update_states if update_states is not None else self.config.update_states
        agent_states = self._build_agent_states(messages, agent_lookup) if do_update else None

        yield RunEndEvent(
            run_id=run_id,
            success=len(errors) == 0,
            final_answer=messages.get(final_id, ""),
            final_agent_id=final_id,
            total_tokens=total_tokens,
            total_time=time.time() - start_time,
            executed_agents=execution_order,
            errors=errors,
            agent_states=agent_states,
        )

    def stream_to_result(
        self,
        role_graph: Any,
        final_agent_id: str | None = None,
        *,
        update_states: bool | None = None,
    ) -> tuple[Iterator[StreamEvent], MACPResult]:
        """
        Stream execution and also return final MACPResult.

        Useful when you want both streaming display and complete result.

        Returns:
            Tuple of (event iterator, MACPResult)

        Example:
            stream, result_future = runner.stream_to_result(graph)
            for event in stream:
                print(event)
            result = result_future  # Available after stream exhausted

        """
        events: list[StreamEvent] = []
        messages: dict[str, str] = {}
        final_answer = ""
        final_agent = ""
        execution_order: list[str] = []
        total_tokens = 0
        total_time = 0.0
        errors_list: list[str] = []

        def collecting_stream() -> Iterator[StreamEvent]:
            nonlocal final_answer, final_agent, total_tokens, total_time, errors_list

            for event in self.stream(role_graph, final_agent_id, update_states=update_states):
                events.append(event)

                if isinstance(event, AgentOutputEvent):
                    messages[event.agent_id] = event.content
                    execution_order.append(event.agent_id)

                elif isinstance(event, RunEndEvent):
                    final_answer = event.final_answer
                    final_agent = event.final_agent_id
                    total_tokens = event.total_tokens
                    total_time = event.total_time
                    errors_list = event.errors

                yield event

        stream = collecting_stream()

        # Create a lazy result that becomes valid after stream is exhausted
        class LazyResult:
            def __init__(self, runner: MACPRunner):
                self._runner = runner
                self._result: MACPResult | None = None

            def __getattr__(self, name: str) -> Any:
                if self._result is None:
                    self._result = MACPResult(
                        messages=messages,
                        final_answer=final_answer,
                        final_agent_id=final_agent,
                        execution_order=execution_order,
                        total_tokens=total_tokens,
                        total_time=total_time,
                        errors=[ExecutionError(message=e, agent_id="", recoverable=False) for e in errors_list]
                        if errors_list
                        else None,
                    )
                return getattr(self._result, name)

        # LazyResult provides a proxy to access result attributes lazily
        lazy_result: MACPResult = LazyResult(self)  # type: ignore[assignment]
        return stream, lazy_result