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
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
use anyhow::Result;
use serde_json::Value;
/// Bridges a `DwAgent` flow node into the agentic-worker runtime.
///
/// The concrete impl (constructed in the runner binary, Task 4.3) wraps
/// `greentic_aw_runtime::AgentRuntime`. The engine holds it as a trait
/// object so `engine.rs` stays free of AW-runtime construction details.
#[async_trait::async_trait]
pub trait AgentNodeHandler: Send + Sync {
/// Execute one agentic step. `flow_input` is the upstream node's
/// JSON payload (expects at least `{"user_text": "..."}`); returns
/// the node output JSON (`{"reply", "trail", "terminated_by"}`).
///
/// `conversational` is the flow node's `conversational` flag (SP3): when
/// true the agent is offered the host `end_conversation` tool so it can end
/// the segment the engine park-loop maintains, regardless of the agent's
/// own config default.
///
/// `caller` is the block the messaging provider verified for this run,
/// carried on `FlowContext` rather than inside `flow_input` — see
/// [`crate::caller_identity`] for why identity must not arrive through a
/// flow's own node mapping. `None` means the turn is anonymous, which is
/// what every provider predating the contract produces.
// `caller` is deliberately its own argument rather than a field folded
// into `flow_input` (authorable) — so this lane, which also carries
// `conversational`, crosses clippy's seven-argument line.
#[allow(clippy::too_many_arguments)]
async fn execute(
&self,
tenant_id: &str,
env_id: &str,
agent_id: &str,
session_id: &str,
flow_input: &Value,
conversational: bool,
caller: Option<&Value>,
) -> Result<Value>;
/// [`Self::execute`] plus the user's answer to a `flow:` tool that parked
/// the previous turn on a card (`terminated_by == "awaiting_tool_input"`).
///
/// `resume_payload` is the raw inbound activity (the flow's `entry`) when
/// the engine is re-entering this node from such a park and the activity
/// is a card submit; `None` otherwise. It is its own argument — like
/// `caller`, and for the same reason — rather than a key inside the
/// authorable `flow_input`.
///
/// The default ignores it and runs [`Self::execute`], which keeps every
/// existing implementor source-compatible; such a handler never produces
/// `awaiting_tool_input`, so it is never handed a payload it would need.
#[allow(clippy::too_many_arguments)]
async fn execute_with_resume(
&self,
tenant_id: &str,
env_id: &str,
agent_id: &str,
session_id: &str,
flow_input: &Value,
conversational: bool,
caller: Option<&Value>,
resume_payload: Option<&Value>,
) -> Result<Value> {
let _ = resume_payload;
self.execute(
tenant_id,
env_id,
agent_id,
session_id,
flow_input,
conversational,
caller,
)
.await
}
}
// ---------------------------------------------------------------------------
// agentic-worker feature: full DwAgent / AgentRuntime integration
// ---------------------------------------------------------------------------
#[cfg(feature = "agentic-worker")]
mod aw {
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use anyhow::Result;
use greentic_aw_runtime::config::AgentConfig;
use greentic_aw_runtime::config_provider::ConfigProvider;
use greentic_aw_runtime::error::{AgentError, ConfigError};
use greentic_aw_runtime::guardrail::GuardrailDirection;
use greentic_aw_runtime::{AgentInput, AgentRuntime, AgentStep, StepObserver, TenantContext};
use serde_json::{Value, json};
use crate::trace::agent_audit::AgentAuditObserver;
use crate::trace::audit_event::{build_agent_run_metering_event, metering_subject};
use crate::trace::audit_sink::AuditSink;
use crate::trace::generate_audit_event_id;
use super::AgentNodeHandler;
// -----------------------------------------------------------------------
// Pack-manifest agent helpers
// -----------------------------------------------------------------------
/// Deserialize raw agent blobs from a pack manifest into typed
/// [`AgentConfig`] structs.
///
/// Malformed blobs are skipped with a [`tracing::warn!`] so a single
/// bad entry never prevents other agents (or pack-level operators) from
/// loading. The `pack_id` argument is used only in log messages.
pub fn agent_configs_from_manifest(
pack_id: &str,
blobs: &std::collections::BTreeMap<String, Value>,
) -> HashMap<String, AgentConfig> {
blobs
.iter()
.filter_map(|(agent_id, blob)| {
match serde_json::from_value::<AgentConfig>(blob.clone()) {
Ok(config) => Some((agent_id.clone(), config)),
Err(deserialize_error) => {
tracing::warn!(
pack_id,
agent_id,
error = %deserialize_error,
"skipping malformed agent blob in pack manifest"
);
None
}
}
})
.collect()
}
/// Merge pack-provided agent configs with operator-declared ones.
///
/// Pack agents form the base layer; operator entries take precedence on
/// `agent_id` collision (operator always wins). This ensures operators can
/// override or refine any pack-embedded agent without touching the pack
/// itself.
pub fn merge_agent_sources(
pack_agents: HashMap<String, AgentConfig>,
operator_agents: HashMap<String, AgentConfig>,
) -> HashMap<String, AgentConfig> {
let mut merged = pack_agents;
for (agent_id, operator_config) in operator_agents {
merged.insert(agent_id, operator_config);
}
merged
}
/// Fill `blobs` from a `dw-agents.json` `sidecar` map, inserting each entry only
/// when its agent_id is absent — so `manifest.agents` stays authoritative and the
/// sidecar only bridges packs whose manifest could not carry agents.
pub fn merge_sidecar_into(
blobs: &mut std::collections::BTreeMap<String, serde_json::Value>,
sidecar: std::collections::BTreeMap<String, serde_json::Value>,
) {
for (agent_id, blob) in sidecar {
blobs.entry(agent_id).or_insert(blob);
}
}
/// Fixed, user-safe reply returned when an agentic step fails. The detailed
/// [`greentic_aw_runtime::AgentError`] is logged but never surfaced to the
/// flow output, so internal failure modes do not leak to end users.
const SANITISED_ERROR_REPLY: &str = "Something went wrong. Please try again.";
/// A turn failed (an LLM error, a lock timeout) while the agent still holds
/// a parked `flow:` tool: turn the sanitised error output into a park that
/// re-offers the card. The engine then keeps its await armed, so the user's
/// next card submit resumes the tool instead of being read as typed text.
fn reoffer_parked_card(out: &mut Value, card: Value) {
out["terminated_by"] = json!("awaiting_tool_input");
out["pending_presentation"] = card;
out["side_turn"] = json!(true);
}
/// Build the structured JSON output emitted by a `DwAgent` node when a
/// guardrail blocks the step.
///
/// The returned value gives the downstream flow a machine-readable signal
/// it can branch on (`guardrail.blocked == true`, `terminated_by ==
/// "guardrail_denied"`) without leaking raw internal error details.
///
/// - `direction` — inbound (user→agent) or outbound (agent→user)
/// - `code` — guardrail-defined denial code (e.g. `"permission_denied"`)
/// - `message` — human-readable denial reason surfaced to the user
/// - `details` — optional JSON string with additional context; parsed into a
/// structured value when present, omitted (null) otherwise
pub(super) fn guardrail_denied_json(
direction: GuardrailDirection,
code: &str,
message: &str,
details: Option<&str>,
) -> Value {
let details_val =
details.and_then(|detail_str| serde_json::from_str::<Value>(detail_str).ok());
json!({
"guardrail": {
"blocked": true,
"direction": direction.as_str(),
"code": code,
"message": message,
"details": details_val,
},
"reply": message,
"trail": Vec::<AgentStep>::new(),
"terminated_by": "guardrail_denied",
})
}
/// Build an [`HttpGuardrailPolicy`] from `GREENTIC_AW_ADMIN_ENDPOINT` +
/// `GREENTIC_AW_ADMIN_TOKEN` (the same pair the agent registry uses).
/// Returns `None` when either is unset/empty, so a non-admin deploy
/// enforces no mandatory policy (today's behavior).
fn guardrail_policy_from_env()
-> Option<greentic_aw_runtime::guardrail_provider::HttpGuardrailPolicy> {
let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
.ok()
.filter(|s| !s.is_empty())?;
let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
.ok()
.filter(|s| !s.is_empty())?;
Some(greentic_aw_runtime::guardrail_provider::HttpGuardrailPolicy::new(endpoint, token))
}
/// Production [`AgentNodeHandler`] wrapping the agentic-worker runtime.
///
/// Holds a shared [`AgentRuntime`] and translates a `DwAgent` flow node's
/// JSON payload into an [`AgentInput`], invoking one Plan-Act-Observe step
/// per call. Construction (Task 4.3b) lives in the runner binary; the engine
/// only ever sees this through the [`AgentNodeHandler`] trait object.
pub struct RuntimeAgentNodeHandler {
runtime: Arc<AgentRuntime>,
/// Best-effort agent-step audit sink (EPIC-B B-3). `None` — the
/// default when no NATS audit client is configured
/// (`GREENTIC_EVENTS_NATS_URL` unset/unreachable) — keeps `execute`
/// on the plain [`AgentRuntime::step`] path, byte-identical to the
/// behaviour before this observer existed.
audit_sink: Option<AuditSink>,
/// Session-keyed streaming-observer registry (R2). `None` — the
/// default when no registry was wired in — keeps `execute` from
/// looking up a stream observer at all. When `Some`, `execute` looks
/// up `session_id` in the registry on every call; a miss (no active
/// SSE stream for that session) behaves exactly like `None`.
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
/// Identity of the deployed unit these agents were loaded from — the
/// revision's `bundle_id`, stamped onto every step's
/// [`TenantContext`] so billing can attribute spend to a project.
///
/// `None` on the tenant-only (legacy, non-revision) pack path, where no
/// bundle is pinned. Billing then OMITS the `project_id` dimension
/// rather than substituting the agent id, which is not unique across
/// packs — see [`greentic_aw_runtime::TenantContext::project_id`].
project_id: Option<String>,
}
impl RuntimeAgentNodeHandler {
/// Wrap a shared [`AgentRuntime`] in a flow-node handler. `audit_sink`
/// is `Some` only when a NATS audit client was configured; `execute`
/// then drives the step via [`AgentRuntime::step_with_observer`] with
/// an [`AgentAuditObserver`] so tool calls/results are published to
/// `audit.<tenant>.agent.<event>`. When `None`, `execute` uses
/// [`AgentRuntime::step`] directly (no observer, no behaviour change).
///
/// `stream_observers` (R2) is the session-keyed registry a
/// `POST /agent/chat/stream` handler inserts into before dispatching a
/// turn; `execute` looks up `session_id` in it and, when present, fans
/// the step's token/tool callbacks out to that observer alongside the
/// audit observer (via [`crate::http::agent_stream::CompositeObserver`]
/// when both are present).
///
/// `project_id` is the deployed unit's `bundle_id` (`None` on the
/// legacy tenant-only path); it becomes the `project_id` billing
/// dimension of every step this handler runs.
pub fn new(
runtime: Arc<AgentRuntime>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
) -> Self {
Self {
runtime,
audit_sink,
stream_observers,
project_id,
}
}
}
/// Build a [`greentic_types::TenantCtx`] for the agent-audit observer from
/// the flow node's plain `tenant_id`/`env_id` strings. Mirrors
/// `HostConfig::tenant_ctx`'s fallback-to-"local" pattern: an id that fails
/// the newtype's validation (which should not happen once a flow has been
/// routed to a tenant) still yields a well-formed `TenantCtx` rather than
/// panicking — the audit event is best-effort, never load-bearing.
fn tenant_ctx_for_audit(tenant_id: &str, env_id: &str) -> greentic_types::TenantCtx {
let env = greentic_types::EnvId::from_str(env_id)
.unwrap_or_else(|_| greentic_types::EnvId::new("local").expect("local env id"));
let tenant = greentic_types::TenantId::from_str(tenant_id)
.unwrap_or_else(|_| greentic_types::TenantId::new("local").expect("local tenant id"));
greentic_types::TenantCtx::new(env, tenant)
}
#[async_trait::async_trait]
impl AgentNodeHandler for RuntimeAgentNodeHandler {
async fn execute(
&self,
tenant_id: &str,
env_id: &str,
agent_id: &str,
session_id: &str,
flow_input: &Value,
conversational: bool,
caller: Option<&Value>,
) -> Result<Value> {
self.execute_with_resume(
tenant_id,
env_id,
agent_id,
session_id,
flow_input,
conversational,
caller,
None,
)
.await
}
async fn execute_with_resume(
&self,
tenant_id: &str,
env_id: &str,
agent_id: &str,
session_id: &str,
flow_input: &Value,
conversational: bool,
caller: Option<&Value>,
resume_payload: Option<&Value>,
) -> Result<Value> {
let user_text = flow_input
.get("user_text")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
// A block the provider stamped but this runtime cannot decode is
// NOT silently treated as verified: the decode failure warns and
// the turn proceeds anonymously, which is the restrictive
// direction and the same state a provider that stamped nothing
// produces.
let verified_caller = caller.and_then(|block| {
match serde_json::from_value::<greentic_aw_runtime::VerifiedCaller>(block.clone()) {
Ok(caller) => Some(caller),
Err(error) => {
tracing::warn!(
%error,
"provider stamped a caller block this runtime cannot decode; \
running the turn anonymously"
);
None
}
}
});
let tenant = TenantContext::new(tenant_id, env_id)
.with_project_id(self.project_id.clone())
.with_caller(verified_caller);
let tenant_for_card = tenant.clone();
let input = AgentInput {
text: user_text,
conversational,
resume_payload: resume_payload.cloned(),
};
// Off by default: with neither an audit sink nor a registered
// stream observer, this is exactly the pre-existing
// `self.runtime.step(...)` call — no observer is constructed and
// behaviour is byte-identical to before EPIC-B B-3 / R2.
let mut observers: Vec<Arc<dyn StepObserver>> = Vec::new();
if let Some(sink) = &self.audit_sink {
observers.push(Arc::new(AgentAuditObserver::new(
sink.clone(),
tenant_ctx_for_audit(tenant_id, env_id),
agent_id.to_string(),
session_id.to_string(),
)));
}
if let Some(reg) = &self.stream_observers
&& let Some(entry) = reg.get(session_id)
{
observers.push(entry.value().clone());
}
// Shared context (Phase A2): this is the ONE place the run's first
// context opens — fresh trace, read-write, bound to this step's
// tenant. It does not set the caller policy; `run_step` does that
// for every agent turn, including ones that never come through this
// handler (graph turns, playbook turns, designer hosts).
let open_run_context =
crate::runner::run_context_policy::should_open_scope(&self.runtime, agent_id);
let step = async move {
match observers.len() {
0 => self.runtime.step(tenant, session_id, agent_id, input).await,
1 => {
self.runtime
.step_with_observer(
tenant,
session_id,
agent_id,
input,
observers.remove(0),
)
.await
}
_ => {
let composite: Arc<dyn StepObserver> =
Arc::new(crate::http::agent_stream::CompositeObserver::new(observers));
self.runtime
.step_with_observer(tenant, session_id, agent_id, input, composite)
.await
}
}
};
let step_result = if open_run_context {
greentic_aw_runtime::RunContext::scope(
greentic_aw_runtime::RunContext::new(
tenant_id,
Arc::new(greentic_aw_runtime::RunTrace::new()),
),
step,
)
.await
} else {
step.await
};
match step_result {
Ok(output) => {
// Best-effort per-run metering event (EPIC-D D-1), emitted
// alongside (never instead of) the per-step agent-audit
// events above. Off by default: with no audit sink
// configured, no metering event is built or sent — this
// mirrors the audit-sink "off" branch's byte-identical
// behaviour above.
if let Some(sink) = &self.audit_sink {
let tenant_ctx = tenant_ctx_for_audit(tenant_id, env_id);
sink.emit(
metering_subject(tenant_id),
&build_agent_run_metering_event(
&tenant_ctx,
agent_id,
output.trail.len(),
chrono::Utc::now(),
generate_audit_event_id(),
),
);
}
let mut node_output = json!({
"reply": output.reply,
"trail": output.trail,
"terminated_by": output.terminated_by,
"usage": output.usage,
});
// Present only while a `flow:` tool is parked on the user
// (`terminated_by == "awaiting_tool_input"`): the card the
// engine renders as this turn's output in place of `reply`.
if let Some(presentation) = output.pending_presentation {
node_output["pending_presentation"] = presentation;
}
// A typed message answered while the tool stays parked:
// `reply` is the answer and the card follows it.
if output.side_turn {
node_output["side_turn"] = json!(true);
}
Ok(node_output)
}
Err(AgentError::GuardrailDenied {
direction,
code,
message,
details,
}) => {
// Surface guardrail denials as a structured, machine-readable
// node output so flows can branch on `guardrail.blocked`.
// The denial code and message are intentionally visible to
// the flow (they are governance messages, not internal detail).
tracing::info!(
agent_id,
session_id,
%code,
"DwAgent blocked by guardrail"
);
Ok(guardrail_denied_json(
direction,
&code,
&message,
details.as_deref(),
))
}
Err(error) => {
// Never leak the internal AgentError to the flow output. Log
// the detail for operators; return a sanitised reply only.
tracing::warn!(error = %error, agent_id, session_id, "DwAgent step failed");
let mut out = json!({
"reply": SANITISED_ERROR_REPLY,
"trail": Vec::<AgentStep>::new(),
"terminated_by": "error",
});
// Opt-in diagnostic: surface the internal error detail (never
// part of the user-facing reply) when `GREENTIC_AGENT_ERROR_DETAIL`
// is truthy, so an operator debugging the offline Test-chat
// sidecar sees the real cause instead of only "Something went
// wrong". The runner's telemetry `main` exports tracing to OTLP,
// not stderr, so the `warn!` above is otherwise invisible.
if std::env::var("GREENTIC_AGENT_ERROR_DETAIL")
.map(|v| matches!(v.trim(), "1" | "true" | "yes" | "on"))
.unwrap_or(false)
{
out["error_detail"] = json!(format!("{error} || {error:?}"));
}
if let Some(card) = self.runtime.parked_card(&tenant_for_card, session_id).await
{
reoffer_parked_card(&mut out, card);
}
Ok(out)
}
}
}
}
/// [`ConfigProvider`] backed by the operator's [`HostConfig::agents`] map.
///
/// Agents are operator-global for the MVP: lookup is keyed purely by
/// `agent_id`; the `tenant`/`env` arguments are accepted (to satisfy the
/// trait contract) but not used for keying. This avoids a tenant/env
/// key-matching footgun against the dispatch path, which derives those
/// values independently. A future per-tenant config source can replace
/// this implementation without touching callers.
pub struct HostConfigProvider {
agents: HashMap<String, AgentConfig>,
}
impl HostConfigProvider {
/// Wrap the operator-declared agents map in a [`ConfigProvider`].
pub fn new(agents: HashMap<String, AgentConfig>) -> Self {
Self { agents }
}
}
impl ConfigProvider for HostConfigProvider {
fn agent_config<'a>(
&'a self,
_tenant: &'a TenantContext,
agent_id: &'a str,
) -> Pin<Box<dyn Future<Output = Result<AgentConfig, ConfigError>> + Send + 'a>> {
let found = self.agents.get(agent_id).cloned();
let agent_id_owned = agent_id.to_string();
Box::pin(async move { found.ok_or(ConfigError::AgentNotFound(agent_id_owned)) })
}
}
/// Resolve the extension discovery directory for tool dispatch.
///
/// Honours `GREENTIC_EXTENSIONS_DIR`; otherwise falls back to
/// `~/.greentic/extensions` (the platform convention), and finally to a
/// temp-dir path when no home directory can be resolved. A missing or
/// empty directory is harmless — `list_tools`/`invoke_tool` simply return
/// empty/NotFound, which is correct for tool-less agents.
fn extension_discovery_dir() -> PathBuf {
if let Ok(dir) = std::env::var("GREENTIC_EXTENSIONS_DIR")
&& !dir.is_empty()
{
return PathBuf::from(dir);
}
if let Some(home) = std::env::var_os("HOME") {
return PathBuf::from(home).join(".greentic").join("extensions");
}
std::env::temp_dir().join("greentic").join("extensions")
}
/// Resolve the directory scanned for `<agent_id>.json` Digital Worker manifests.
///
/// Honours `GREENTIC_AGENT_MANIFESTS_DIR`; otherwise `~/.greentic/agents`, and
/// finally a temp-dir path when no home is resolvable (keeps the fn total). A
/// missing dir is harmless — the overlay provider simply finds no manifest and
/// returns the YAML base unchanged.
fn manifests_discovery_dir() -> PathBuf {
if let Ok(dir) = std::env::var("GREENTIC_AGENT_MANIFESTS_DIR")
&& !dir.is_empty()
{
return PathBuf::from(dir);
}
if let Some(home) = std::env::var_os("HOME") {
return PathBuf::from(home).join(".greentic").join("agents");
}
std::env::temp_dir().join("greentic").join("agents")
}
/// Build an [`HttpConfigProvider`] from `GREENTIC_AW_ADMIN_ENDPOINT` +
/// `GREENTIC_AW_ADMIN_TOKEN`. Returns `None` when either is unset/empty, so
/// the runtime keeps using the local overlay alone.
fn registry_from_env() -> Option<greentic_aw_runtime::HttpConfigProvider> {
let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
.ok()
.filter(|s| !s.is_empty())?;
let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
.ok()
.filter(|s| !s.is_empty())?;
Some(greentic_aw_runtime::HttpConfigProvider::new(
endpoint, token,
))
}
/// Build an [`McpToolSource`] from the same admin endpoint/token the agent
/// registry uses (`GREENTIC_AW_ADMIN_ENDPOINT` + `GREENTIC_AW_ADMIN_TOKEN`).
///
/// MCP tools are ON by default whenever the admin credentials are present:
/// exposure is already authorized twice upstream (the tenant registers the
/// server with the `agentic_worker` role in admin, and the agent's
/// allowlist must explicitly reference `mcp:<server_id>`), so a configured
/// runner participates without extra ceremony. `GREENTIC_AW_MCP=0` is the
/// operator opt-out escape hatch for environments where outbound calls to
/// tenant-registered MCP servers must stay disabled. Returns `None` on
/// opt-out or when either credential is missing/empty.
///
/// `secrets`, when `Some`, is threaded into [`McpToolSource::with_secrets`]
/// so `local-wasm` tools dispatched from this source's catalogs can read
/// their tenant credentials. Callers with no per-tenant secrets context
/// (the process-level serve path) pass `None`, matching prior behavior.
///
/// [`McpToolSource`]: greentic_aw_runtime::McpToolSource
/// [`McpToolSource::with_secrets`]: greentic_aw_runtime::McpToolSource::with_secrets
pub(crate) fn mcp_source_from_env(
secrets: Option<crate::secrets::DynSecretsManager>,
) -> Option<Arc<greentic_aw_runtime::McpToolSource>> {
if std::env::var("GREENTIC_AW_MCP").ok().as_deref() == Some("0") {
tracing::info!("GREENTIC_AW_MCP=0; MCP tool source disabled");
return None;
}
let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
.ok()
.filter(|s| !s.is_empty())?;
let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
.ok()
.filter(|s| !s.is_empty())?;
tracing::info!(endpoint = %endpoint, "MCP tool source constructed");
let source = match secrets {
Some(manager) => {
greentic_aw_runtime::McpToolSource::with_secrets(endpoint, token, manager)
}
None => greentic_aw_runtime::McpToolSource::new(endpoint, token),
};
Some(Arc::new(source))
}
/// Build the MCP tool source from the route material the operator's loaded
/// packs carry in `assets/mcp-routes.json`, for a deployed runner that has
/// no admin credentials.
///
/// Mirrors [`component_source_from_packs`] and [`flow_source_from_packs`]:
/// discover from the packs rather than a remote admin. It is the FALLBACK
/// behind [`mcp_source_from_env`], never a replacement — see the precedence
/// note at the two construction sites.
///
/// Honours the same `GREENTIC_AW_MCP=0` opt-out as [`mcp_source_from_env`]:
/// an operator who disabled outbound MCP must not have it re-enabled by a
/// pack. Returns `None` when disabled, when no pack is loaded, or when no
/// loaded pack declares any route — so `mcp:` tool refs then resolve from
/// their `ToolRef` contract for the LLM tool list and report an honest
/// "unknown mcp tool" if actually called.
///
/// Route ids are deduplicated across packs, first pack wins. Server ids are
/// tenant-scoped in the admin, so a collision between two packs of the same
/// tenant means the same server; a collision across tenants in one host is
/// pre-existing and not made worse here (spec §11 O-3).
///
/// The dedup cannot mix UNITS: `packs` is one revision's pack list (the
/// runtime is built per `TenantRuntime`, i.e. per deployed unit), so every
/// record here belongs to the unit named by `unit`. `unit` is that
/// revision's `bundle_id` and scopes the credential read (see
/// [`greentic_aw_runtime::mcp_secrets::read_mcp_secret_for_unit`]); `None`
/// on the legacy tenant-only runtime keeps the team / `_` lookup exactly.
/// The secrets manager an agent's `mcp:` tools resolve their credential
/// with — the injected host manager, UNLESS `SECRETS_BACKEND` explicitly
/// names one.
///
/// # Why this is not simply the injected manager
///
/// It was, and that made the pack-backed MCP path unreachable in the lane
/// it was built for. `greentic-start` injects its own manager
/// (`HostBuilder::with_secrets_manager`, `revision_boot.rs`) whose kind is
/// one of `dev-store` / `env` / `vault` — there is no broker variant — and
/// greentic-designer's `orchestrate::mcp_runtime` projects
/// `SECRETS_BACKEND=broker` + the two `SECRETS_BROKER_*` variables onto
/// exactly that child. So the operator asked for a broker, the projection
/// arrived intact, and the agent loop resolved against a manager that had
/// never heard of it: every `mcp:` tool failed with "no credential at
/// secrets://…", having sent no request to the broker at all. Verified end
/// to end on 2026-08-21 (greentic-designer `docs/superpowers/specs/
/// 2026-08-20-aw-mcp-in-deployed-bundles-design.md`, the Slice 8 note).
///
/// The flow-node path had the SAME problem and was not fixed alongside
/// this one: it built its own manager from `SECRETS_BACKEND` and ignored
/// the injected one, so every `mcp` node in a Cloud Run or Kubernetes
/// deployment failed on a credential it never looked for in the right
/// store. This comment previously asserted the opposite, which is why that
/// went unnoticed for the life of #706. Both paths now share
/// [`crate::runner::mcp_node::aw::choose_mcp_secrets`].
///
/// # Why it is gated on the variable being SET
///
/// An unset `SECRETS_BACKEND` must keep the injected manager, or every host
/// that deliberately supplies one — the designer's in-process host, a
/// greentic-start pod on Vault — would be silently downgraded to the `env`
/// backend, which `SecretsBackend::from_env` returns for an absent value.
/// That would break working deployments to fix a broken one. The variable
/// being present is the operator's explicit instruction, and only then does
/// it win.
///
/// A failure to build from the variable falls back to the injected manager
/// rather than to nothing: a malformed broker endpoint should degrade to
/// the host's own resolution, not strip the agent of every credential.
pub(crate) fn mcp_secrets_manager(
injected: &crate::secrets::DynSecretsManager,
) -> crate::secrets::DynSecretsManager {
let requested = std::env::var("SECRETS_BACKEND").ok();
crate::runner::mcp_node::aw::choose_mcp_secrets(
requested.as_deref(),
crate::runner::mcp_node::aw::secrets_from_env(),
Some(injected),
)
// `choose_mcp_secrets` returns `None` only when nothing at all is
// available, and `injected` is `Some` here by construction.
.unwrap_or_else(|| injected.clone())
}
pub(crate) fn mcp_source_from_packs(
packs: &[Arc<crate::pack::PackRuntime>],
tenant: &str,
secrets: Option<crate::secrets::DynSecretsManager>,
unit: Option<&str>,
) -> Option<Arc<greentic_aw_runtime::McpToolSource>> {
if std::env::var("GREENTIC_AW_MCP").ok().as_deref() == Some("0") {
tracing::info!("GREENTIC_AW_MCP=0; pack-backed MCP tool source disabled");
return None;
}
if packs.is_empty() {
return None;
}
let mut seen = std::collections::HashSet::new();
let mut records = Vec::new();
for pack in packs {
let Some(routes) = pack.mcp_routes() else {
continue;
};
for route in routes.iter() {
if !seen.insert(route.server_id.clone()) {
continue;
}
records.push(greentic_aw_runtime::McpPackRoute {
server_id: route.server_id.clone(),
transport: route.transport.clone(),
transport_url: route.transport_url.clone(),
auth_header_name: route.auth_header_name.clone(),
auth_team: route.auth_team.clone(),
component_ref: route.component_ref.clone(),
component_version: route.component_version.clone(),
component_digest: route.component_digest.clone(),
});
}
}
if records.is_empty() {
return None;
}
tracing::info!(
tenant = %tenant,
servers = records.len(),
"pack-backed MCP tool source constructed"
);
Some(Arc::new(
greentic_aw_runtime::McpToolSource::from_pack_routes(records, secrets)
.with_unit(unit.map(str::to_string)),
))
}
/// Build the component tool source from the operator's loaded packs, gated
/// by `GREENTIC_AW_COMPONENT_TOOLS` (set to "0" to disable). Returns `None`
/// when disabled or when no packs are loaded, so `component:` tool refs then
/// resolve to nothing. Mirrors [`mcp_source_from_env`] but discovers tools
/// from in-pack components rather than a remote admin.
pub(crate) fn component_source_from_packs(
packs: &[Arc<crate::pack::PackRuntime>],
tenant: &str,
) -> Option<Arc<greentic_aw_runtime::ComponentToolSource>> {
if std::env::var("GREENTIC_AW_COMPONENT_TOOLS").ok().as_deref() == Some("0") {
tracing::info!("GREENTIC_AW_COMPONENT_TOOLS=0; component tool source disabled");
return None;
}
if packs.is_empty() {
return None;
}
let invoker = Arc::new(
crate::runner::component_invoker::PackRuntimeComponentInvoker::new(
packs.to_vec(),
tenant.to_string(),
),
);
tracing::info!(tenant = %tenant, packs = packs.len(), "component tool source constructed");
Some(Arc::new(greentic_aw_runtime::ComponentToolSource::new(
invoker,
)))
}
/// Build the flow tool source from the operator's loaded packs, gated by
/// `GREENTIC_AW_FLOW_TOOLS` (set to "0" to disable). Returns `None` when
/// disabled or when no packs are loaded, so `flow:` tool refs then resolve
/// to nothing. Mirrors [`component_source_from_packs`] but discovers tools
/// from in-pack flows rather than in-pack components.
pub(crate) fn flow_source_from_packs(
packs: &[Arc<crate::pack::PackRuntime>],
tenant: &str,
) -> Option<Arc<greentic_aw_runtime::FlowToolSource>> {
if std::env::var("GREENTIC_AW_FLOW_TOOLS").ok().as_deref() == Some("0") {
tracing::info!("GREENTIC_AW_FLOW_TOOLS=0; flow tool source disabled");
return None;
}
if packs.is_empty() {
return None;
}
let invoker = Arc::new(crate::runner::flow_invoker::PackRuntimeFlowInvoker::new(
packs.to_vec(),
tenant.to_string(),
));
tracing::info!(tenant = %tenant, packs = packs.len(), "flow tool source constructed");
Some(Arc::new(greentic_aw_runtime::FlowToolSource::new(invoker)))
}
/// Build the sorla (SoR BusinessAction) tool source from a configured
/// SoRX deployment, gated by `GREENTIC_AW_SORLA_TOOLS` (set to "0" to
/// disable) and addressed by `GREENTIC_AW_SORX_URL`. Returns `None` when
/// disabled or when no SoRX URL is configured, so `sorla:` tool refs then
/// resolve to nothing. Mirrors [`component_source_from_packs`] but
/// discovers tools from a deployed SoR's capability-admin API rather than
/// in-pack components.
///
/// The capability fetch (`SorxHttpInvoker::fetch`) is infallible: a
/// down/unreachable SoR degrades to an empty operation set (logged)
/// rather than blocking worker startup, so this still returns `Some`
/// whenever a URL is configured.
pub(crate) async fn sorla_source_from_env() -> Option<Arc<greentic_aw_runtime::SorlaToolSource>>
{
if std::env::var("GREENTIC_AW_SORLA_TOOLS").ok().as_deref() == Some("0") {
tracing::info!("GREENTIC_AW_SORLA_TOOLS=0; sorla tool source disabled");
return None;
}
let base = std::env::var("GREENTIC_AW_SORX_URL")
.ok()
.filter(|s| !s.is_empty())?;
let invoker = Arc::new(crate::runner::sorx_invoker::SorxHttpInvoker::fetch(base).await);
tracing::info!("sorla tool source constructed");
Some(Arc::new(greentic_aw_runtime::SorlaToolSource::new(invoker)))
}
/// Build the production [`greentic_ext_runtime::ExtensionRuntime`] used for
/// tool dispatch, wrapped in an [`Arc`] for sharing with [`AgentRuntime`].
///
/// On construction failure (e.g. wasmtime engine init), logs the error and
/// returns `None`; the caller then disables `DwAgent` nodes rather than
/// panicking.
///
/// Unlike the designer (which installs extensions through an explicit flow),
/// the runner has no install step — so it performs an initial scan of the
/// `design/` kind directory under the discovery root and registers each
/// on-disk extension here. Without this the agentic worker would boot with
/// an empty tool runtime and every extension tool would be silently dropped.
/// Per-extension failures (bad signature, malformed describe) are logged and
/// skipped so one broken extension never aborts boot; the watcher still
/// hot-reloads later changes.
/// Resolves an agentic-worker tool extension's `secret://…` reference to an
/// environment variable: strip the `secret://` scheme and upper-case every
/// run of non-alphanumeric chars to a single `_` — e.g.
/// `secret://tavily/api_key` → `TAVILY_API_KEY`. Lets local/desktop runs
/// supply tool secrets via the env (the in-process AW path has no broker).
pub(crate) struct EnvSecretsBackend;
impl greentic_ext_runtime::SecretsBackend for EnvSecretsBackend {
fn get(&self, uri: &str) -> Result<String, greentic_ext_runtime::SecretsError> {
let name = env_var_name_for_secret(uri);
std::env::var(&name)
.map_err(|_| greentic_ext_runtime::SecretsError::NotFound(uri.to_string()))
}
}
/// Tool-secret backend that resolves an extension's `secret://<provider>/<key>`
/// reference from the per-tenant secrets store first, then falls back to the
/// process env. This is what makes `gtc start` zero-env: `gtc setup` persists
/// the value in the dev store, and the injected secrets manager's read-side
/// candidate fallback bridges the canonical store scope to the pack-namespaced
/// scope setup actually wrote. The env fallback preserves existing
/// `TAVILY_API_KEY`-style runs.
///
/// `unit` is the deployed unit's `bundle_id` and scopes the store read. It
/// has to: one environment can run the same provider credential for two
/// workers, and without it both resolve
/// `secrets://{env}/{tenant}/_/{provider}/{key}` — ONE address for the whole
/// environment, so the second value staged wins and the other worker
/// silently authenticates as the wrong account. `None` on the legacy
/// tenant-only path and the process-level serve path, where there is no unit
/// to scope by.
struct StoreToolSecretsBackend {
secrets: crate::secrets::DynSecretsManager,
tenant: String,
env: String,
unit: Option<String>,
}
impl StoreToolSecretsBackend {
fn new(
secrets: crate::secrets::DynSecretsManager,
tenant: String,
unit: Option<String>,
) -> Self {
let env = std::env::var("GREENTIC_ENV")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| "dev".to_string());
Self {
secrets,
tenant,
env,
unit,
}
}
/// Every store URI a `secret://<provider>/<key>` read will try, in
/// order: this unit's own address first, then the env-wide one.
///
/// Both are built by
/// [`crate::secrets::agent_tool_secret_uri`] — the one function the
/// designer stages through as well, so a writer cannot spell an address
/// this reader never asks for.
///
/// REVIEW BY 2026-12-18: the env-wide candidate is a COMPATIBILITY
/// fallback when a unit is known, not a design choice. It exists so an
/// environment staged before this scope existed keeps working when its
/// runner moves; the next stage writes the unit-scoped address. Once
/// every lane stages unit-scoped tool secrets, it lets one unit read a
/// value another unit's writer left at the shared address — decide then
/// whether to drop it for the unit case. It remains the ONLY candidate
/// when no unit is known. This mirrors, deliberately, the same decision
/// `crate::secrets::pack_secret_path_candidates` records for a pack
/// secret and `greentic_aw_runtime::mcp_secrets` for an MCP token.
fn store_uri_candidates(&self, uri: &str) -> Vec<String> {
let body = uri.strip_prefix("secret://").unwrap_or(uri);
let Some((provider, key)) = body.split_once('/') else {
return Vec::new();
};
let bare =
crate::secrets::agent_tool_secret_uri(&self.env, &self.tenant, provider, key, None);
let scoped = self.unit.as_deref().and_then(|unit| {
crate::secrets::agent_tool_secret_uri(
&self.env,
&self.tenant,
provider,
key,
Some(unit),
)
});
// A scoped URI equal to the bare one would make the fallback a
// duplicate read rather than a fallback; it cannot happen (the unit
// segment always carries `_unit_<hash>`), but the guard keeps that a
// fact rather than a hope.
match (scoped, bare) {
(Some(scoped), Some(bare)) if scoped != bare => vec![scoped, bare],
(Some(scoped), None) => vec![scoped],
(_, Some(bare)) => vec![bare],
(None, None) => Vec::new(),
}
}
}
impl greentic_ext_runtime::SecretsBackend for StoreToolSecretsBackend {
fn get(&self, uri: &str) -> Result<String, greentic_ext_runtime::SecretsError> {
let candidates = self.store_uri_candidates(uri);
if !candidates.is_empty() {
// Read off a dedicated thread with its own current-thread runtime:
// the extension runtime may invoke this from within the async
// runner, where a nested `block_on` would panic.
let secrets = self.secrets.clone();
let resolved = std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.ok()?;
runtime.block_on(async move {
for candidate in &candidates {
if let Ok(bytes) = secrets.read(candidate).await {
return Some(bytes);
}
}
None
})
})
.join()
.ok()
.flatten();
if let Some(bytes) = resolved
&& let Ok(value) = String::from_utf8(bytes)
{
return Ok(value);
}
}
// Fallback: env var (preserves pre-store behaviour).
let name = env_var_name_for_secret(uri);
std::env::var(&name)
.map_err(|_| greentic_ext_runtime::SecretsError::NotFound(uri.to_string()))
}
}
/// A process-shared blocking HTTP client for tool extensions.
///
/// `reqwest::blocking::Client` owns an internal tokio runtime; dropping it
/// from within an async context panics ("cannot drop a runtime …"). The
/// in-process AW path creates and drops short-lived `ExtensionRuntime`s
/// inside the async runner, so we keep ONE client alive for the whole
/// process (built off the async runtime) and hand out cheap clones — a
/// clone dropped in async context never drops the underlying runtime, which
/// is released only at process exit (outside any runtime).
fn shared_blocking_http_client() -> Option<greentic_ext_runtime::reqwest::blocking::Client> {
use std::sync::OnceLock;
static CLIENT: OnceLock<Option<greentic_ext_runtime::reqwest::blocking::Client>> =
OnceLock::new();
CLIENT
.get_or_init(|| {
// Build on a plain OS thread so reqwest's internal runtime is
// not constructed inside a tokio context.
std::thread::spawn(|| {
greentic_ext_runtime::reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.ok()
})
.join()
.ok()
.flatten()
})
.clone()
}
pub(crate) fn env_var_name_for_secret(uri: &str) -> String {
let body = uri.strip_prefix("secret://").unwrap_or(uri);
let mut out = String::with_capacity(body.len());
let mut prev_underscore = false;
for ch in body.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_uppercase());
prev_underscore = false;
} else if !prev_underscore {
out.push('_');
prev_underscore = true;
}
}
out.trim_matches('_').to_string()
}
/// Env-keyed [`LlmPort`](greentic_ext_runtime::host_ports::LlmPort) for the
/// extension runtime.
///
/// Tool extensions that call `host.llm.complete()` internally (e.g. the
/// adaptive-cards `generate_card` / `data_to_card` tools) route through this
/// port. Without it wired the ext-runtime returns `"llm not configured for
/// this runtime"`. It reuses the same env-keyed multi-provider backend the
/// agent's OWN reasoning LLM uses ([`GreenticLlmBackend`]), so a single
/// `GREENTIC_LLM_API_KEY` powers both the agent and its tools.
///
/// Provider resolution is deliberately env-global (single key), mirroring the
/// agent's in-process backend: `ctx`, `role`, and `extension_id` do not select
/// a provider here (per-role/per-tenant resolution is the designer-admin's job,
/// not the in-process runner's). The synchronous `complete` drives the async
/// backend on a dedicated OS thread with its own current-thread runtime — the
/// same bridge [`StoreToolSecretsBackend::get`] uses — because the ext-runtime
/// may invoke it from within the async runner, where a nested `block_on`
/// would panic.
#[cfg(feature = "greentic-llm-backend")]
pub(crate) struct EnvLlmPort {
backend: Arc<dyn greentic_aw_runtime::llm::LlmBackend>,
provider: String,
model: String,
}
#[cfg(feature = "greentic-llm-backend")]
impl EnvLlmPort {
/// Default provider when `GREENTIC_LLM_PROVIDER` is unset. Mirrors the
/// runner's DeepSeek-first posture for the in-process worker.
const DEFAULT_PROVIDER: &'static str = "deepseek";
/// Default model when `GREENTIC_LLM_MODEL` is unset (DeepSeek's chat model,
/// matching `GreenticLlmBackend`'s live-test default).
const DEFAULT_MODEL: &'static str = "deepseek-chat";
/// Build an [`EnvLlmPort`] from the environment, or `None` when no LLM key
/// is present. Reads `GREENTIC_LLM_API_KEY` (fallback `OPENAI_API_KEY`),
/// `GREENTIC_LLM_PROVIDER` (default `deepseek`), `GREENTIC_LLM_MODEL`
/// (default `deepseek-chat`), and `GREENTIC_LLM_BASE_URL` — the SAME env
/// contract as [`in_process_llm_backend_with_key`], so the agent and its
/// tools never resolve to different credentials.
pub(crate) fn from_env() -> Option<Self> {
let api_key = std::env::var("GREENTIC_LLM_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| {
std::env::var("OPENAI_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
})?;
let provider = std::env::var("GREENTIC_LLM_PROVIDER")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| Self::DEFAULT_PROVIDER.to_string());
let model = std::env::var("GREENTIC_LLM_MODEL")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| Self::DEFAULT_MODEL.to_string());
let base_url = std::env::var("GREENTIC_LLM_BASE_URL").ok();
Some(Self {
backend: Arc::new(greentic_aw_runtime::GreenticLlmBackend::new(
api_key, base_url,
)),
provider,
model,
})
}
}
/// Map a port request onto an AW request for `provider`/`model`.
///
/// Tool-calling is not exposed to extension-internal completions, so
/// `tools` is empty; the port's `response_format` has no greentic-llm
/// counterpart at this layer (JSON coercion, when requested, is the
/// extension's own concern), so it is not forwarded. `credential_ref` is
/// `None` because the backend already holds the resolved key.
///
/// Shared by every [`greentic_ext_runtime::host_ports::LlmPort`]
/// implementation in this crate (`EnvLlmPort` and
/// `crate::runner::ext_llm_port::AgentLlmPort`) so the mapping cannot
/// drift between them.
#[cfg(feature = "greentic-llm-backend")]
pub(crate) fn port_request_to_llm_request(
request: greentic_ext_runtime::host_ports::LlmPortRequest,
provider: &str,
model: &str,
) -> greentic_aw_runtime::llm::LlmRequest {
use greentic_aw_runtime::state::ChatMessage;
let history = request
.messages
.into_iter()
.map(|(role, content)| match role.as_str() {
"assistant" => ChatMessage::Assistant {
content,
tool_calls: Vec::new(),
},
"system" => ChatMessage::System { content },
// Any non-assistant/non-system role (notably "user") maps to a
// user turn — the safe default for a chat completion.
_ => ChatMessage::User { content },
})
.collect();
greentic_aw_runtime::llm::LlmRequest {
system_prompt: request.system_prompt,
history,
tools: Vec::new(),
provider: greentic_aw_runtime::config::LlmProviderRef {
provider: provider.to_string(),
model: model.to_string(),
credential_ref: None,
},
}
}
/// Drive an async completion on a dedicated OS thread with its own
/// current-thread runtime. The ext-runtime may call a port from inside the
/// async runner, where a nested `block_on` panics. Same bridge as
/// `StoreToolSecretsBackend::get`.
///
/// Shared by every [`greentic_ext_runtime::host_ports::LlmPort`]
/// implementation in this crate so the thread bridge exists in exactly one
/// place.
#[cfg(feature = "greentic-llm-backend")]
pub(crate) fn complete_on_thread(
backend: Arc<dyn greentic_aw_runtime::llm::LlmBackend>,
request: greentic_aw_runtime::llm::LlmRequest,
) -> Result<
greentic_ext_runtime::host_ports::LlmPortResponse,
greentic_ext_runtime::host_ports::LlmPortError,
> {
use greentic_ext_runtime::host_ports::{LlmPortError, LlmPortResponse};
let result = std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|error| LlmPortError::Backend(error.to_string()))?;
runtime
.block_on(backend.complete(request))
.map_err(|error| LlmPortError::Backend(error.to_string()))
})
.join()
.map_err(|_| LlmPortError::Backend("llm completion thread panicked".to_string()))??;
let content = result.content.unwrap_or_default();
let total_tokens = result
.tokens_in
.checked_add(result.tokens_out)
.filter(|&total| total > 0);
Ok(LlmPortResponse {
content,
total_tokens,
})
}
#[cfg(feature = "greentic-llm-backend")]
impl greentic_ext_runtime::host_ports::LlmPort for EnvLlmPort {
fn complete(
&self,
_extension_id: &str,
_ctx: &greentic_ext_runtime::host_ports::HostCallContext,
_role: &str,
request: greentic_ext_runtime::host_ports::LlmPortRequest,
) -> Result<
greentic_ext_runtime::host_ports::LlmPortResponse,
greentic_ext_runtime::host_ports::LlmPortError,
> {
let llm_request = port_request_to_llm_request(request, &self.provider, &self.model);
complete_on_thread(self.backend.clone(), llm_request)
}
}
/// Which tier of `select_ext_llm_port`'s precedence produced the chosen
/// port. Returned alongside the port so the tracing line naming which
/// tier won is DERIVED from this same decision — never a second,
/// hand-kept `match` re-expressing the same precedence, which could
/// silently drift from the real one if either copy were edited alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExtLlmTier {
Host,
Agent,
Env,
}
/// Pick the extension runtime's LLM port. Pure so the tier order is
/// testable: the bug this exists to prevent was a wrong tier being
/// chosen silently. Returns the winning tier alongside the port for the
/// same reason.
fn select_ext_llm_port(
host_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
agent_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
env_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
) -> Option<(
ExtLlmTier,
Arc<dyn greentic_ext_runtime::host_ports::LlmPort>,
)> {
if let Some(port) = host_llm_port {
return Some((ExtLlmTier::Host, port));
}
if let Some(port) = agent_llm_port {
return Some((ExtLlmTier::Agent, port));
}
env_llm_port.map(|port| (ExtLlmTier::Env, port))
}
/// Whether `build_runtime_with_stores` should attempt to build tier 2 of
/// the extension LLM port (the worker's own resolved backend) at THIS
/// call. Pure, so the two call sites' `None`s share one TESTED decision
/// instead of each being an untested one-line condition that could
/// invert silently: `ExtensionRuntime` exposes no `llm_port` accessor, so
/// a test can only see this boolean, never the runtime it produced. An
/// inverted guard would have `AgentLlmPort::from_agents` build (and log)
/// a port that `select_ext_llm_port` then discards in favour of a
/// higher-priority tier — exactly the lying "wired (the worker's own
/// agent LLM)" log this whole change exists to remove.
///
/// - `bridge_extension_configured`: the `GREENTIC_AW_LLM_EXTENSION`
/// bridge branch never attempts tier 2 — its `llm` dispatches through
/// `ext_runtime` itself, so there is no in-process backend to wrap yet.
/// - `host_port_present`: the zero-env branch attempts tier 2 only when
/// the HOST has not already injected its own port. `select_ext_llm_port`
/// prefers the host port unconditionally, so building the agent port
/// anyway would be discarded work that also logs as though it mattered.
fn should_attempt_agent_llm_port(
bridge_extension_configured: bool,
host_port_present: bool,
) -> bool {
!bridge_extension_configured && !host_port_present
}
pub(crate) fn build_ext_runtime(
secrets_backend: Arc<dyn greentic_ext_runtime::SecretsBackend>,
host_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
agent_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: &[Arc<crate::pack::PackRuntime>],
) -> Option<Arc<greentic_ext_runtime::ExtensionRuntime>> {
use greentic_ext_runtime::{
DiscoveryPaths, ExtensionRuntime, HostOverrides, RuntimeConfig, discovery,
};
let root = extension_discovery_dir();
let paths = DiscoveryPaths::new(root.clone());
// Wire the provided secrets backend and an HTTP client so tool
// extensions can read their declared `secret://…` references and reach
// their upstreams. `HostOverrides::default()` leaves both empty, which
// silently breaks any AW tool that needs either (e.g. tavily_search).
// The per-tenant path passes a store-backed backend (zero-env); the
// process-level serve paths pass the env-only backend.
//
// `llm_port` powers tool extensions that call `host.llm.complete()`
// internally (e.g. adaptive-cards `generate_card`). The tier order is
// decided by `select_ext_llm_port`, which also reports WHICH tier won
// as an `ExtLlmTier` — kept pure and unit-tested so a wrong tier
// being chosen silently — the bug this whole change exists to fix —
// cannot creep back in unnoticed, and so the tracing line below can
// be derived from that single decision rather than a second copy of
// it:
// 1. A `host_llm_port` injected by the embedding host (e.g. the
// designer) — its own per-tenant, admin-backed, metered path. NOT
// feature-gated: a host can inject a port regardless of features.
// 2. The WORKER's own resolved backend, when this runtime serves
// agents (`agent_llm_port`, built by the caller via
// `AgentLlmPort::from_agents`). This is the model the operator
// actually selected. It exists because `build_ext_runtime` used
// to run BEFORE the worker's backend was resolved, so every
// deployed lane fell straight through to tier 3's env-keyed
// default (or tier 4's refusal) instead. Wired today at
// `build_runtime_with_stores`'s zero-env branch, which also
// serves the ephemeral desktop path via
// `build_agent_node_wiring_ephemeral` — see tier 3 below for the
// one agent-holding site this tier does not reach yet.
// 3. Otherwise, the env-keyed `EnvLlmPort` — the call sites that
// serve no agents at all (`runner/mod.rs`'s process-level
// ext-runtime field, `graph_node.rs`'s process-level graph serve
// path), only when the `greentic-llm-backend` feature is on AND
// an LLM key is present in env. `build_agent_runtime` (the
// `serve_agentic` / process-level in-proc NATS path) is the
// exception worth naming: it DOES hold agents (an empty map
// returns `None` before reaching here) and is deliberately NOT
// wired to tier 2 yet — its `llm` comes from
// `build_llm_backend(&ext_runtime)`, which needs `ext_runtime`
// to exist unconditionally (not only on a bridge branch, unlike
// `build_runtime_with_stores`), so closing it needs the same
// circular-dependency split, and that split has not been done
// there. That lane still runs an extension's
// `host.llm.complete` on this tier's env-keyed default even
// though it serves agents — see the `tracing::warn!` at its own
// `build_ext_runtime` call, which says so out loud rather than
// leaving it to this comment alone.
// 4. Otherwise `None`, so the ext-runtime keeps returning "llm not
// configured for this runtime" (unchanged no-key behaviour).
//
// Note `env_llm_port` below is now built EAGERLY on every call,
// regardless of which tier ends up winning — previously this line
// only ran when the host port was absent. `EnvLlmPort::from_env()` is
// env reads plus a struct construction, no I/O, so the redundant work
// when tier 1 or 2 wins is a remark, not a performance concern.
let env_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>> = {
#[cfg(feature = "greentic-llm-backend")]
{
EnvLlmPort::from_env().map(|port| {
Arc::new(port) as Arc<dyn greentic_ext_runtime::host_ports::LlmPort>
})
}
#[cfg(not(feature = "greentic-llm-backend"))]
{
None
}
};
// The tracing line is derived from the tier `select_ext_llm_port`
// actually chose, rather than a second `match` re-deciding the same
// precedence from the three `is_some()`s — that second copy is
// exactly what let the log claim "host-provided" while a different
// tier's port was the one actually wired. `AgentLlmPort::from_agents`
// already logs its own `info` line naming the agent, so tier 2 does
// not log again here.
let selected = select_ext_llm_port(host_llm_port, agent_llm_port, env_llm_port);
match &selected {
Some((ExtLlmTier::Host, _)) => {
tracing::info!("extension runtime LLM port wired (host-provided ext LLM)");
}
Some((ExtLlmTier::Agent, _)) => {}
Some((ExtLlmTier::Env, _)) => {
tracing::info!(
"extension runtime LLM port wired (env ext LLM, env-keyed greentic-llm; \
no host port, no agent port)"
);
}
None => {
tracing::info!(
"extension runtime LLM port not configured (no host port, no agent port, no env key)"
);
}
}
let llm_port = selected.map(|(_, port)| port);
let overrides = HostOverrides {
secrets_backend,
http_client: shared_blocking_http_client(),
llm_port,
..HostOverrides::default()
};
let config = RuntimeConfig::from_paths(paths).with_host_overrides(overrides);
let mut runtime = match ExtensionRuntime::new(config) {
Ok(runtime) => runtime,
Err(error) => {
tracing::warn!(error = %error, "extension runtime init failed; DwAgent nodes disabled");
return None;
}
};
// Initial load of on-disk design extensions (agentic-worker tools live
// in `<root>/design/<ext>/`).
let design_dir = root.join("design");
let mut on_disk = 0usize;
match discovery::scan_kind_dir(&design_dir) {
Ok(ext_dirs) => {
for ext_dir in ext_dirs {
match runtime.register_loaded_from_dir(&ext_dir) {
Ok(()) => on_disk += 1,
Err(error) => tracing::warn!(
error = %error, dir = %ext_dir.display(),
"skipping extension that failed to load"
),
}
}
}
Err(error) => {
tracing::warn!(error = %error, dir = %design_dir.display(), "scanning design extensions failed")
}
}
// Then the extensions the loaded packs carry at `extensions/*.gtxpack`.
//
// This runs SECOND on purpose: `register_loaded_from_dir` inserts by
// `ExtensionId`, so a pack pass ahead of the disk scan would let a
// pack-frozen copy overwrite the one an operator installed. See
// `pack_extensions::is_shadowed` for why disk wins and what that costs.
//
// In a k8s or Cloud Run container the directory above is empty — nothing
// writes `GREENTIC_EXTENSIONS_DIR` there — so this is the only source
// the worker has, and before it existed every extension tool an operator
// bound was dropped with a warn after the deploy reported success.
let from_packs = crate::runner::pack_extensions::register_from_packs(&mut runtime, packs);
// Log the cap ids, not just a count: an unresolved mandatory guardrail
// cap blocks every agent turn, and until now the only way to see which
// caps a runner has was to trigger that failure. Emitted after both
// sources so the line describes the registry the agent will actually
// dispatch against.
let mut cap_ids: Vec<String> = runtime
.capability_registry()
.offerings()
.map(|offering| offering.cap_id.to_string())
.collect();
cap_ids.sort();
tracing::info!(
loaded = on_disk,
from_packs = from_packs.loaded,
shadowed_by_disk = from_packs.shadowed,
pack_failures = from_packs.failed,
dir = %design_dir.display(),
caps = %cap_ids.join(","),
"loaded design extensions"
);
Some(Arc::new(runtime))
}
/// Whether `provider` needs an API key to authenticate.
///
/// Authoritative when `greentic-llm-backend` is compiled in: the answer
/// comes from `greentic_llm::ProviderKind::requires_api_key()`. The local
/// table is the fallback for builds without that feature (where
/// `greentic_llm` is not linked at all) and for a provider string that
/// crate does not recognise; `keyless_table_matches_greentic_llm` pins the
/// two together.
///
/// Keyless providers talk to a local daemon with no auth (Ollama,
/// Llamafile) or authenticate out of band (Bedrock, via the AWS credential
/// chain), so an absent or empty `GREENTIC_LLM_API_KEY` is the NORMAL state
/// for them and must not disqualify the multi-provider backend.
///
/// `None` — nothing named a provider anywhere — is treated as
/// key-requiring, because the historical default is OpenAI.
pub(super) fn provider_requires_api_key(provider: Option<&str>) -> bool {
let Some(provider) = provider.map(str::trim).filter(|p| !p.is_empty()) else {
return true;
};
#[cfg(feature = "greentic-llm-backend")]
if let Ok(kind) = provider.parse::<greentic_llm::ProviderKind>() {
return kind.requires_api_key();
}
keyless_table_requires_api_key(provider)
}
/// The local mirror of `greentic_llm::ProviderKind::requires_api_key()`,
/// used for builds without the `greentic-llm-backend` feature and for
/// provider strings greentic-llm does not recognise. Pinned to the real
/// thing by `keyless_table_matches_greentic_llm`.
fn keyless_table_requires_api_key(provider: &str) -> bool {
!matches!(
provider.to_ascii_lowercase().as_str(),
"ollama" | "llamafile" | "bedrock"
)
}
/// The operator's explicitly configured LLM endpoint, if any.
///
/// Unset, blank or whitespace-only all mean "the operator configured
/// nothing", matching `llm_openai::normalize_base_url`'s reading of the
/// same variable.
#[cfg(feature = "greentic-llm-backend")]
fn custom_llm_base_url() -> Option<String> {
std::env::var("GREENTIC_LLM_BASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
}
/// Whether a resolved (key, provider) pair selects the in-process
/// multi-provider greentic-llm backend rather than the single-provider
/// OpenAI fall-through.
#[cfg(feature = "greentic-llm-backend")]
pub(super) fn selects_multi_provider_backend(api_key: &str, provider: Option<&str>) -> bool {
selects_multi_provider_backend_with(api_key, provider, custom_llm_base_url().as_deref())
}
/// The pure half of [`selects_multi_provider_backend`], split out so the
/// rules below are testable without mutating process-global env — which
/// races every other test in the binary, the same reasoning
/// `llm_openai::normalize_base_url` was split for.
///
/// Three ways in, and the third is the one that had to be added:
///
/// 1. **A non-empty key.** Always.
/// 2. **A keyless provider** (Ollama, Llamafile, Bedrock), which
/// authenticates through a local daemon or the AWS credential chain.
/// 3. **An explicitly configured endpoint**, whatever the provider name.
///
/// Rule 3 exists because `provider = "openai"` means "speaks the OpenAI
/// protocol", not "is api.openai.com". An operator pointing
/// `GREENTIC_LLM_BASE_URL` at Ollama's `/v1`, LM Studio, vLLM or any other
/// local gateway has named an endpoint that legitimately wants no key —
/// and without this they had to invent a dummy one, because an empty key
/// dropped them onto the fall-through client.
///
/// **That fall-through does not merely lack a key — it cannot reach the
/// endpoint at all.** `OpenAiLlmBackend` appends `/v1/...` to whatever base
/// URL it is given (see `normalize_base_url`'s doc comment), so a base URL
/// that already ends in `/v1` becomes `/v1/v1/chat/completions` and every
/// request 404s. Recorded here because the symptom — "keyless works with a
/// dummy key, 404s without one" — reads like an authentication problem and
/// is a path-construction one. The path behaviour is that client's
/// documented contract and is deliberately left alone; this stops the
/// keyless case from landing on it.
#[cfg(feature = "greentic-llm-backend")]
fn selects_multi_provider_backend_with(
api_key: &str,
provider: Option<&str>,
base_url: Option<&str>,
) -> bool {
!api_key.trim().is_empty()
|| !provider_requires_api_key(provider)
|| base_url.map(str::trim).is_some_and(|url| !url.is_empty())
}
/// The provider name an explicit `GREENTIC_LLM_PROVIDER` names, if any.
pub(super) fn env_llm_provider() -> Option<String> {
std::env::var("GREENTIC_LLM_PROVIDER")
.ok()
.filter(|provider| !provider.trim().is_empty())
}
/// The agent whose LLM configuration represents this runtime, chosen
/// deterministically: sorted id order, first agent declaring a non-empty
/// `llm.provider`. `None` when no agent declares one.
///
/// Sorted, not `HashMap` order: this decides both which provider the
/// in-process agent backend is built for
/// ([`configured_llm_provider`]) and which provider
/// `crate::runner::ext_llm_port::AgentLlmPort` resolves an extension's
/// `host.llm.complete()` call to. An unstable pick means a worker that
/// answers on a different provider after every restart — and, since both
/// callers iterate the same map independently, a hash-order pick could
/// also let the agent's own reasoning LLM and its extensions' LLM calls
/// silently disagree with each other on the same boot.
pub(crate) fn first_declared_llm_agent(
agents: &HashMap<String, AgentConfig>,
) -> Option<(&String, &AgentConfig)> {
let mut ids: Vec<&String> = agents.keys().collect();
ids.sort();
ids.into_iter()
.filter_map(|id| agents.get(id).map(|agent| (id, agent)))
.find(|(_, agent)| !agent.llm.provider.trim().is_empty())
}
/// The provider to judge keylessness by: the env override first (it is the
/// deployment's explicit statement), then the first agent that declares
/// one. The in-process backend carries a single key, so a single provider
/// decides — matching the one-key model in
/// [`in_process_llm_backend_with_key`].
pub(super) fn configured_llm_provider(agents: &HashMap<String, AgentConfig>) -> Option<String> {
env_llm_provider().or_else(|| {
first_declared_llm_agent(agents).map(|(_, agent)| agent.llm.provider.trim().to_string())
})
}
/// Resolve the [`LlmBackend`] from the environment.
///
/// Prefers the LLM bridge extension when `GREENTIC_AW_LLM_EXTENSION` is set
/// (LLM-as-extension); otherwise falls back to the env-keyed in-process
/// OpenAI client. Shared by the single-agent (`build_agent_node_handler`)
/// and graph (`graph_node::build_graph_node_handler`) construction paths so
/// both resolve the backend identically.
pub(crate) fn build_llm_backend(
ext_runtime: &Arc<greentic_ext_runtime::ExtensionRuntime>,
) -> Arc<dyn greentic_aw_runtime::LlmBackend> {
use std::time::Duration;
use greentic_aw_runtime::{ExtensionLlmBackend, OpenAiLlmBackend, RetryingLlmBackend};
match std::env::var("GREENTIC_AW_LLM_EXTENSION")
.ok()
.filter(|s| !s.trim().is_empty())
{
Some(ext_id) => {
let api_key = std::env::var("GREENTIC_LLM_API_KEY")
.or_else(|_| std::env::var("OPENAI_API_KEY"))
.unwrap_or_default();
match bridge_credential(
std::env::var("GREENTIC_LLM_PROVIDER").ok(),
std::env::var("GREENTIC_LLM_MODEL").ok(),
api_key,
std::env::var("GREENTIC_LLM_BASE_URL").ok(),
) {
Some(cred) => {
tracing::info!(
extension = %ext_id, provider = %cred.provider, model = %cred.model,
"AW LLM via bridge extension"
);
Arc::new(RetryingLlmBackend::new(
ExtensionLlmBackend::new(ext_runtime.clone(), ext_id, cred),
3,
Duration::from_millis(250),
))
}
None => {
tracing::warn!(
provider = env_llm_provider().as_deref().unwrap_or("openai"),
"GREENTIC_AW_LLM_EXTENSION set but no LLM API key and the \
configured provider requires one; falling back to in-process \
OpenAI client"
);
Arc::new(RetryingLlmBackend::new(
OpenAiLlmBackend::new(String::new()),
3,
Duration::from_millis(250),
))
}
}
}
None => in_process_llm_backend(),
}
}
/// In-process LLM backend when no bridge extension is configured.
///
/// With the `greentic-llm-backend` feature and an LLM key present — or a
/// keyless provider configured — routes the worker's LLM call through
/// greentic-llm so a `dw.agent` can use any provider its `AgentConfig.llm`
/// declares (DeepSeek, Anthropic, Gemini, Ollama, …): the provider + model
/// ride on each request, the key + optional base URL come from the env.
/// Otherwise falls back to the legacy env-keyed OpenAI client. Shared by
/// every non-bridge construction path so they never drift.
///
/// This path sees no agent configs, so the provider is whatever
/// `GREENTIC_LLM_PROVIDER` names.
pub(crate) fn in_process_llm_backend() -> Arc<dyn greentic_aw_runtime::LlmBackend> {
in_process_llm_backend_with_key(None, env_llm_provider())
}
/// In-process LLM backend, optionally given a store-resolved API key.
///
/// `override_key` (resolved from an agent's `credential_ref` via the
/// per-tenant secrets store) takes precedence over the env key when present —
/// this is what makes the in-process desktop LLM path zero-env. When `None`,
/// the key comes from `GREENTIC_LLM_API_KEY`/`OPENAI_API_KEY` exactly as
/// before, so env-based and bridge-less runs are unaffected.
///
/// `provider` is the configured LLM provider (see
/// [`configured_llm_provider`]). It decides one thing: whether an EMPTY key
/// still selects the multi-provider backend. For a keyless provider it
/// must, or an Ollama worker silently talks to `api.openai.com` with an
/// empty bearer — which is what made `GREENTIC_LLM_API_KEY=ollama` a
/// necessary workaround. For every key-requiring provider the behaviour is
/// unchanged.
pub(crate) fn in_process_llm_backend_with_key(
override_key: Option<String>,
provider: Option<String>,
) -> Arc<dyn greentic_aw_runtime::LlmBackend> {
use greentic_aw_runtime::{OpenAiLlmBackend, RetryingLlmBackend};
use std::time::Duration;
// Only read under `greentic-llm-backend` (below); prefixed so the
// binding doesn't trip `unused_variables` when that feature is off
// (it isn't a default feature — see Cargo.toml).
let _store_resolved = override_key
.as_ref()
.map(|key| !key.trim().is_empty())
.unwrap_or(false);
#[cfg(feature = "greentic-llm-backend")]
{
let api_key = override_key
.clone()
.filter(|key| !key.trim().is_empty())
.or_else(|| std::env::var("GREENTIC_LLM_API_KEY").ok())
.or_else(|| std::env::var("OPENAI_API_KEY").ok())
.unwrap_or_default();
if selects_multi_provider_backend(&api_key, provider.as_deref()) {
let base_url = std::env::var("GREENTIC_LLM_BASE_URL").ok();
if api_key.trim().is_empty() {
// Once per backend construction, not per token: the returned
// `Arc` serves the whole agent handler's lifetime.
tracing::warn!(
provider = provider.as_deref().unwrap_or_default(),
"AW LLM provider is keyless: running with an empty API key. \
This is expected for Ollama / Llamafile / Bedrock (which \
authenticate through a local daemon or the AWS credential \
chain); set GREENTIC_LLM_API_KEY only if your endpoint \
actually demands one"
);
}
tracing::info!(
store_resolved = _store_resolved,
provider = provider.as_deref().unwrap_or_default(),
"AW LLM via in-process greentic-llm (multi-provider)"
);
return Arc::new(RetryingLlmBackend::new(
greentic_aw_runtime::GreenticLlmBackend::new(api_key, base_url),
3,
Duration::from_millis(250),
));
}
}
let openai_key = override_key
.filter(|key| !key.trim().is_empty())
.or_else(|| std::env::var("OPENAI_API_KEY").ok())
.unwrap_or_default();
// Fall-through: the single-provider OpenAI-protocol client. Reached
// either because `greentic-llm-backend` is not compiled in (the block
// above does not exist at all), or because it is compiled in and no
// key resolved for a provider that REQUIRES one — a keyless provider
// (Ollama, Llamafile, Bedrock) takes the branch above with an empty
// key. Both mean the agent's `AgentConfig.llm.provider` is IGNORED and
// every request goes to one OpenAI-shaped endpoint — which is a
// silent, total misroute if the agent declared DeepSeek/Anthropic/… So
// say so. This runs once per backend construction, not per token: the
// returned `Arc` is reused for the whole agent handler's lifetime.
#[cfg(feature = "greentic-llm-backend")]
let reason = "no LLM API key resolved (tried the agent's llm.credential_ref, \
GREENTIC_LLM_API_KEY, then OPENAI_API_KEY)";
#[cfg(not(feature = "greentic-llm-backend"))]
let reason = "this binary was built WITHOUT the `greentic-llm-backend` feature, \
so the multi-provider backend is not compiled in";
tracing::warn!(
reason,
provider = provider.as_deref().unwrap_or_default(),
endpoint = %std::env::var("GREENTIC_LLM_BASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
.unwrap_or_else(|| "https://api.openai.com".to_string()),
fix = "rebuild with `--features greentic-llm-backend` and supply a key via \
GREENTIC_LLM_API_KEY or the agent's llm.credential_ref; or point \
GREENTIC_LLM_BASE_URL at an OpenAI-compatible endpoint",
"AW LLM falling back to the single-provider OpenAI client: the agent's \
configured llm.provider is IGNORED and every request goes to this endpoint"
);
Arc::new(RetryingLlmBackend::new(
OpenAiLlmBackend::new(openai_key),
3,
Duration::from_millis(250),
))
}
/// Resolve an LLM API key from the per-tenant secrets store via the first
/// agent that declares `llm.credential_ref`, mirroring the credential URI
/// `secrets://default/{tenant}/_/llm/{credential_ref}` that
/// [`greentic_aw_runtime::llm_credential::SecretsBackedCredentialResolver`]
/// reads. This lets the in-process LLM backend be zero-env (key from store)
/// when no `GREENTIC_LLM_API_KEY` env is set.
///
/// Returns `None` when no agent declares a credential_ref or the read misses.
/// The in-process backend carries a single key, so when agents declare
/// different credential_refs only the first is used — matching the existing
/// one-key in-process model; the bridge-extension path resolves per-request.
///
/// `pub(crate)` (not private): also reused by `runtime.rs` to resolve the
/// `greentic_llm::LlmProvider` key for the in-process `operala.call`
/// (`DeepWorkerInvoker`) wiring, so the two in-process LLM paths (dw.agent,
/// operala.call) share one key-resolution policy instead of drifting.
pub(crate) async fn resolve_in_process_llm_key(
secrets: &crate::secrets::DynSecretsManager,
tenant: &str,
merged_agents: &HashMap<String, AgentConfig>,
) -> Option<String> {
let credential_ref = merged_agents
.values()
.find_map(|agent| agent.llm.credential_ref.clone())?;
let uri = format!("secrets://default/{tenant}/_/llm/{credential_ref}");
let bytes = secrets.read(&uri).await.ok()?;
let key = String::from_utf8(bytes).ok()?.trim().to_string();
if key.is_empty() { None } else { Some(key) }
}
/// Build a vault-style `BridgeCredential` from resolved parts. `None` when
/// no API key is present AND the resolved provider needs one — a keyless
/// provider (Ollama, Llamafile, Bedrock) is credential-complete with an
/// empty key, and dropping it here is what used to route an Ollama worker
/// to the OpenAI fall-through. Defaults: provider "openai", model "gpt-4o".
/// Pure (no env) so it is unit-testable without global state.
pub(super) fn bridge_credential(
provider: Option<String>,
model: Option<String>,
api_key: String,
base_url: Option<String>,
) -> Option<greentic_aw_runtime::BridgeCredential> {
let provider = provider
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| "openai".into());
if api_key.trim().is_empty() && provider_requires_api_key(Some(&provider)) {
return None;
}
Some(greentic_aw_runtime::BridgeCredential {
provider,
model: model
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| "gpt-4o".into()),
api_key,
base_url: base_url.filter(|s| !s.trim().is_empty()),
})
}
/// Shared store-agnostic tail: builds the extension runtime, LLM backend,
/// config providers, and [`AgentRuntime`] given the three already-constructed
/// store trait objects, then mounts the knowledge (RAG) and long-term-memory
/// seams so the returned in-process runtime grounds identically to the
/// out-of-process NATS serve path ([`build_agent_runtime`]).
///
/// Extracted so both the Redis path ([`build_agent_node_handler`]) and the
/// ephemeral desktop path ([`build_agent_node_handler_ephemeral`]) share
/// identical post-store construction logic; store differences are the only
/// divergence between the two callers. Returning the bare [`AgentRuntime`]
/// (rather than the wrapped handler) also keeps the mounted knowledge seam
/// observable to the regression test that guards this wiring.
///
/// Returns `None` when the extension runtime fails to initialise (the only
/// failure mode at this layer — store errors are handled by callers).
///
/// `unit` is the deployed unit's `bundle_id` (`None` on the legacy
/// tenant-only path); it scopes the pack-carried MCP credential read.
#[allow(clippy::too_many_arguments)]
async fn build_runtime_with_stores(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
state_store: Arc<dyn greentic_aw_runtime::state::AgentStateStore>,
token_meter: Arc<dyn greentic_aw_runtime::cost::TokenMeter>,
ledger: Arc<dyn greentic_aw_runtime::tools::ToolLedger>,
unit: Option<String>,
billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
) -> Option<Arc<AgentRuntime>> {
use std::time::Duration;
use greentic_aw_runtime::LayeredConfigProvider;
use greentic_aw_runtime::ManifestToolOverlayProvider;
use greentic_aw_runtime::config_provider::CachingConfigProvider;
use greentic_aw_runtime::{
ExtensionLlmBackend, LlmBackend, OtelTelemetry, RetryingLlmBackend,
};
// Per-tenant path: tool secrets resolve from the store first (zero-env),
// env as fallback. `secrets` is the injected per-tenant manager whose
// candidate fallback bridges the gtc-setup dev-store scope.
// The deployed unit scopes the tool-secret read for the same reason it
// scopes the MCP one below: this runtime is built per `TenantRuntime`,
// i.e. per deployed unit, so `unit` already names the only worker whose
// credentials this backend may resolve.
let secrets_backend: Arc<dyn greentic_ext_runtime::SecretsBackend> = Arc::new(
StoreToolSecretsBackend::new(secrets.clone(), tenant.clone(), unit.clone()),
);
// Resolving `llm` and building `ext_runtime` have a circular
// dependency in exactly one case: the LLM-bridge-extension branch
// below dispatches through `ext_runtime` itself, so it cannot run
// until `build_ext_runtime` returns. The zero-env branch has no such
// dependency, so when no bridge extension is configured it is
// resolved FIRST and fed into `build_ext_runtime` as tier 2 of the
// extension LLM port (see `select_ext_llm_port`) — this is the actual
// fix: `build_ext_runtime` used to always run before this
// resolution, so tier 2 was unreachable in every deployed lane. The
// bridge branch keeps exactly the order and construction it had
// before this change — tier 2 is `None` for that one case, and
// `build_ext_runtime` falls through to tier 3 (env) or tier 4 (none)
// for it, same as always.
let bridge_extension_id = std::env::var("GREENTIC_AW_LLM_EXTENSION")
.ok()
.filter(|s| !s.trim().is_empty());
let (ext_runtime, llm): (
Arc<greentic_ext_runtime::ExtensionRuntime>,
Arc<dyn LlmBackend>,
) = match bridge_extension_id {
Some(ext_id) => {
// Bridge extension configured: `llm` must dispatch through
// `ext_runtime`, so build the runtime first with no
// agent-backed tier 2 — there is no worker backend yet to
// wire, and there never was for this branch.
// `should_attempt_agent_llm_port` is the single tested source
// of that decision; asserting it here too (not only in the
// zero-env branch's `if`) means an inversion of the shared
// logic is caught on this branch as well.
debug_assert!(!should_attempt_agent_llm_port(true, ext_llm_port.is_some()));
let ext_runtime = build_ext_runtime(secrets_backend, ext_llm_port, None, &packs)?;
use greentic_aw_runtime::llm_credential::SecretsBackedCredentialResolver;
let resolver = Arc::new(SecretsBackedCredentialResolver::new(
secrets.clone(),
tenant.clone(),
));
tracing::info!(
extension = %ext_id,
tenant = %tenant,
"AW LLM via bridge (per-tenant creds)"
);
let llm: Arc<dyn LlmBackend> = Arc::new(RetryingLlmBackend::new(
ExtensionLlmBackend::with_resolver_runtime(
ext_runtime.clone(),
ext_id,
resolver,
),
3,
Duration::from_millis(250),
));
(ext_runtime, llm)
}
None => {
// Zero-env LLM: with no bridge extension and no env key, resolve
// the agent's `credential_ref` from the per-tenant store (the same
// manager whose candidate fallback bridges the gtc-setup scope).
// An env key still wins (legacy single-provider runs unaffected).
let env_key_present = std::env::var("GREENTIC_LLM_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
.or_else(|| {
std::env::var("OPENAI_API_KEY")
.ok()
.filter(|value| !value.trim().is_empty())
})
.is_some();
let store_key = if env_key_present {
None
} else {
resolve_in_process_llm_key(&secrets, &tenant, &merged_agents).await
};
if store_key.is_some() {
tracing::info!(
tenant = %tenant,
"AW LLM key resolved from store via credential_ref (zero-env)"
);
}
// This path DOES see the agent configs, so a worker that
// declares a keyless provider (Ollama) reaches the
// multi-provider backend even with no key anywhere.
let llm = in_process_llm_backend_with_key(
store_key,
configured_llm_provider(&merged_agents),
);
// Tier 2 of the extension LLM port: the worker's own resolved
// backend, so `host.llm.complete()` inside an extension runs
// on the provider the operator actually selected instead of
// falling through to the env-keyed default. Built only when
// the host has not already injected its own port:
// `select_ext_llm_port` prefers the host port regardless, so
// building this one anyway would have `AgentLlmPort::from_agents`
// log as if it were in play while it is silently discarded.
let agent_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>> =
if should_attempt_agent_llm_port(false, ext_llm_port.is_some()) {
#[cfg(feature = "greentic-llm-backend")]
{
crate::runner::ext_llm_port::AgentLlmPort::from_agents(
llm.clone(),
&merged_agents,
)
.map(|port| {
Arc::new(port) as Arc<dyn greentic_ext_runtime::host_ports::LlmPort>
})
}
#[cfg(not(feature = "greentic-llm-backend"))]
{
None
}
} else {
None
};
let ext_runtime =
build_ext_runtime(secrets_backend, ext_llm_port, agent_llm_port, &packs)?;
(ext_runtime, llm)
}
};
// Shared context (Phase A2): per-binding sharing modes from the packs.
// Computed here because `merged_agents` is moved just below.
let share_policy = crate::runner::run_context_policy::share_policy_from_packs(
&packs,
merged_agents.keys().map(String::as_str),
);
// Shared context (Phase C): the user ledger, when the host passed a
// door target AND a pack names an agent. Computed here, beside
// `share_policy`, because `merged_agents` is moved just below. Bound to
// `tenant`, the tenant this runtime's turns run under.
let ledger_binding = crate::runner::user_ledger_policy::user_ledger_binding(
&tenant,
&packs,
merged_agents.keys().map(String::as_str),
user_ledger,
);
let agent_count = merged_agents.len();
let overlay = ManifestToolOverlayProvider::new(
HostConfigProvider::new(merged_agents),
manifests_discovery_dir(),
);
let config_provider: Arc<dyn ConfigProvider> = match registry_from_env() {
Some(http) => Arc::new(CachingConfigProvider::new(LayeredConfigProvider::new(
http, overlay,
))),
None => Arc::new(CachingConfigProvider::new(overlay)),
};
let telemetry = Arc::new(OtelTelemetry);
// One manager for every remote tool source that reads a credential at
// run time (MCP and A2A). Hoisted out of the MCP block so both honour
// the same explicit `SECRETS_BACKEND` override; see
// `mcp_secrets_manager` for why that override must win over the
// injected manager.
let remote_tool_secrets = mcp_secrets_manager(&secrets);
// Hoisted into locals so the playbook turn host below can share the
// SAME source objects — and therefore the same TTL caches — rather than
// each nested turn re-enumerating the packs.
let components = component_source_from_packs(&packs, &tenant);
let flows = flow_source_from_packs(&packs, &tenant);
let sorla = match sorla_source_from_env().await {
Some(env) => Some(env),
None => {
crate::runner::sorla_pack_source::sorla_source_from_packs(
&packs,
&tenant,
Some(remote_tool_secrets.clone()),
unit.as_deref(),
)
.await
}
};
// Pack-only: there is no admin A2A source to prefer. This site covers
// deployed dw.agent units, the desktop runner and the designer's
// test-chat sidecar; `graph_node::graph_a2a_source` builds the graph
// turns' source from the same inputs through the same helper.
// `build_agent_runtime` (process-level serve, no packs) stays without
// one, as it is for pack MCP.
let a2a = crate::runner::a2a_pack_source::a2a_source_from_packs(
&packs,
&tenant,
Some(remote_tool_secrets.clone()),
unit.as_deref(),
);
// A playbook's own turn gets every source above and deliberately NOT a
// playbook one, so a skill cannot call a skill — see `playbook_turn`.
let playbooks = crate::runner::playbook_turn::playbook_source_from_packs(
&packs,
crate::runner::playbook_turn::PlaybookTurnHost {
state_store: state_store.clone(),
ext_runtime: ext_runtime.clone(),
llm: llm.clone(),
telemetry: telemetry.clone(),
token_meter: token_meter.clone(),
ledger: ledger.clone(),
mcp: None,
components: components.clone(),
flows: flows.clone(),
sorla: sorla.clone(),
a2a: a2a.clone(),
},
);
let base = AgentRuntime::new(
config_provider,
state_store,
ext_runtime.clone(),
llm,
telemetry,
token_meter,
ledger,
// The env-configured ADMIN source wins; the pack-carried routes are
// the fallback. This is deliberately the OPPOSITE of the flow MCP
// node's precedence (`mcp_node::aw::invoke_with_secrets`, "A
// pack-carried route wins"), and the asymmetry is load-bearing:
//
// - A flow node's pack route strictly ADDS capability. The admin
// catalog supplies the same route and nothing else, so preferring
// the pack can only turn a failure into a success.
// - The agent catalog additionally carries LIVE tool schemas probed
// from the server this run, and applies each server's
// `allowed_tools`. Preferring the pack there would downgrade every
// environment that has a working admin source — the designer's own
// in-process host among them.
//
// A per-server merge (pack fills only the servers the admin catalog
// lacks) is a strictly better v2 and is out of scope: it needs a
// merge rule for a server present in both with different URLs.
mcp_source_from_env(Some(remote_tool_secrets.clone())).or_else(|| {
mcp_source_from_packs(
&packs,
&tenant,
Some(remote_tool_secrets.clone()),
unit.as_deref(),
)
}),
)
.with_component_source(components)
.with_flow_source(flows)
.with_sorla_source(sorla)
.with_a2a_source(a2a)
.with_playbook_source(playbooks)
.with_share_policy(share_policy)
.with_user_ledger(ledger_binding);
// Mount the long-term-memory and knowledge (RAG) seams so IN-PROCESS
// `dw.agent` workers ground on the ingested corpus exactly as the
// out-of-process NATS serve path does (see [`build_agent_runtime`], which
// makes the identical call). The backends come from the agent-runtime
// extensions the binary registered (see `runtime_ext`); with none
// registered, or the operator env unset, this leaves `base` unchanged.
// Without this call the in-process handler's `runtime.knowledge` stayed
// `None`, so `knowledge_active()` was false and `search_knowledge` was
// never invoked — the model hallucinated instead of retrieving from the
// corpus that had already been ingested at boot.
let base = crate::runner::runtime_ext::attach_all(base).await;
// Knowledge delegated to a design-extension tool. Unconditional and not
// feature-gated (see `knowledge_ext`): it wraps whatever corpus backend
// an extension above left in place and acts only on a worker whose knowledge
// binding names `provider.knowledge.extension`.
// Beneath it, retrieval from a Greentic-operated Chronicle index server
// (`provider.knowledge.chronicle-index`), whose credentials resolve
// through the same manager and tenant as the worker's MCP credentials.
let base = crate::runner::knowledge_index::attach(
base,
Some(mcp_secrets_manager(&secrets)),
Some(tenant.clone()),
);
let base = crate::runner::knowledge_ext::attach(base, ext_runtime);
// Billing metering. `billing_meter` is the one [`resolve_billing_meter`]
// chose: the meter the embedding host installed for this unit (a
// deployed env-canvas unit's `WorkerUsageMeter`), else the
// env-configured cloud-commerce sink, identical to the
// `build_agent_runtime` serve path. Without either the in-process
// `dw.agent` node would run on the default `NoopBillingMeter`: its LLM
// spend never metered AND the credit gate never firing.
//
// Ship-dark: with no installed meter this stays a no-op until an
// operator sets GREENTIC_BILLING_BASE_URL + GREENTIC_BILLING_SERVICE_SECRET.
let billing_enabled = billing_meter.is_some();
let base = match billing_meter {
Some(meter) => base.with_billing_meter(meter),
None => base,
};
let runtime = Arc::new(base);
// `billing_enabled` is logged rather than left implicit: this path
// silently metered nothing for its whole existence, and a boot line
// stating it either way is what makes that visible to an operator.
tracing::info!(
agent_count,
tenant = %tenant,
billing_enabled,
"AW runtime constructed"
);
Some(runtime)
}
/// Wrap the shared in-process [`AgentRuntime`] (built by
/// [`build_runtime_with_stores`], including the mounted knowledge and
/// long-term-memory seams) in a flow-node handler. Both the Redis path
/// ([`build_agent_node_handler`]) and the ephemeral desktop path
/// ([`build_agent_node_handler_ephemeral`]) route through here.
///
/// Returns `None` when the runtime could not be built (extension-runtime init
/// failure — the only failure mode at this layer).
///
/// `audit_sink` (EPIC-B B-3) is forwarded verbatim to the constructed
/// [`RuntimeAgentNodeHandler`] — `None` keeps `dw.agent` execution on the
/// plain [`AgentRuntime::step`] path. `stream_observers` (R2) is likewise
/// forwarded verbatim — `None` keeps `execute` from consulting the
/// session-keyed streaming-observer registry at all.
///
/// `project_id` is the deployed unit's `bundle_id`, forwarded verbatim so
/// billing can attribute this runtime's spend to a project. `None` on the
/// legacy tenant-only path, where the dimension is omitted entirely.
#[allow(clippy::too_many_arguments)]
async fn build_runtime_handler_with_stores(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
state_store: Arc<dyn greentic_aw_runtime::state::AgentStateStore>,
token_meter: Arc<dyn greentic_aw_runtime::cost::TokenMeter>,
ledger: Arc<dyn greentic_aw_runtime::tools::ToolLedger>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
) -> Option<AgentNodeWiring> {
// The deployed unit (`bundle_id`) doubles as the MCP credential scope:
// the same identity billing attributes this runtime's spend to.
let runtime = build_runtime_with_stores(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
state_store,
token_meter,
ledger,
project_id.clone(),
billing_meter,
user_ledger,
)
.await?;
let handler: Arc<dyn AgentNodeHandler> = Arc::new(RuntimeAgentNodeHandler::new(
Arc::clone(&runtime),
audit_sink,
stream_observers,
project_id,
));
Some(AgentNodeWiring { handler, runtime })
}
/// The `dw.agent` handler together with the [`AgentRuntime`] it drives.
///
/// The runtime is exposed so other in-process node handlers of the SAME
/// `TenantRuntime` — the `operala.call` deep worker — can reuse its tool
/// catalogs, secrets scope and ledger instead of building a second,
/// divergent runtime.
pub struct AgentNodeWiring {
pub handler: Arc<dyn AgentNodeHandler>,
pub runtime: Arc<AgentRuntime>,
}
/// Build the production `DwAgent` handler if the environment is configured.
///
/// Returns `None` (so `DwAgent` flow dispatch errors clearly) under any of
/// these graceful-degradation conditions:
/// - `merged_agents` is empty (no agents from packs or operator config);
/// - `GREENTIC_AW_STATE_BACKEND=redis` with `GREENTIC_AW_REDIS_URL`
/// unset/empty;
/// - the AW Redis connection fails;
/// - the extension runtime fails to initialise.
///
/// An unset `GREENTIC_AW_REDIS_URL` on its own is NOT one of them: the
/// state backend then auto-selects the process-global in-memory store
/// (`aw_backends::build_aw_backends`), so this server path runs `dw.agent`
/// — and hands `operala.call` deep workers their tools — with no Redis.
///
/// `merged_agents` is the result of merging pack-embedded agents (base)
/// with operator-declared [`HostConfig::agents`] (operator wins on
/// collision). This merged map replaces the former direct read of
/// `config.agents` so pack-provided agents are included in the runtime.
///
/// Redis is sourced from the environment because the runner uses an
/// in-memory flow-state store by default and carries no Redis URL in
/// [`HostConfig`]; this mirrors the existing env-config convention.
///
/// The `tenant` and `secrets` arguments wire in per-tenant LLM credential
/// resolution when `GREENTIC_AW_LLM_EXTENSION` is set: requests resolve
/// credentials from the secrets broker for the calling tenant rather than
/// reading global env vars. Callers without per-tenant context (e.g.
/// `serve_agentic`) should use [`build_agent_runtime`] directly, which uses
/// the env-keyed backend and accepts no secrets context.
///
/// `audit_sink` (EPIC-B B-3) is threaded straight through to the
/// constructed [`RuntimeAgentNodeHandler`]; `None` (no NATS audit client
/// configured) keeps `dw.agent` execution on the plain
/// [`greentic_aw_runtime::AgentRuntime::step`] path — zero behaviour
/// change from before this parameter existed.
///
/// `project_id` is the deployed unit's `bundle_id` — the value
/// greentic-designer records as `pack_name` — used as the `project_id`
/// billing dimension. Pass `None` when no bundle is pinned (the legacy
/// tenant-only pack path); billing then omits the dimension instead of
/// attributing spend to a non-unique agent id.
#[allow(clippy::too_many_arguments)]
pub async fn build_agent_node_handler(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
) -> Option<Arc<dyn AgentNodeHandler>> {
// Boxed so this wrapper adds no depth to the caller's future layout:
// the runner-desktop `run_pack_async` future already sits close to
// rustc's query-depth limit.
Box::pin(build_agent_node_wiring(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
audit_sink,
stream_observers,
project_id,
))
.await
.map(|wiring| wiring.handler)
}
/// [`build_agent_node_handler`], also returning the [`AgentRuntime`] the
/// handler drives (see [`AgentNodeWiring`]). Same `None` conditions.
///
/// Bills through [`resolve_billing_meter`]`(None)` — the env-configured
/// cloud-commerce sink, or nothing — exactly as before the host seam
/// existed. A host that installs a per-unit meter goes through
/// `TenantRuntime::load_revision_with` instead.
#[allow(clippy::too_many_arguments)]
pub async fn build_agent_node_wiring(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
) -> Option<AgentNodeWiring> {
build_agent_node_wiring_metered(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
audit_sink,
stream_observers,
project_id,
resolve_billing_meter(None),
// The un-metered wrappers carry no host seam: no user ledger.
None,
)
.await
}
/// Which billing sink a runtime built for one unit installs.
///
/// - An installed meter (for a deployed env-canvas unit, greentic-start's
/// per-unit `greentic_aw_runtime::billing::WorkerUsageMeter`) AND the
/// env-configured [`greentic_aw_runtime::billing::HttpBillingMeter`]
/// (`GREENTIC_BILLING_BASE_URL` + `GREENTIC_BILLING_SERVICE_SECRET`):
/// a [`greentic_aw_runtime::billing::FanOutBillingMeter`] — usage goes to
/// both, and the credit gate is the env sink's. An installed meter must
/// never switch the cloud-commerce credit gate off.
/// - Installed only: that meter.
/// - Env only, or neither: exactly the behaviour before the seam existed —
/// the env sink, else `None` (the runtime's `NoopBillingMeter`).
///
/// Resolved ONCE per `TenantRuntime` and shared by its `dw.agent`,
/// agent-graph and deep-worker paths, so all three bill through the same
/// sink (and, for the HTTP sink, one wallet cache).
pub fn resolve_billing_meter(
installed: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
) -> Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>> {
use greentic_aw_runtime::billing::{BillingMeter, FanOutBillingMeter, HttpBillingMeter};
let env =
HttpBillingMeter::from_env().map(|meter| Arc::new(meter) as Arc<dyn BillingMeter>);
match (installed, env) {
(Some(installed), Some(env)) => {
Some(Arc::new(FanOutBillingMeter::new(env, installed)) as Arc<dyn BillingMeter>)
}
(Some(installed), None) => Some(installed),
(None, env) => env,
}
}
/// [`build_agent_node_wiring`] with an explicit, already-resolved billing
/// sink (see [`resolve_billing_meter`]).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn build_agent_node_wiring_metered(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
) -> Option<AgentNodeWiring> {
use crate::runner::aw_backends::{AwBackends, build_aw_backends};
if merged_agents.is_empty() {
return None;
}
let AwBackends {
state_store,
token_meter,
tool_ledger: ledger,
checkpoint_store: _,
} = build_aw_backends().await?;
build_runtime_handler_with_stores(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
state_store,
token_meter,
ledger,
audit_sink,
stream_observers,
project_id,
billing_meter,
user_ledger,
)
.await
}
/// Desktop/local builder: in-memory state, token meter, and ledger so
/// `gtc start` runs agents with NO external infra. State is ephemeral
/// (lost on process exit) — never used by the server path.
///
/// Returns `None` only when `merged_agents` is empty or the extension
/// runtime fails to initialise. Unlike [`build_agent_node_handler`] this
/// function never returns `None` due to a missing Redis URL, making it safe
/// for desktop environments where no Redis is available.
///
/// `project_id` mirrors [`build_agent_node_handler`]: the deployed unit's
/// `bundle_id`, or `None` when none is pinned (billing then omits the
/// dimension).
#[cfg(feature = "desktop-agent-ephemeral")]
#[allow(clippy::too_many_arguments)]
pub async fn build_agent_node_handler_ephemeral(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
) -> Option<Arc<dyn AgentNodeHandler>> {
// Boxed so this wrapper adds no depth to the caller's future layout:
// the runner-desktop `run_pack_async` future already sits close to
// rustc's query-depth limit.
Box::pin(build_agent_node_wiring_ephemeral(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
audit_sink,
stream_observers,
project_id,
))
.await
.map(|wiring| wiring.handler)
}
/// [`build_agent_node_handler_ephemeral`], also returning the
/// [`AgentRuntime`] the handler drives (see [`AgentNodeWiring`]). Bills
/// through [`resolve_billing_meter`]`(None)`, as before the host seam.
#[cfg(feature = "desktop-agent-ephemeral")]
#[allow(clippy::too_many_arguments)]
pub async fn build_agent_node_wiring_ephemeral(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
) -> Option<AgentNodeWiring> {
build_agent_node_wiring_ephemeral_metered(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
audit_sink,
stream_observers,
project_id,
resolve_billing_meter(None),
// The un-metered wrappers carry no host seam: no user ledger.
None,
)
.await
}
/// [`build_agent_node_wiring_ephemeral`] with an explicit, already-resolved
/// billing sink (see [`resolve_billing_meter`]).
#[cfg(feature = "desktop-agent-ephemeral")]
#[allow(clippy::too_many_arguments)]
pub(crate) async fn build_agent_node_wiring_ephemeral_metered(
merged_agents: HashMap<String, AgentConfig>,
tenant: String,
secrets: crate::secrets::DynSecretsManager,
ext_llm_port: Option<Arc<dyn greentic_ext_runtime::host_ports::LlmPort>>,
packs: Vec<Arc<crate::pack::PackRuntime>>,
audit_sink: Option<AuditSink>,
stream_observers: Option<crate::http::agent_stream::StreamObserverRegistry>,
project_id: Option<String>,
billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
) -> Option<AgentNodeWiring> {
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::mock::{MockAgentStateStore, NoopToolLedger};
use std::sync::OnceLock;
if merged_agents.is_empty() {
return None;
}
// Process-global in-memory state store, shared across every flow
// invocation in this process. The desktop runner rebuilds the agent
// handler on each `dw.agent` node call, so a per-call store would erase
// conversation memory between turns — a multi-turn agent could never
// act on a user's "yes" to a proposal made on the previous turn. A
// single shared store keeps memory alive for the lifetime of the
// process WITHOUT any external infrastructure (Redis remains optional,
// selected only when GREENTIC_AW_REDIS_URL is set). State is still lost
// on process exit — that is the documented desktop trade-off.
static EPHEMERAL_STATE_STORE: OnceLock<Arc<MockAgentStateStore>> = OnceLock::new();
tracing::warn!(
tenant = %tenant,
"AW desktop ephemeral state store (in-memory, process-global; persists across \
turns for this process, lost on exit)"
);
let state_store =
Arc::clone(EPHEMERAL_STATE_STORE.get_or_init(|| Arc::new(MockAgentStateStore::new())));
let token_meter = Arc::new(MockTokenMeter::new(0));
let ledger = Arc::new(NoopToolLedger);
build_runtime_handler_with_stores(
merged_agents,
tenant,
secrets,
ext_llm_port,
packs,
state_store,
token_meter,
ledger,
audit_sink,
stream_observers,
project_id,
billing_meter,
user_ledger,
)
.await
}
/// Construct the shared [`AgentRuntime`] from the environment.
///
/// Factored out of [`build_agent_node_handler`] so both the in-process
/// `dw.agent`/`agentic.call` flow node and the out-of-process NATS serve
/// mode ([`serve_agentic`]) build an identical runtime (Redis state, env-
/// resolved LLM backend, design extensions, agent config providers, MCP).
///
/// Returns `None` under the same graceful-degradation conditions as the node
/// handler: empty agent map, a disabled or unreachable state backend (see
/// [`build_agent_node_handler`]), or extension-runtime init failure.
pub async fn build_agent_runtime(
merged_agents: HashMap<String, AgentConfig>,
) -> Option<Arc<AgentRuntime>> {
use crate::runner::aw_backends::{AwBackends, build_aw_backends};
use greentic_aw_runtime::LayeredConfigProvider;
use greentic_aw_runtime::ManifestToolOverlayProvider;
use greentic_aw_runtime::OtelTelemetry;
use greentic_aw_runtime::config_provider::CachingConfigProvider;
if merged_agents.is_empty() {
return None; // nothing to serve
}
let AwBackends {
state_store,
token_meter,
tool_ledger: ledger,
checkpoint_store: _,
} = build_aw_backends().await?;
// Process-level serve path has no per-tenant secrets context, so tool
// secrets resolve from the env only. It also has no embedding host,
// so tier 1 (host-injected) never applies here.
//
// Tier 2 (this worker's own resolved backend) is deliberately NOT
// wired at this call site, even though `merged_agents` is guaranteed
// non-empty by the early return above. Closing it needs the same
// circular-dependency split `build_runtime_with_stores` uses: `llm`
// below comes from `build_llm_backend(&ext_runtime)`, which needs
// `ext_runtime` to exist first UNCONDITIONALLY (not only on a bridge
// branch, unlike `build_runtime_with_stores`), so it cannot be
// resolved before this call the way it is there. Left for a
// follow-up — the `tracing::warn!` below says so at run time, not
// only in this comment, so the gap stays visible rather than
// silently assumed fixed.
//
// NO pack-carried extensions here, for the same reason this path has no
// pack-backed MCP fallback (see the `mcp_source_from_env` call below):
// it is the process-level serve path, its agents come from
// `GREENTIC_AGENT_MANIFESTS_DIR`, and it holds no `PackRuntime` at all.
tracing::warn!(
"extension runtime LLM port: this process-level serve path holds agents but is \
not wired to tier 2 (the worker's own backend); an extension's host.llm.complete \
here still falls through to tier 3 (env-keyed) or tier 4 (unconfigured)"
);
let ext_runtime = build_ext_runtime(Arc::new(EnvSecretsBackend), None, None, &[])?;
// Prefer the LLM bridge extension when configured (LLM-as-extension);
// fall back to the env-keyed in-process OpenAI client otherwise.
// NOTE: this path has no per-tenant secrets context (it is used by
// `serve_agentic` and process-level in-proc serve). Per-tenant
// credential resolution is only available via `build_agent_node_handler`.
let llm = build_llm_backend(&ext_runtime);
let agent_count = merged_agents.len();
// Base config source = the merged agents (pack-embedded ⊕ operator,
// operator wins). Wrap in the manifest-tool overlay, then layer the
// admin agent registry on top when configured (registry first, overlay
// fallback); cache the result either way.
let overlay = ManifestToolOverlayProvider::new(
HostConfigProvider::new(merged_agents),
manifests_discovery_dir(),
);
let config_provider: Arc<dyn ConfigProvider> = match registry_from_env() {
Some(http) => Arc::new(CachingConfigProvider::new(LayeredConfigProvider::new(
http, overlay,
))),
None => Arc::new(CachingConfigProvider::new(overlay)),
};
let telemetry = Arc::new(OtelTelemetry);
let base = AgentRuntime::new(
config_provider,
state_store,
ext_runtime.clone(),
llm,
telemetry,
token_meter,
ledger,
// This process-level serve path has no per-tenant secrets context
// (see the `ext_runtime`/`llm` construction above), but a `local-wasm`
// MCP tool still needs to read its tenant secret — the tenant arrives
// per call and the URI is built from it. So supply the same
// env-built, tenant-agnostic secrets manager the flow-node path uses
// (`mcp_node::aw::secrets_from_env`, memoized once per process); the
// http transport ignores it, the local-wasm transport consumes it.
//
// NO pack-backed fallback here, unlike `build_runtime_with_stores`.
// This is the process-level serve path: its agents come from
// `GREENTIC_AGENT_MANIFESTS_DIR` and it holds no `PackRuntime` at
// all, so there is no `assets/mcp-routes.json` to read. A worker
// reached this way needs `GREENTIC_AW_ADMIN_ENDPOINT` +
// `GREENTIC_AW_ADMIN_TOKEN` for its `mcp:` tools to dispatch; its
// tools are still ADVERTISED to the LLM from the agent config's own
// `ToolRef` schemas.
mcp_source_from_env(crate::runner::mcp_node::aw::secrets_from_env()),
)
.with_guardrails(
{
let policy: Arc<dyn greentic_aw_runtime::guardrail::GuardrailPolicy> =
match guardrail_policy_from_env() {
Some(http) => Arc::new(http),
None => Arc::new(greentic_aw_runtime::guardrail::StaticGuardrailPolicy(
Vec::new(),
)),
};
policy
},
Arc::new(
greentic_aw_runtime::guardrail::ExtRuntimeGuardrailEvaluator {
ext_runtime: ext_runtime.clone(),
},
),
);
// Short-term ("working") memory: in-memory provider is always available
// (no external deps); the remember/recall tools stay gated by
// config.memory.short_term in the loop.
let base = base.with_short_term_memory(Arc::new(
greentic_aw_runtime::memory::InMemoryMemoryProvider::new(),
));
// Billing metering: install the HTTP sink when both env vars are set;
// fall back to the built-in no-op (billing disabled) otherwise.
// Ship-dark: no-op until GREENTIC_BILLING_BASE_URL +
// GREENTIC_BILLING_SERVICE_SECRET are configured by the operator.
let base =
if let Some(http_meter) = greentic_aw_runtime::billing::HttpBillingMeter::from_env() {
tracing::info!("billing metering enabled for digital-worker LLM usage");
base.with_billing_meter(std::sync::Arc::new(http_meter))
} else {
base
};
// Optionally attach operator-configured long-term memory and knowledge
// (document RAG) backends from the registered agent-runtime extensions
// (see `runtime_ext`). With none registered `base` passes unchanged.
let base = crate::runner::runtime_ext::attach_all(base).await;
// Knowledge delegated to a design-extension tool — the out-of-process
// serve path's copy of the mount above. See `knowledge_ext` for why the
// adapter reads its target per turn rather than per runtime: THIS is the
// path that serves many agents from one runtime.
// Chronicle-index retrieval beneath it. This path has no injected
// secrets manager or tenant, so credentials resolve through the
// environment's manager under each turn's own tenant.
let base = crate::runner::knowledge_index::attach(
base,
crate::runner::mcp_node::aw::secrets_from_env(),
None,
);
let base = crate::runner::knowledge_ext::attach(base, ext_runtime.clone());
let runtime = Arc::new(base);
tracing::info!(agent_count, "AW runtime constructed");
Some(runtime)
}
/// Run the agentic-worker runtime as a NATS-consuming service.
///
/// Builds the production [`AgentRuntime`] via [`build_agent_runtime`] and,
/// when it could be constructed, serves `greentic.agentic.request.v1`
/// forever via the shared `aw-event-bridge`. This is the out-of-process
/// (`agentic.call`) counterpart to the in-process `dw.agent` node.
///
/// When `GREENTIC_AW_REDIS_URL` is set and reachable the serve path wires
/// a [`greentic_aw_runtime::RedisDispatchLedger`] so JetStream at-least-once
/// redeliveries are short-circuited without re-running the LLM step. If the
/// Redis connect fails the ledger falls back to [`greentic_aw_runtime::NoopDispatchLedger`]
/// (idempotency disabled, warning logged) so serving is never blocked.
///
/// Returns `Ok(())` immediately (a no-op) when the runtime cannot be built
/// (e.g. no agents, no Redis) so the host can call this unconditionally.
pub async fn serve_agentic(
nats_url: &str,
merged_agents: HashMap<String, AgentConfig>,
) -> anyhow::Result<()> {
use greentic_aw_runtime::dispatch_ledger::RedisDispatchLedger;
use greentic_aw_runtime::{DispatchLedger, NoopDispatchLedger, RedisAgentStateStore};
match build_agent_runtime(merged_agents).await {
Some(runtime) => {
// Dispatch idempotency ledger: only Redis provides cross-redelivery
// caching, so it is wired only when the resolved state backend is
// Redis (URL present AND backend redis/unset). Memory/disk backends
// use the no-op ledger (at-least-once). Best-effort: a connect
// failure disables idempotency but never blocks serving.
let redis_url = std::env::var("GREENTIC_AW_REDIS_URL")
.ok()
.filter(|url| !url.is_empty());
// Derive "is Redis" from the SAME selector the backends use, so an
// unusual value (e.g. `GREENTIC_AW_STATE_BACKEND=cassandra` with a
// URL) can't disagree between the state store and the ledger gate.
let backend_env = std::env::var("GREENTIC_AW_STATE_BACKEND").ok();
let backend_is_redis = matches!(
crate::runner::aw_backends::select_state_backend(
backend_env.as_deref(),
redis_url.as_deref(),
None,
),
crate::runner::aw_backends::StateBackendChoice::Redis(_)
);
let (ledger, ledger_active): (Arc<dyn DispatchLedger>, bool) = match redis_url {
Some(url) if backend_is_redis => {
match RedisAgentStateStore::connect(&url).await {
Ok(store) => {
(Arc::new(RedisDispatchLedger::new(store.manager())), true)
}
Err(error) => {
tracing::warn!(
%error,
"dispatch ledger Redis connect failed; \
idempotency disabled"
);
(Arc::new(NoopDispatchLedger), false)
}
}
}
_ => (Arc::new(NoopDispatchLedger), false),
};
tracing::info!(
nats_url,
dispatch_ledger_active = ledger_active,
"agentic serve mode starting"
);
greentic_aw_runtime::serve::serve_with_ledger(nats_url, runtime, ledger).await
}
None => {
tracing::info!(
"agentic serve mode skipped: no agentic runtime could be constructed"
);
Ok(())
}
}
}
/// Load process-level base agent configs from the manifests directory.
///
/// Reads every `<agent_id>.json` file in [`manifests_discovery_dir`] as a
/// full [`AgentConfig`] (NOT the tool-only Digital Worker manifest consumed
/// by [`ManifestToolOverlayProvider`]). This is the ONLY process-level base
/// agent source: pack-embedded agents and `HostConfig::agents` are both
/// per-tenant and only materialise inside `TenantRuntime::from_packs`, so an
/// in-process serve started at process startup cannot see them.
///
/// Returns an empty map when the directory is absent or unreadable. Files
/// that fail to decode into an [`AgentConfig`], or whose `agent_id` does not
/// match the file stem, are logged and skipped so one malformed file never
/// aborts loading. The file stem is the authoritative key (the in-map id is
/// taken from the stem), mirroring the `<agent_id>.json` convention.
pub fn load_process_agent_configs() -> HashMap<String, AgentConfig> {
let dir = manifests_discovery_dir();
let entries = match std::fs::read_dir(&dir) {
Ok(entries) => entries,
Err(error) => {
tracing::debug!(
dir = %dir.display(),
error = %error,
"agent manifests dir not readable; no process-level agents loaded"
);
return HashMap::new();
}
};
let mut agents: HashMap<String, AgentConfig> = HashMap::new();
for entry in entries.flatten() {
let path = entry.path();
let is_json = path
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| ext.eq_ignore_ascii_case("json"));
if !is_json {
continue;
}
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let bytes = match std::fs::read(&path) {
Ok(bytes) => bytes,
Err(error) => {
tracing::warn!(path = %path.display(), error = %error, "agent config read failed; skipping");
continue;
}
};
match serde_json::from_slice::<AgentConfig>(&bytes) {
Ok(config) => {
if config.agent_id != stem {
tracing::warn!(
file_stem = stem,
agent_id = config.agent_id.as_str(),
"agent config id does not match filename; keying by filename"
);
}
agents.insert(stem.to_string(), config);
}
Err(error) => {
tracing::warn!(path = %path.display(), error = %error, "agent config decode failed; skipping");
}
}
}
agents
}
#[cfg(test)]
mod parked_card_tests {
use serde_json::json;
#[test]
fn a_failed_turn_with_a_kept_park_offers_its_reply_then_the_card() {
let mut out = json!({
"reply": super::SANITISED_ERROR_REPLY,
"trail": [],
"terminated_by": "error"
});
let card = json!({ "type": "AdaptiveCard", "body": [] });
super::reoffer_parked_card(&mut out, card.clone());
assert_eq!(out["terminated_by"], "awaiting_tool_input");
assert_eq!(out["reply"], super::SANITISED_ERROR_REPLY);
let rendered = crate::runner::engine::rendered_park(&out);
let items = rendered.as_array().expect("reply + card");
assert_eq!(items[0]["reply"], super::SANITISED_ERROR_REPLY);
assert_eq!(items[1], card);
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::llm::LlmResponse;
use greentic_aw_runtime::mock::{
MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockTelemetry, NoopToolLedger,
};
use greentic_aw_runtime::{AgentConfig, AgentLimits, LlmProviderRef};
use greentic_aw_runtime::{AgentRuntime, TenantContext};
use serde_json::json;
use super::*;
pub(crate) fn sample_agent_config(agent_id: &str) -> AgentConfig {
AgentConfig {
agent_id: agent_id.into(),
system_prompt: "sys".into(),
tools: vec![],
guardrails: vec![],
llm: LlmProviderRef {
provider: "openai".into(),
model: "gpt-4o-mini".into(),
credential_ref: None,
},
limits: AgentLimits::default(),
memory: None,
knowledge: None,
conversational: false,
opening_message: None,
on_text_while_parked: Default::default(),
}
}
#[tokio::test]
async fn execute_returns_reply_json() {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("pong".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let config_provider = MockConfigProvider::new();
let tenant = TenantContext::new("t", "e");
config_provider.insert(
&tenant,
"greeter",
AgentConfig {
agent_id: "greeter".into(),
system_prompt: "sys".into(),
tools: vec![],
guardrails: vec![],
llm: LlmProviderRef {
provider: "mock".into(),
model: "m".into(),
credential_ref: None,
},
limits: AgentLimits::default(),
memory: None,
knowledge: None,
conversational: false,
opening_message: None,
on_text_while_parked: Default::default(),
},
);
let config_provider = Arc::new(config_provider);
let token_meter = Arc::new(MockTokenMeter::new(0));
let ledger = Arc::new(NoopToolLedger);
let ext_runtime = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let runtime = Arc::new(AgentRuntime::new(
config_provider,
store,
ext_runtime,
llm,
telemetry,
token_meter,
ledger,
None,
));
let handler = RuntimeAgentNodeHandler::new(runtime, None, None, None);
let output = handler
.execute(
"t",
"e",
"greeter",
"sess-1",
&json!({"user_text": "ping"}),
false,
None,
)
.await
.expect("execute should succeed");
assert_eq!(output["reply"].as_str(), Some("pong"));
}
// -------------------------------------------------------------------
// `project_id` billing dimension = the deployed unit's bundle id
// -------------------------------------------------------------------
/// Captures the `TenantContext.project_id` of every billing emit the
/// agent loop makes, so a test can assert what `execute` actually
/// handed the sink rather than what it looks like it should have.
#[derive(Default)]
struct RecordingBillingMeter {
project_ids: std::sync::Mutex<Vec<Option<String>>>,
}
impl greentic_aw_runtime::billing::BillingMeter for RecordingBillingMeter {
fn emit<'a>(
&'a self,
tenant: &'a TenantContext,
_input_tokens: u64,
_output_tokens: u64,
_agent_id: &'a str,
_model: &'a str,
) -> std::pin::Pin<
Box<
dyn std::future::Future<
Output = Result<(), greentic_aw_runtime::billing::BillingError>,
> + Send
+ 'a,
>,
> {
self.project_ids
.lock()
.expect("recording meter lock poisoned")
.push(tenant.project_id.clone());
Box::pin(async { Ok(()) })
}
fn over_budget<'a>(
&'a self,
_tenant: &'a TenantContext,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>
{
Box::pin(std::future::ready(false))
}
}
/// Run one `execute` through a handler built with `project_id` and
/// return the project ids the billing sink observed.
async fn project_ids_seen_by_billing(project_id: Option<String>) -> Vec<Option<String>> {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("pong".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]));
let config_provider = MockConfigProvider::new();
config_provider.insert(
&TenantContext::new("t", "e"),
"greeter",
sample_agent_config("greeter"),
);
let meter = Arc::new(RecordingBillingMeter::default());
let runtime = Arc::new(
AgentRuntime::new(
Arc::new(config_provider),
Arc::new(MockAgentStateStore::new()),
Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap()),
llm,
Arc::new(MockTelemetry::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
None,
)
.with_billing_meter(meter.clone()),
);
RuntimeAgentNodeHandler::new(runtime, None, None, project_id)
.execute(
"t",
"e",
"greeter",
"sess-1",
&json!({"user_text": "ping"}),
false,
None,
)
.await
.expect("execute should succeed");
let seen = meter
.project_ids
.lock()
.expect("recording meter lock poisoned");
seen.clone()
}
#[tokio::test]
async fn execute_bills_the_pack_identity_as_project_id() {
let seen = project_ids_seen_by_billing(Some("customer.support".into())).await;
assert_eq!(
seen,
vec![Some("customer.support".to_string())],
"the deployed bundle id must reach the billing sink, not the in-pack agent id"
);
}
#[tokio::test]
async fn execute_bills_no_project_id_when_the_pack_identity_is_unknown() {
let seen = project_ids_seen_by_billing(None).await;
assert_eq!(
seen,
vec![None],
"an unknown pack identity must stay absent — never fall back to the agent id"
);
}
// -------------------------------------------------------------------
// Billing wiring on the in-process `dw.agent` path
// -------------------------------------------------------------------
/// The in-process `dw.agent` runtime must talk to the configured
/// billing service, exactly as the out-of-process serve path does.
///
/// Asserted through observable behaviour rather than by inspecting the
/// runtime: the agent loop consults `BillingMeter::over_budget` before
/// it touches the LLM or the state store, and the HTTP sink implements
/// that as `GET /v1/tenants/{tenant}/wallet`. So a request arriving at
/// the billing server proves a real meter is installed; with the
/// default `NoopBillingMeter` nothing is ever sent.
#[tokio::test]
#[serial_test::serial]
// `set_var`/`remove_var` are process-global; `serial` keeps them from
// racing other env-reading tests.
#[allow(unsafe_code)]
async fn in_process_handler_consults_the_configured_billing_service() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/v1/tenants/acme/wallet"))
// `available: 0` short-circuits the step at the credit gate, so
// the test never reaches the LLM backend or acquires a lock.
.respond_with(
wiremock::ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"available": "0"})),
)
.mount(&server)
.await;
// Pin extension discovery at an empty dir: without this the runtime
// scans the developer's real `~/.greentic/extensions`, which makes
// the test depend on machine state and cost ~45s locally.
let empty_extensions = tempfile::tempdir().expect("tempdir");
unsafe {
std::env::set_var("GREENTIC_BILLING_BASE_URL", server.uri());
std::env::set_var("GREENTIC_BILLING_SERVICE_SECRET", "secret");
std::env::set_var("GREENTIC_EXTENSIONS_DIR", empty_extensions.path());
}
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let handler = build_runtime_handler_with_stores(
agents,
"acme".to_string(),
crate::secrets::default_manager().expect("env secrets manager"),
None,
vec![],
Arc::new(MockAgentStateStore::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
None,
None,
None,
// No host-installed meter: the env-configured sink, exactly
// what every builder resolved before the seam existed.
resolve_billing_meter(None),
None,
)
.await
.expect("handler should build from mock stores")
.handler;
let _ = handler
.execute(
"acme",
"prod",
"greeter",
"s",
&json!({"user_text": "hi"}),
false,
None,
)
.await;
unsafe {
std::env::remove_var("GREENTIC_BILLING_BASE_URL");
std::env::remove_var("GREENTIC_BILLING_SERVICE_SECRET");
std::env::remove_var("GREENTIC_EXTENSIONS_DIR");
}
let wallet_calls = server
.received_requests()
.await
.unwrap_or_default()
.iter()
.filter(|r| r.url.path() == "/v1/tenants/acme/wallet")
.count();
assert!(
wallet_calls >= 1,
"in-process dw.agent must consult the billing service; got {wallet_calls} \
wallet requests, which means it is still running on NoopBillingMeter \
and its LLM spend is never metered"
);
}
/// A host-installed meter used by the billing tests below: records
/// every emit and every budget question, and answers `over`.
struct ProbeMeter {
emits: std::sync::atomic::AtomicUsize,
budget_asks: std::sync::atomic::AtomicUsize,
over: bool,
}
impl ProbeMeter {
fn new(over: bool) -> Arc<Self> {
Arc::new(Self {
emits: std::sync::atomic::AtomicUsize::new(0),
budget_asks: std::sync::atomic::AtomicUsize::new(0),
over,
})
}
}
impl greentic_aw_runtime::billing::BillingMeter for ProbeMeter {
fn emit<'a>(
&'a self,
_tenant: &'a TenantContext,
_input_tokens: u64,
_output_tokens: u64,
_agent_id: &'a str,
_model: &'a str,
) -> std::pin::Pin<
Box<
dyn std::future::Future<
Output = Result<(), greentic_aw_runtime::billing::BillingError>,
> + Send
+ 'a,
>,
> {
self.emits.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Box::pin(async { Ok(()) })
}
fn over_budget<'a>(
&'a self,
_tenant: &'a TenantContext,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>
{
self.budget_asks
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Box::pin(std::future::ready(self.over))
}
}
/// Build the in-process handler with `chosen` as its billing sink and
/// drive one turn for tenant `acme`.
async fn run_one_turn_billed_by(
chosen: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
) {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let handler = build_runtime_handler_with_stores(
agents,
"acme".to_string(),
crate::secrets::default_manager().expect("env secrets manager"),
None,
vec![],
Arc::new(MockAgentStateStore::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
None,
None,
Some("support-bot".to_string()),
chosen,
None,
)
.await
.expect("handler should build from mock stores")
.handler;
let _ = handler
.execute(
"acme",
"prod",
"greeter",
"s",
&json!({"user_text": "hi"}),
false,
None,
)
.await;
}
/// A host-installed meter (a deployed unit's `WorkerUsageMeter`) must
/// NOT switch off the env-configured cloud-commerce credit gate. With
/// both present the credit gate is the env sink's: the wallet is asked
/// (`available: 0` stops the step), and the installed meter — which has
/// no wallet — is never asked for a budget.
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn an_installed_meter_keeps_the_env_credit_gate() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/v1/tenants/acme/wallet"))
.respond_with(
wiremock::ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"available": "0"})),
)
.mount(&server)
.await;
let empty_extensions = tempfile::tempdir().expect("tempdir");
unsafe {
std::env::set_var("GREENTIC_BILLING_BASE_URL", server.uri());
std::env::set_var("GREENTIC_BILLING_SERVICE_SECRET", "secret");
std::env::set_var("GREENTIC_EXTENSIONS_DIR", empty_extensions.path());
}
let installed = ProbeMeter::new(false);
let chosen = resolve_billing_meter(Some(
Arc::clone(&installed) as Arc<dyn greentic_aw_runtime::billing::BillingMeter>
));
run_one_turn_billed_by(chosen).await;
unsafe {
std::env::remove_var("GREENTIC_BILLING_BASE_URL");
std::env::remove_var("GREENTIC_BILLING_SERVICE_SECRET");
std::env::remove_var("GREENTIC_EXTENSIONS_DIR");
}
let wallet_calls = server
.received_requests()
.await
.unwrap_or_default()
.iter()
.filter(|r| r.url.path() == "/v1/tenants/acme/wallet")
.count();
assert!(
wallet_calls >= 1,
"the env cloud-commerce credit gate must still run with a meter installed"
);
assert_eq!(
installed
.budget_asks
.load(std::sync::atomic::Ordering::SeqCst),
0,
"the installed recorder is never the credit gate"
);
}
/// With no env sink, the installed meter alone is the runtime's sink.
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn an_installed_meter_alone_is_the_sink_when_no_env_sink_is_configured() {
let empty_extensions = tempfile::tempdir().expect("tempdir");
unsafe {
std::env::remove_var("GREENTIC_BILLING_BASE_URL");
std::env::remove_var("GREENTIC_BILLING_SERVICE_SECRET");
std::env::set_var("GREENTIC_EXTENSIONS_DIR", empty_extensions.path());
}
// `over = true` stops the step at the gate, proving it was asked.
let installed = ProbeMeter::new(true);
let as_dyn =
Arc::clone(&installed) as Arc<dyn greentic_aw_runtime::billing::BillingMeter>;
let chosen = resolve_billing_meter(Some(Arc::clone(&as_dyn)));
assert!(
chosen.as_ref().is_some_and(|c| Arc::ptr_eq(c, &as_dyn)),
"no env sink → the installed meter itself, not a wrapper"
);
run_one_turn_billed_by(chosen).await;
unsafe {
std::env::remove_var("GREENTIC_EXTENSIONS_DIR");
}
assert!(
installed
.budget_asks
.load(std::sync::atomic::Ordering::SeqCst)
>= 1
);
}
/// With nothing installed, the choice is exactly the pre-seam one.
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn no_installed_meter_falls_back_to_the_env_configured_sink() {
unsafe {
std::env::remove_var("GREENTIC_BILLING_BASE_URL");
std::env::remove_var("GREENTIC_BILLING_SERVICE_SECRET");
}
assert!(resolve_billing_meter(None).is_none());
unsafe {
std::env::set_var("GREENTIC_BILLING_BASE_URL", "http://127.0.0.1:9");
std::env::set_var("GREENTIC_BILLING_SERVICE_SECRET", "secret");
}
let chosen = resolve_billing_meter(None);
unsafe {
std::env::remove_var("GREENTIC_BILLING_BASE_URL");
std::env::remove_var("GREENTIC_BILLING_SERVICE_SECRET");
}
assert!(chosen.is_some(), "the env-configured sink, as before");
}
// -------------------------------------------------------------------
// State-store prerequisite of the server (non-ephemeral) path
// -------------------------------------------------------------------
/// The SERVER builder — the one greentic-start and the distroless
/// image use, since they do not enable `desktop-agent-ephemeral` —
/// must build the agent runtime with NO Redis configured.
///
/// That runtime is also the tool surface `runtime.rs` hands to
/// `operala.call` deep workers (`OperalaToolContext`), so this pins
/// both halves of one claim: a Redis-less deployment runs `dw.agent`
/// AND gives its deep workers their tools. It was documented as the
/// opposite ("no state store: set GREENTIC_AW_REDIS_URL") after
/// `build_aw_backends` had already made Redis optional.
///
/// The control proves the assertion is about the backend selector,
/// not a builder that never returns `None`: naming the redis backend
/// without a URL is an honest misconfiguration and disables both.
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn server_builder_wires_the_agent_runtime_without_redis() {
let empty_extensions = tempfile::tempdir().expect("tempdir");
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::remove_var("GREENTIC_AW_REDIS_URL");
std::env::remove_var("GREENTIC_AW_STATE_BACKEND");
std::env::remove_var("GREENTIC_AW_STATE_PATH");
std::env::remove_var("GREENTIC_AW_LLM_EXTENSION");
std::env::set_var("GREENTIC_EXTENSIONS_DIR", empty_extensions.path());
}
async fn build() -> Option<AgentNodeWiring> {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
build_agent_node_wiring(
agents,
"acme".to_string(),
crate::secrets::default_manager().expect("env secrets manager"),
None,
vec![],
None,
None,
None,
)
.await
}
let without_redis = build().await;
unsafe {
std::env::set_var("GREENTIC_AW_STATE_BACKEND", "redis");
}
let explicit_redis_without_url = build().await;
unsafe {
std::env::remove_var("GREENTIC_AW_STATE_BACKEND");
std::env::remove_var("GREENTIC_EXTENSIONS_DIR");
}
assert!(
without_redis.is_some(),
"with GREENTIC_AW_REDIS_URL unset the server builder must fall back to \
the in-memory state store and build the runtime dw.agent and \
operala.call deep workers share"
);
assert!(
explicit_redis_without_url.is_none(),
"GREENTIC_AW_STATE_BACKEND=redis with no URL must disable the runtime"
);
}
// -----------------------------------------------------------------------
// audit_sink enable/disable branch (EPIC-B B-3)
// -----------------------------------------------------------------------
/// Build an [`AgentRuntime`] scripted to make one `remember` (host
/// built-in short-term-memory) tool call before replying "done". The
/// host built-in path fires `StepObserver::on_tool_call`/`on_tool_result`
/// without needing a real WASM extension dispatch, so it is the
/// cheapest way to drive a genuine tool call through `execute`.
fn runtime_with_scripted_remember_call(tenant_id: &str, env_id: &str) -> Arc<AgentRuntime> {
use greentic_aw_runtime::state::ToolCallRecord;
use greentic_aw_runtime::{InMemoryMemoryProvider, MemoryProviderRef, MemorySettings};
let llm = Arc::new(MockLlmBackend::new(vec![
Ok(LlmResponse {
content: None,
tool_calls: vec![ToolCallRecord {
call_id: "c1".into(),
extension_id: "host".into(),
tool_name: "remember".into(),
args: json!({"key": "k", "value": "v"}),
}],
tokens_in: 1,
tokens_out: 1,
}),
Ok(LlmResponse {
content: Some("done".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
}),
]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let config_provider = MockConfigProvider::new();
let tenant = TenantContext::new(tenant_id, env_id);
let mut cfg = sample_agent_config("greeter");
cfg.memory = Some(MemorySettings {
short_term: Some(MemoryProviderRef {
provider: "inmemory".into(),
capability: "cap://memory/short-term".into(),
params: Default::default(),
credential_ref: None,
}),
long_term: None,
});
config_provider.insert(&tenant, "greeter", cfg);
let config_provider = Arc::new(config_provider);
let token_meter = Arc::new(MockTokenMeter::new(0));
let ledger = Arc::new(NoopToolLedger);
let ext_runtime = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
Arc::new(
AgentRuntime::new(
config_provider,
store,
ext_runtime,
llm,
telemetry,
token_meter,
ledger,
None,
)
.with_short_term_memory(Arc::new(InMemoryMemoryProvider::new())),
)
}
#[tokio::test]
async fn execute_with_audit_sink_routes_through_step_with_observer_and_enqueues_events() {
let runtime = runtime_with_scripted_remember_call("t1", "e1");
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
let sink = AuditSink::from_sender(tx);
let handler = RuntimeAgentNodeHandler::new(runtime, Some(sink), None, None);
let output = handler
.execute(
"t1",
"e1",
"greeter",
"sess-1",
&json!({"user_text": "remember this"}),
false,
None,
)
.await
.expect("execute should succeed");
assert_eq!(output["reply"].as_str(), Some("done"));
let (subject, bytes) = rx.try_recv().expect("tool_call event enqueued");
assert_eq!(subject, "audit.t1.agent.tool_call");
let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
assert_eq!(value["payload"]["tool"], json!("remember"));
assert_eq!(value["payload"]["agent_id"], json!("greeter"));
let (subject, bytes) = rx.try_recv().expect("tool_result event enqueued");
assert_eq!(subject, "audit.t1.agent.tool_result");
let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
assert_eq!(value["payload"]["tool"], json!("remember"));
// EPIC-D D-1: a per-run metering event follows the per-step
// agent-audit events once the run completes successfully.
let (subject, bytes) = rx.try_recv().expect("metering event enqueued");
assert_eq!(subject, "audit.t1.metering.agent_run");
let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
assert_eq!(value["type"], json!("greentic.runner.metering.agent_run"));
assert_eq!(value["payload"]["unit"], json!("agent_run"));
assert_eq!(value["payload"]["quantity"], json!(1));
assert_eq!(value["payload"]["agent_id"], json!("greeter"));
assert_eq!(
value["payload"]["steps"],
json!(output["trail"].as_array().expect("trail is an array").len())
);
assert!(
rx.try_recv().is_err(),
"exactly three audit events enqueued (tool_call, tool_result, metering.agent_run)"
);
}
// -----------------------------------------------------------------------
// stream_observers registry lookup (R2)
// -----------------------------------------------------------------------
#[tokio::test]
async fn execute_routes_registered_stream_observer_and_receives_tool_events() {
use crate::http::agent_stream::StreamObserverRegistry;
use std::sync::Mutex;
// A recording StepObserver we register under the session id. The
// scripted-tool-call runtime (shared with the audit test above)
// drives `MockLlmBackend`, which does not stream token deltas, so
// this asserts on `on_tool_call`/`on_tool_result` (per the R2
// design note) rather than `on_token_delta`.
#[derive(Default)]
struct Rec {
hits: Mutex<Vec<String>>,
}
impl StepObserver for Rec {
fn wants_streaming(&self) -> bool {
true
}
fn on_tool_call(&self, name: &str, _call_id: &str, _args: &Value) {
self.hits.lock().unwrap().push(format!("c:{name}"));
}
fn on_tool_result(&self, name: &str, _call_id: &str, _result: &Value) {
self.hits.lock().unwrap().push(format!("r:{name}"));
}
fn on_tool_failed(&self, name: &str, _call_id: &str, _error: &Value) {
self.hits.lock().unwrap().push(format!("f:{name}"));
}
}
let runtime = runtime_with_scripted_remember_call("t1", "e1");
let registry: StreamObserverRegistry = Arc::new(dashmap::DashMap::new());
let rec = Arc::new(Rec::default());
registry.insert("sess-1".to_string(), rec.clone() as Arc<dyn StepObserver>);
let handler = RuntimeAgentNodeHandler::new(runtime, None, Some(registry), None);
let output = handler
.execute(
"t1",
"e1",
"greeter",
"sess-1",
&json!({"user_text": "remember this"}),
false,
None,
)
.await
.expect("execute should succeed");
assert_eq!(output["reply"].as_str(), Some("done"));
let hits = rec.hits.lock().unwrap();
assert!(
hits.iter().any(|h| h == "c:remember"),
"tool call forwarded to the registered stream observer: {hits:?}"
);
assert!(
hits.iter().any(|h| h == "r:remember"),
"tool result forwarded to the registered stream observer: {hits:?}"
);
}
#[tokio::test]
async fn execute_ignores_stream_registry_when_session_not_registered() {
use crate::http::agent_stream::StreamObserverRegistry;
// A registry that exists but has no entry for this session must
// behave exactly like `None` — no observer is built at all, so
// the plain `self.runtime.step(...)` path runs unchanged.
let runtime = runtime_with_scripted_remember_call("t1", "e1");
let registry: StreamObserverRegistry = Arc::new(dashmap::DashMap::new());
let handler = RuntimeAgentNodeHandler::new(runtime, None, Some(registry), None);
let output = handler
.execute(
"t1",
"e1",
"greeter",
"sess-1",
&json!({"user_text": "remember this"}),
false,
None,
)
.await
.expect("execute should succeed");
assert_eq!(output["reply"].as_str(), Some("done"));
}
#[tokio::test]
async fn execute_without_audit_sink_uses_plain_step_path_unchanged() {
// Same scripted tool call as the audited test above, but the
// handler carries no audit sink at all — proves the "off" branch
// (self.runtime.step, no observer constructed) still dispatches
// the tool call and returns the same reply, exactly as it did
// before AgentAuditObserver existed.
let runtime = runtime_with_scripted_remember_call("t1", "e1");
let handler = RuntimeAgentNodeHandler::new(runtime, None, None, None);
let output = handler
.execute(
"t1",
"e1",
"greeter",
"sess-1",
&json!({"user_text": "remember this"}),
false,
None,
)
.await
.expect("execute should succeed");
assert_eq!(output["reply"].as_str(), Some("done"));
}
#[test]
fn tenant_ctx_for_audit_uses_real_ids_when_valid() {
let ctx = super::tenant_ctx_for_audit("acme", "prod");
assert_eq!(ctx.tenant.as_str(), "acme");
assert_eq!(ctx.env.as_str(), "prod");
}
#[test]
fn tenant_ctx_for_audit_falls_back_to_local_on_invalid_ids() {
// Empty strings fail the newtype validation; the helper must not
// panic and should fall back to "local" for both fields.
let ctx = super::tenant_ctx_for_audit("", "");
assert_eq!(ctx.tenant.as_str(), "local");
assert_eq!(ctx.env.as_str(), "local");
}
#[tokio::test]
async fn host_config_provider_returns_config_for_known_agent() {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let provider = HostConfigProvider::new(agents);
let tenant = TenantContext::new("acme", "prod");
let resolved = provider
.agent_config(&tenant, "greeter")
.await
.expect("known agent resolves");
assert_eq!(resolved.agent_id, "greeter");
}
#[tokio::test]
async fn overlay_provider_replaces_tools_from_manifest() {
use greentic_aw_runtime::ManifestToolOverlayProvider;
use greentic_aw_runtime::config::ToolRef;
use greentic_aw_runtime::config_provider::ConfigProvider;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("greeter.json"),
r#"{"id":"greeter","display_name":"G",
"tenancy":{"tenant":"t","team_policy":"disabled"},
"locale":{"worker_default_locale":"en-US","policy":"worker_default",
"propagation":"current_task_only","output":"worker_default"},
"extension_tools":[{"extension_id":"greentic.tavily","extension_version":"1.0.0",
"tool_name":"web_search","description":"d","input_schema_json":"{\"type\":\"object\"}",
"capabilities":["agentic_worker"],"agentic_worker_metadata":{}}]}"#,
)
.unwrap();
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let provider = ManifestToolOverlayProvider::new(
HostConfigProvider::new(agents),
tmp.path().to_path_buf(),
);
let tenant = TenantContext::new("acme", "prod");
let cfg = provider.agent_config(&tenant, "greeter").await.unwrap();
assert_eq!(
cfg.tools,
vec![ToolRef {
extension_id: "greentic.tavily".into(),
tool_name: "web_search".into(),
description: None,
input_schema: None,
usage_note: None,
}]
);
}
#[test]
fn bridge_credential_defaults_provider_and_model() {
let c = super::bridge_credential(None, None, "sk-x".into(), None).unwrap();
assert_eq!(c.provider, "openai");
assert_eq!(c.model, "gpt-4o");
assert_eq!(c.api_key, "sk-x");
assert!(c.base_url.is_none());
}
#[test]
fn bridge_credential_honors_explicit_parts() {
let c = super::bridge_credential(
Some("anthropic".into()),
Some("claude-x".into()),
"sk-ant".into(),
Some("https://proxy".into()),
)
.unwrap();
assert_eq!(c.provider, "anthropic");
assert_eq!(c.model, "claude-x");
assert_eq!(c.base_url.as_deref(), Some("https://proxy"));
}
#[test]
fn bridge_credential_none_without_key() {
assert!(
super::bridge_credential(Some("openai".into()), None, " ".into(), None).is_none()
);
}
#[test]
fn bridge_credential_allows_a_keyless_provider_without_a_key() {
let c = super::bridge_credential(Some("ollama".into()), None, String::new(), None)
.expect("Ollama needs no API key, so an empty one must still build a credential");
assert_eq!(c.provider, "ollama");
assert!(c.api_key.is_empty());
}
#[test]
fn keyless_providers_do_not_require_an_api_key() {
for provider in ["ollama", "llamafile", "bedrock", "Ollama", " ollama "] {
assert!(
!super::provider_requires_api_key(Some(provider)),
"{provider} authenticates without an API key"
);
}
for provider in ["openai", "anthropic", "deepseek", "gemini"] {
assert!(
super::provider_requires_api_key(Some(provider)),
"{provider} needs an API key"
);
}
// Nothing named a provider, or a name nothing recognises: assume the
// historical OpenAI default, which needs a key.
assert!(super::provider_requires_api_key(None));
assert!(super::provider_requires_api_key(Some(" ")));
assert!(super::provider_requires_api_key(Some("not-a-provider")));
}
/// The local table and greentic-llm must agree, or a build without the
/// `greentic-llm-backend` feature judges keylessness differently from
/// one with it.
#[cfg(feature = "greentic-llm-backend")]
#[test]
fn keyless_table_matches_greentic_llm() {
for kind in greentic_llm::ProviderKind::all() {
assert_eq!(
super::keyless_table_requires_api_key(kind.as_str()),
kind.requires_api_key(),
"local keyless table disagrees with greentic-llm about {}",
kind.as_str()
);
}
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
fn ollama_without_a_key_selects_the_multi_provider_backend() {
assert!(
super::selects_multi_provider_backend_with("", Some("ollama"), None),
"an Ollama worker with no key must reach greentic-llm, not the \
OpenAI fall-through"
);
assert!(super::selects_multi_provider_backend_with(
" ",
Some("bedrock"),
None
));
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
fn openai_without_a_key_or_an_endpoint_keeps_the_openai_fall_through() {
// Nothing configured: the historical default really is OpenAI, and
// a keyless request to it is going to fail either way.
assert!(!super::selects_multi_provider_backend_with(
"",
Some("openai"),
None
));
assert!(!super::selects_multi_provider_backend_with(
" ", None, None
));
// A key still selects the multi-provider backend for everyone.
assert!(super::selects_multi_provider_backend_with(
"sk-x",
Some("openai"),
None
));
assert!(super::selects_multi_provider_backend_with(
"sk-x", None, None
));
}
/// `provider = "openai"` means "speaks the OpenAI protocol", not "is
/// api.openai.com". An operator who pointed the endpoint at a local
/// gateway had to invent a dummy key, because an empty one dropped them
/// onto a fall-through client that appends `/v1/...` to a base URL
/// already ending in `/v1` and 404s every request.
#[cfg(feature = "greentic-llm-backend")]
#[test]
fn a_configured_endpoint_makes_an_empty_key_legitimate() {
assert!(super::selects_multi_provider_backend_with(
"",
Some("openai"),
Some("http://127.0.0.1:11434/v1")
));
// Also for a provider nobody named at all.
assert!(super::selects_multi_provider_backend_with(
"",
None,
Some("http://127.0.0.1:1234/v1")
));
}
/// Blank and whitespace-only mean "configured nothing", matching how
/// `llm_openai::normalize_base_url` reads the same variable. Without
/// this, an env var someone exported empty would silently change which
/// backend every keyless deployment gets.
#[cfg(feature = "greentic-llm-backend")]
#[test]
fn a_blank_endpoint_is_not_a_configured_one() {
assert!(!super::selects_multi_provider_backend_with(
"",
Some("openai"),
Some("")
));
assert!(!super::selects_multi_provider_backend_with(
"",
Some("openai"),
Some(" ")
));
}
/// `#[serial_test::serial]` for the same reason as its sibling below
/// (`configured_llm_provider_is_stable_across_hashmap_orderings`):
/// this test also guards its assertions behind
/// `env_llm_provider().is_none()`, so it must join the same serial
/// group as the `EnvLlmPort` tests that mutate
/// `GREENTIC_LLM_PROVIDER` — without it, a parallel run can observe
/// the var mid-mutation between the guard check and the assertions.
#[test]
#[serial_test::serial]
fn configured_llm_provider_falls_back_to_an_agents_declared_provider() {
// No env var is read here beyond `GREENTIC_LLM_PROVIDER`, which this
// test does not set: the agent's own declaration must be found.
let mut agents = HashMap::new();
let mut agent = sample_agent_config("greeter");
agent.llm.provider = "ollama".into();
agents.insert("greeter".to_string(), agent);
// Only assert the agent leg when the env is not overriding it, so the
// test is not at the mercy of the developer's shell.
if super::env_llm_provider().is_none() {
assert_eq!(
super::configured_llm_provider(&agents).as_deref(),
Some("ollama")
);
assert_eq!(super::configured_llm_provider(&HashMap::new()), None);
}
}
/// `configured_llm_provider` iterated a HashMap, so a worker declaring
/// several agents with different providers got a provider chosen by hash
/// order — a different one across process starts, with nothing
/// reporting it. The pick must be stable.
///
/// `#[serial_test::serial]` because this test reads `GREENTIC_LLM_PROVIDER`
/// (via the `env_llm_provider().is_some()` guard below) and several
/// `EnvLlmPort` tests in this module set that same process-global env var
/// under their own `#[serial_test::serial]` — without joining that group,
/// a parallel run could observe the var mid-mutation between the guard
/// check and the assertions, failing for a reason that has nothing to do
/// with the sort this test actually exercises.
#[test]
#[serial_test::serial]
fn configured_llm_provider_is_stable_across_hashmap_orderings() {
if super::env_llm_provider().is_some() {
// The env leg wins by design; this test is about the agent leg.
return;
}
for _ in 0..50 {
let mut agents = HashMap::new();
for (id, provider) in [("zz", "ollama"), ("aa", "anthropic"), ("mm", "groq")] {
let mut agent = sample_agent_config(id);
agent.llm.provider = provider.into();
agents.insert(id.to_string(), agent);
}
assert_eq!(
super::configured_llm_provider(&agents).as_deref(),
Some("anthropic"),
"the sorted-first agent id must decide the provider"
);
}
}
#[tokio::test]
async fn host_config_provider_returns_not_found_for_unknown_agent() {
use greentic_aw_runtime::error::ConfigError;
let provider = HostConfigProvider::new(HashMap::new());
let tenant = TenantContext::new("acme", "prod");
let result = provider.agent_config(&tenant, "missing").await;
assert!(matches!(result, Err(ConfigError::AgentNotFound(_))));
}
// -----------------------------------------------------------------------
// merge_agent_sources tests
// -----------------------------------------------------------------------
#[test]
fn merge_pack_only_agent_resolves() {
let mut pack_agents = HashMap::new();
pack_agents.insert("pack-bot".to_string(), sample_agent_config("pack-bot"));
let merged = super::merge_agent_sources(pack_agents, HashMap::new());
assert!(merged.contains_key("pack-bot"));
assert_eq!(merged["pack-bot"].agent_id, "pack-bot");
}
#[test]
fn merge_operator_only_agent_resolves() {
let mut operator_agents = HashMap::new();
operator_agents.insert("op-bot".to_string(), sample_agent_config("op-bot"));
let merged = super::merge_agent_sources(HashMap::new(), operator_agents);
assert!(merged.contains_key("op-bot"));
assert_eq!(merged["op-bot"].agent_id, "op-bot");
}
#[test]
fn merge_operator_wins_on_collision() {
let mut pack_agents = HashMap::new();
let mut pack_config = sample_agent_config("shared-bot");
pack_config.system_prompt = "pack prompt".to_string();
pack_agents.insert("shared-bot".to_string(), pack_config);
let mut operator_agents = HashMap::new();
let mut operator_config = sample_agent_config("shared-bot");
operator_config.system_prompt = "operator prompt".to_string();
operator_agents.insert("shared-bot".to_string(), operator_config);
let merged = super::merge_agent_sources(pack_agents, operator_agents);
assert_eq!(merged.len(), 1);
assert_eq!(
merged["shared-bot"].system_prompt, "operator prompt",
"operator config must override pack config on agent_id collision"
);
}
// -----------------------------------------------------------------------
// agent_configs_from_manifest tests
// -----------------------------------------------------------------------
#[test]
fn deserialize_agent_blob_produces_correct_config() {
let blob = serde_json::json!({
"agent_id": "demo-agent",
"system_prompt": "You are helpful.",
"tools": [],
"llm": {
"provider": "openai",
"model": "gpt-4o-mini"
},
"limits": {
"max_iter": 5,
"timeout": 30,
"max_history_turns": 10,
"llm_retry_attempts": 2,
"llm_retry_backoff": 500,
"provider_failure_message": null,
"daily_token_cap_per_tenant": null
}
});
let config: AgentConfig =
serde_json::from_value(blob).expect("valid blob must deserialize");
assert_eq!(config.agent_id, "demo-agent");
assert_eq!(config.system_prompt, "You are helpful.");
assert_eq!(config.limits.max_iter, 5);
assert_eq!(config.limits.timeout, std::time::Duration::from_secs(30));
}
#[test]
fn agent_configs_from_manifest_skips_malformed_blobs() {
use std::collections::BTreeMap;
let mut blobs: BTreeMap<String, serde_json::Value> = BTreeMap::new();
// Valid agent blob
blobs.insert(
"good-agent".to_string(),
serde_json::json!({
"agent_id": "good-agent",
"system_prompt": "Valid.",
"tools": [],
"llm": { "provider": "openai", "model": "gpt-4o-mini" },
"limits": {
"max_iter": 8,
"timeout": 60,
"max_history_turns": 20,
"llm_retry_attempts": 3,
"llm_retry_backoff": 250,
"provider_failure_message": null,
"daily_token_cap_per_tenant": null
}
}),
);
// Malformed blob (missing required fields)
blobs.insert(
"bad-agent".to_string(),
serde_json::json!({ "broken": true }),
);
let configs = super::agent_configs_from_manifest("test-pack", &blobs);
assert_eq!(configs.len(), 1, "malformed blob must be skipped");
assert!(configs.contains_key("good-agent"));
assert!(!configs.contains_key("bad-agent"));
}
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn registry_from_env_requires_both_vars() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
assert!(super::registry_from_env().is_none());
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
}
assert!(
super::registry_from_env().is_none(),
"endpoint alone is not enough"
);
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
}
assert!(super::registry_from_env().is_some());
unsafe {
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
}
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn guardrail_policy_from_env_requires_both_vars() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
assert!(super::guardrail_policy_from_env().is_none());
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
}
assert!(
super::guardrail_policy_from_env().is_none(),
"endpoint alone is not enough"
);
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
}
assert!(super::guardrail_policy_from_env().is_some());
unsafe {
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
}
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn mcp_source_from_env_default_on_with_opt_out() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::remove_var("GREENTIC_AW_MCP");
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
// (a) Default-on: endpoint + token present, gate unset → Some.
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
}
assert!(
super::mcp_source_from_env(None).is_some(),
"MCP is on by default when admin credentials are configured"
);
// (b) Explicit opt-out wins even with full credentials.
unsafe {
std::env::set_var("GREENTIC_AW_MCP", "0");
}
assert!(
super::mcp_source_from_env(None).is_none(),
"GREENTIC_AW_MCP=0 disables MCP regardless of credentials"
);
// (b') Legacy opt-in value still enables (any non-"0" value does).
unsafe {
std::env::set_var("GREENTIC_AW_MCP", "1");
}
assert!(super::mcp_source_from_env(None).is_some());
// (c) Missing credential → None even without an opt-out.
unsafe {
std::env::remove_var("GREENTIC_AW_MCP");
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
}
assert!(
super::mcp_source_from_env(None).is_none(),
"no endpoint → no MCP source"
);
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
assert!(
super::mcp_source_from_env(None).is_none(),
"no token → no MCP source"
);
unsafe {
std::env::remove_var("GREENTIC_AW_MCP");
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
}
// -----------------------------------------------------------------------
// guardrail_denied_json tests
// -----------------------------------------------------------------------
#[test]
fn guardrail_denied_maps_to_structured_output() {
use greentic_aw_runtime::guardrail::GuardrailDirection;
let v = super::guardrail_denied_json(
GuardrailDirection::Inbound,
"permission_denied",
"blocked",
None,
);
assert_eq!(v["guardrail"]["blocked"], serde_json::json!(true));
assert_eq!(v["guardrail"]["direction"], serde_json::json!("inbound"));
assert_eq!(
v["guardrail"]["code"],
serde_json::json!("permission_denied")
);
assert_eq!(v["terminated_by"], serde_json::json!("guardrail_denied"));
assert_eq!(v["reply"], serde_json::json!("blocked"));
}
#[cfg(feature = "desktop-agent-ephemeral")]
#[tokio::test]
#[allow(unsafe_code)]
async fn ephemeral_builder_yields_handler_without_redis() {
// Remove Redis URL so we prove the ephemeral builder does not need it.
// SAFETY: single-threaded test; no concurrent env mutation.
unsafe {
std::env::remove_var("GREENTIC_AW_REDIS_URL");
}
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
// Build a minimal env-backed secrets manager (no broker configured in tests).
let secrets: crate::secrets::DynSecretsManager =
Arc::new(greentic_secrets_lib::env::EnvSecretsManager);
let handler = super::build_agent_node_handler_ephemeral(
agents,
"t1".to_string(),
secrets,
None,
Vec::new(),
None,
None,
None,
)
.await;
assert!(
handler.is_some(),
"ephemeral builder must not require Redis"
);
}
/// Regression guard for the in-process knowledge (RAG) mount.
///
/// Before the fix `build_runtime_with_stores` built the in-process
/// [`AgentRuntime`] via `AgentRuntime::new(...)` and returned it WITHOUT
/// mounting the corpus backend, so `runtime.knowledge` stayed `None`,
/// `knowledge_active()` was false and `search_knowledge` was never
/// invoked — the in-process `dw.agent` worker hallucinated instead of
/// grounding on the ingested corpus. The corpus backend now comes from a
/// registered [`crate::runner::runtime_ext::AgentRuntimeExtension`] (the
/// Chronicle one lives in a private crate), so this proves the in-process
/// path calls every registered extension, and does so BEFORE the
/// extension-delegated adapter wraps the result.
///
/// Asserted through [`crate::runner::knowledge_ext::corpus_backend`]
/// rather than `has_knowledge()`, and that is not cosmetic:
/// [`crate::runner::knowledge_ext::attach`] mounts unconditionally, so
/// `has_knowledge()` is true on this path whether the extension ran or
/// not. Asserting it would pass forever over a deleted
/// `runtime_ext::attach_all` — which is precisely the failure this was
/// written to catch. And a backend mounted AFTER the adapter would sit on
/// top of it and replace it, which `corpus_backend` would still find but
/// the adapter check below would not.
///
/// The extension is process-global once registered, so it acts only
/// inside this test's task-local scope and leaves every other test's
/// runtime untouched.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn in_process_runtime_attaches_registered_extensions() {
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::mock::{MockAgentStateStore, MockKnowledge, NoopToolLedger};
tokio::task_local! {
static IN_THIS_TEST: ();
}
struct CorpusExtension;
#[async_trait::async_trait]
impl crate::runner::runtime_ext::AgentRuntimeExtension for CorpusExtension {
async fn attach(&self, rt: AgentRuntime) -> AgentRuntime {
if IN_THIS_TEST.try_with(|_| ()).is_err() {
return rt;
}
rt.with_knowledge(Arc::new(MockKnowledge::new(Vec::new())))
}
}
static REGISTER: std::sync::Once = std::sync::Once::new();
REGISTER.call_once(|| {
crate::runner::runtime_ext::register_agent_runtime_extension(Arc::new(
CorpusExtension,
));
});
// Build the in-process runtime through the SAME shared tail both
// in-process handlers use (Redis + ephemeral), with cheap mock stores.
async fn build_runtime() -> Option<Arc<AgentRuntime>> {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let secrets: crate::secrets::DynSecretsManager =
Arc::new(greentic_secrets_lib::env::EnvSecretsManager);
let state_store: Arc<dyn greentic_aw_runtime::state::AgentStateStore> =
Arc::new(MockAgentStateStore::new());
let token_meter: Arc<dyn greentic_aw_runtime::cost::TokenMeter> =
Arc::new(MockTokenMeter::new(0));
let ledger: Arc<dyn greentic_aw_runtime::tools::ToolLedger> =
Arc::new(NoopToolLedger);
super::build_runtime_with_stores(
agents,
"t1".to_string(),
secrets,
None,
Vec::new(),
state_store,
token_meter,
ledger,
None,
None,
None,
)
.await
}
// Control: the extension declines outside the scope, so no corpus
// backend may be mounted — proving the positive case below is the
// extension doing its job, not a tautology.
let runtime_optout = build_runtime().await.expect("runtime should build");
assert!(
crate::runner::knowledge_ext::corpus_backend(&runtime_optout).is_none(),
"no corpus backend may be mounted when no extension provides one"
);
let runtime = IN_THIS_TEST
.scope((), build_runtime())
.await
.expect("runtime should build");
assert!(
crate::runner::knowledge_ext::corpus_backend(&runtime).is_some(),
"in-process dw.agent runtime must mount a registered extension's \
corpus backend, so an ingested corpus is retrievable"
);
let top = runtime
.knowledge_backend()
.expect("the extension adapter is always mounted");
assert!(
top.wrapped_backend().is_some(),
"the extension-delegated adapter must be the OUTER layer, wrapping \
the extension's corpus backend rather than being replaced by it"
);
}
/// In-memory `SecretsManager` for backend tests: returns seeded values,
/// `NotFound` otherwise.
struct MapSecrets(std::collections::HashMap<String, Vec<u8>>);
#[async_trait::async_trait]
impl greentic_secrets_lib::SecretsManager for MapSecrets {
async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
self.0
.get(path)
.cloned()
.ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
}
async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
Ok(())
}
async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
Ok(())
}
}
/// Build a backend for one unit over a seeded store.
fn backend_for(
unit: Option<&str>,
seed: &[(&str, &str)],
) -> super::StoreToolSecretsBackend {
let map = seed
.iter()
.map(|(uri, value)| (uri.to_string(), value.as_bytes().to_vec()))
.collect::<std::collections::HashMap<_, _>>();
super::StoreToolSecretsBackend {
secrets: Arc::new(MapSecrets(map)),
tenant: "acme".to_string(),
env: "dev".to_string(),
unit: unit.map(str::to_string),
}
}
fn tool_uri(provider: &str, key: &str, unit: Option<&str>) -> String {
crate::secrets::agent_tool_secret_uri("dev", "acme", provider, key, unit)
.expect("agent tool uri")
}
/// The defect this scope exists for: one environment, two workers, one
/// `hubspot/access_token`, two different accounts. Before the unit
/// segment both read one address and the second staged value won, so
/// one worker silently authenticated as the other's account.
#[test]
fn two_units_with_one_provider_and_key_each_read_their_own_value() {
use greentic_ext_runtime::SecretsBackend as _;
let seed = [
(
tool_uri("hubspot", "access_token", Some("sales-bot")),
"sales-token",
),
(
tool_uri("hubspot", "access_token", Some("support-bot")),
"support-token",
),
];
let seed: Vec<(&str, &str)> = seed
.iter()
.map(|(uri, value)| (uri.as_str(), *value))
.collect();
assert_eq!(
backend_for(Some("sales-bot"), &seed)
.get("secret://hubspot/access_token")
.expect("sales value"),
"sales-token"
);
assert_eq!(
backend_for(Some("support-bot"), &seed)
.get("secret://hubspot/access_token")
.expect("support value"),
"support-token"
);
}
/// A unit's own value beats the env-wide one left by an older stage.
#[test]
fn the_unit_scope_wins_over_the_env_wide_address() {
use greentic_ext_runtime::SecretsBackend as _;
let scoped = tool_uri("tavily", "api_key", Some("web-chat"));
let bare = tool_uri("tavily", "api_key", None);
let backend = backend_for(
Some("web-chat"),
&[(scoped.as_str(), "mine"), (bare.as_str(), "shared")],
);
assert_eq!(
backend.get("secret://tavily/api_key").expect("value"),
"mine"
);
}
/// The compatibility fallback: an environment staged before the unit
/// scope existed keeps resolving when its runner moves.
#[test]
fn a_unit_with_no_own_value_falls_back_to_the_env_wide_address() {
use greentic_ext_runtime::SecretsBackend as _;
let bare = tool_uri("tavily", "api_key", None);
let backend = backend_for(Some("web-chat"), &[(bare.as_str(), "shared")]);
assert_eq!(
backend.get("secret://tavily/api_key").expect("value"),
"shared"
);
}
/// With no unit — the legacy tenant-only path and the process-level
/// serve path — the env-wide address is the ONLY one tried, and a
/// unit-scoped value is never picked up by accident.
#[test]
fn no_unit_reads_exactly_the_env_wide_address() {
use greentic_ext_runtime::SecretsBackend as _;
let backend = backend_for(None, &[]);
assert_eq!(
backend.store_uri_candidates("secret://tavily/api_key"),
vec![tool_uri("tavily", "api_key", None)]
);
let scoped = tool_uri("tavily", "api_key", Some("web-chat"));
let other = backend_for(None, &[(scoped.as_str(), "someone-elses")]);
// Falls through to the env fallback, which has nothing either.
assert!(other.get("secret://tavily/api_key").is_err());
}
#[test]
fn the_candidates_are_the_unit_address_then_the_env_wide_one() {
let backend = backend_for(Some("web-chat"), &[]);
assert_eq!(
backend.store_uri_candidates("secret://tavily/api_key"),
vec![
tool_uri("tavily", "api_key", Some("web-chat")),
tool_uri("tavily", "api_key", None),
]
);
}
/// A reference with no `<provider>/<key>` split has no store address at
/// all, and must fall through to the env rather than build a malformed
/// URI.
#[test]
fn a_reference_with_no_key_has_no_store_candidates() {
let backend = backend_for(Some("web-chat"), &[]);
assert!(backend.store_uri_candidates("secret://tavily").is_empty());
}
#[test]
fn store_tool_secret_backend_maps_secret_uri_to_store_scope() {
use greentic_ext_runtime::SecretsBackend as _;
let mut map = std::collections::HashMap::new();
// The injected manager resolves the canonical store scope (in real
// runs its candidate fallback bridges to the pack scope; here we seed
// the canonical path the backend constructs directly).
map.insert(
"secrets://dev/acme/_/tavily/api_key".to_string(),
b"tvly-xyz".to_vec(),
);
let secrets: crate::secrets::DynSecretsManager = Arc::new(MapSecrets(map));
let backend = super::StoreToolSecretsBackend {
secrets,
tenant: "acme".to_string(),
env: "dev".to_string(),
unit: None,
};
let got = backend
.get("secret://tavily/api_key")
.expect("resolve tavily key from store");
assert_eq!(got, "tvly-xyz");
}
#[test]
#[allow(unsafe_code)]
fn store_tool_secret_backend_falls_back_to_env_on_store_miss() {
use greentic_ext_runtime::SecretsBackend as _;
let secrets: crate::secrets::DynSecretsManager =
Arc::new(MapSecrets(std::collections::HashMap::new()));
let backend = super::StoreToolSecretsBackend {
secrets,
tenant: "acme".to_string(),
env: "dev".to_string(),
unit: None,
};
// SAFETY: single-threaded test; no concurrent env mutation.
unsafe {
std::env::set_var("ZEROENV_MYPROVIDER_MYKEY", "from-env");
}
let got = backend
.get("secret://zeroenv_myprovider/mykey")
.expect("env fallback resolves");
assert_eq!(got, "from-env");
unsafe {
std::env::remove_var("ZEROENV_MYPROVIDER_MYKEY");
}
}
#[test]
#[allow(unsafe_code)]
fn load_process_agent_configs_reads_full_configs_and_skips_bad_files() {
let dir = tempfile::tempdir().expect("tempdir");
// Valid full AgentConfig keyed by file stem.
let good = sample_agent_config("greeter");
std::fs::write(
dir.path().join("greeter.json"),
serde_json::to_vec(&good).expect("serialize"),
)
.expect("write good");
// Malformed JSON — skipped, must not abort the load.
std::fs::write(dir.path().join("broken.json"), b"{ not json").expect("write broken");
// Non-JSON file — ignored.
std::fs::write(dir.path().join("README.md"), b"ignore me").expect("write md");
let previous = std::env::var("GREENTIC_AGENT_MANIFESTS_DIR").ok();
unsafe {
std::env::set_var("GREENTIC_AGENT_MANIFESTS_DIR", dir.path());
}
let loaded = super::load_process_agent_configs();
unsafe {
match &previous {
Some(value) => std::env::set_var("GREENTIC_AGENT_MANIFESTS_DIR", value),
None => std::env::remove_var("GREENTIC_AGENT_MANIFESTS_DIR"),
}
}
assert_eq!(loaded.len(), 1, "only the valid config should load");
assert!(loaded.contains_key("greeter"));
assert_eq!(loaded["greeter"].agent_id, "greeter");
}
#[test]
fn merge_sidecar_fills_only_missing_keys() {
use std::collections::BTreeMap;
let mut blobs: BTreeMap<String, serde_json::Value> =
BTreeMap::from([("a".to_string(), serde_json::json!({"from": "manifest"}))]);
let sidecar: BTreeMap<String, serde_json::Value> = BTreeMap::from([
("a".to_string(), serde_json::json!({"from": "sidecar"})), // must NOT override
("b".to_string(), serde_json::json!({"from": "sidecar"})), // must be added
]);
super::merge_sidecar_into(&mut blobs, sidecar);
assert_eq!(blobs["a"]["from"], "manifest"); // manifest wins
assert_eq!(blobs["b"]["from"], "sidecar"); // gap filled
assert_eq!(blobs.len(), 2);
}
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn flow_source_disabled_by_env_and_empty_packs() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::set_var("GREENTIC_AW_FLOW_TOOLS", "0");
}
assert!(
super::flow_source_from_packs(&[], "acme").is_none(),
"GREENTIC_AW_FLOW_TOOLS=0 must disable the flow tool source"
);
unsafe {
std::env::remove_var("GREENTIC_AW_FLOW_TOOLS");
}
assert!(
super::flow_source_from_packs(&[], "acme").is_none(),
"empty packs => None even when gate is unset"
);
}
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn pack_mcp_source_disabled_by_env_and_empty_packs() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::set_var("GREENTIC_AW_MCP", "0");
}
assert!(
super::mcp_source_from_packs(&[], "acme", None, None).is_none(),
"an operator who disabled outbound MCP must not have it \
re-enabled by a pack-carried sidecar"
);
unsafe {
std::env::remove_var("GREENTIC_AW_MCP");
}
assert!(
super::mcp_source_from_packs(&[], "acme", None, None).is_none(),
"empty packs => None even when the gate is unset"
);
}
/// Wiring guard: the in-process runtime built by
/// `build_runtime_with_stores` carries the pack-backed A2A source.
/// Without this, a dropped `.with_a2a_source(..)` fails only at run
/// time, as a bound tool that silently vanished.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn the_in_process_runtime_wires_the_pack_carried_a2a_source() {
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::mock::{MockAgentStateStore, NoopToolLedger};
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::remove_var("GREENTIC_AW_A2A");
std::env::remove_var("GREENTIC_AW_LLM_EXTENSION");
}
async fn build(pack_dir: &std::path::Path) -> Arc<AgentRuntime> {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let secrets: crate::secrets::DynSecretsManager =
Arc::new(greentic_secrets_lib::env::EnvSecretsManager);
let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(pack_dir));
super::build_runtime_with_stores(
agents,
"t1".to_string(),
secrets,
None,
vec![pack],
Arc::new(MockAgentStateStore::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
Some("worker-a".to_string()),
None,
None,
)
.await
.expect("runtime should build")
}
let with_sidecar = tempfile::tempdir().unwrap();
std::fs::create_dir_all(with_sidecar.path().join("assets")).unwrap();
std::fs::write(
with_sidecar.path().join("assets/a2a-routes.json"),
br#"[{"agent_id":"recipe","base_url":"https://agent.example.com"}]"#,
)
.unwrap();
assert!(
build(with_sidecar.path()).await.has_a2a_source(),
"a pack carrying assets/a2a-routes.json must wire an A2A source"
);
let without = tempfile::tempdir().unwrap();
assert!(
!build(without.path()).await.has_a2a_source(),
"control: no sidecar, no source"
);
}
/// Wiring guard: the in-process runtime carries the pack's sharing
/// policy. A dropped `.with_share_policy(..)` would only show as nested
/// calls that silently share nothing.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn the_in_process_runtime_wires_the_pack_carried_share_policy() {
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::mock::{MockAgentStateStore, NoopToolLedger};
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::remove_var("GREENTIC_AW_LLM_EXTENSION");
}
async fn build(pack_dir: &std::path::Path) -> Arc<AgentRuntime> {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let secrets: crate::secrets::DynSecretsManager =
Arc::new(greentic_secrets_lib::env::EnvSecretsManager);
let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(pack_dir));
super::build_runtime_with_stores(
agents,
"t1".to_string(),
secrets,
None,
vec![pack],
Arc::new(MockAgentStateStore::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
Some("worker-a".to_string()),
None,
None,
)
.await
.expect("runtime should build")
}
let with_sidecar = tempfile::tempdir().unwrap();
std::fs::create_dir_all(with_sidecar.path().join("assets")).unwrap();
std::fs::write(
with_sidecar.path().join("assets/run-context.json"),
br#"{"greeter":{"flow:refund":"read"}}"#,
)
.unwrap();
let rt = build(with_sidecar.path()).await;
assert!(
rt.share_policy()
.is_some_and(|p| p.has_sharing_binding("greeter"))
);
let without = tempfile::tempdir().unwrap();
assert!(
build(without.path()).await.share_policy().is_none(),
"control"
);
}
/// Wiring guard: the in-process runtime carries the user ledger only
/// when the host passed a target AND the pack names an agent. A dropped
/// `.with_user_ledger(..)` would only show as a ledger that never runs.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn the_in_process_runtime_carries_the_user_ledger_binding() {
use greentic_aw_runtime::cost::MockTokenMeter;
use greentic_aw_runtime::mock::{MockAgentStateStore, NoopToolLedger};
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::remove_var("GREENTIC_AW_LLM_EXTENSION");
std::env::remove_var("GREENTIC_AW_USER_LEDGER");
}
fn target() -> Option<greentic_aw_runtime::user_ledger::UserLedgerTarget> {
Some(greentic_aw_runtime::user_ledger::UserLedgerTarget::new(
"https://admin.example/api/v1/ingest/ledger",
"gtm_t",
"alpha",
))
}
async fn build(
pack_dir: &std::path::Path,
user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
) -> Arc<AgentRuntime> {
let mut agents = HashMap::new();
agents.insert("greeter".to_string(), sample_agent_config("greeter"));
let secrets: crate::secrets::DynSecretsManager =
Arc::new(greentic_secrets_lib::env::EnvSecretsManager);
let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(pack_dir));
super::build_runtime_with_stores(
agents,
"t1".to_string(),
secrets,
None,
vec![pack],
Arc::new(MockAgentStateStore::new()),
Arc::new(MockTokenMeter::new(0)),
Arc::new(NoopToolLedger),
Some("worker-a".to_string()),
None,
user_ledger,
)
.await
.expect("runtime should build")
}
let with_sidecar = tempfile::tempdir().unwrap();
std::fs::create_dir_all(with_sidecar.path().join("assets")).unwrap();
std::fs::write(
with_sidecar.path().join("assets/user-ledger.json"),
br#"{"greeter":"read_write"}"#,
)
.unwrap();
let rt = build(with_sidecar.path(), target()).await;
let binding = rt
.user_ledger()
.expect("a target plus a sidecar naming the agent must install a binding");
// Bound to the tenant the runtime was built for ("t1").
let alice = greentic_aw_runtime::VerifiedCaller {
user_verified: true,
sub: Some("alice".into()),
..Default::default()
};
let said = greentic_aw_runtime::AgentInput {
text: "hi".into(),
..Default::default()
};
assert!(
binding
.turn_for(
&TenantContext::new("t1", "e").with_caller(Some(alice.clone())),
"greeter",
&said
)
.is_some(),
"the binding must serve a verified turn of the runtime's own tenant"
);
assert!(
binding
.turn_for(
&TenantContext::new("other", "e").with_caller(Some(alice)),
"greeter",
&said
)
.is_none()
);
assert!(
build(with_sidecar.path(), None)
.await
.user_ledger()
.is_none(),
"control: a sidecar with no host target is off"
);
let without = tempfile::tempdir().unwrap();
assert!(
build(without.path(), target())
.await
.user_ledger()
.is_none(),
"control: a target with no sidecar is off"
);
}
/// The agent path prefers the env-configured ADMIN source and uses the
/// pack routes only as a fallback — deliberately the opposite of the
/// flow node, because the admin catalog carries LIVE tool schemas and
/// `allowed_tools` that a pack cannot. `or_else` is what makes the
/// fallback lazy, so an admin-backed deployment never even reads its
/// packs' sidecars; this pins that shape.
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn the_admin_source_wins_and_the_pack_fallback_is_never_consulted() {
use std::cell::Cell;
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "https://admin.example");
std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
std::env::remove_var("GREENTIC_AW_MCP");
}
let consulted = Cell::new(false);
let chosen = super::mcp_source_from_env(None).or_else(|| {
consulted.set(true);
super::mcp_source_from_packs(&[], "acme", None, None)
});
unsafe {
std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
}
assert!(chosen.is_some(), "the admin source must be built");
assert!(
!consulted.get(),
"the pack fallback must not be consulted when the admin \
credentials are present"
);
}
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn sorla_source_from_env_none_when_gate_opted_out() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::set_var("GREENTIC_AW_SORLA_TOOLS", "0");
std::env::set_var("GREENTIC_AW_SORX_URL", "http://localhost:9999");
}
assert!(
super::sorla_source_from_env().await.is_none(),
"GREENTIC_AW_SORLA_TOOLS=0 must disable the sorla tool source even with a URL set"
);
unsafe {
std::env::remove_var("GREENTIC_AW_SORLA_TOOLS");
std::env::remove_var("GREENTIC_AW_SORX_URL");
}
}
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn sorla_source_from_env_none_when_url_unset() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention).
unsafe {
std::env::remove_var("GREENTIC_AW_SORLA_TOOLS");
std::env::remove_var("GREENTIC_AW_SORX_URL");
}
assert!(
super::sorla_source_from_env().await.is_none(),
"no GREENTIC_AW_SORX_URL => no sorla source"
);
}
#[tokio::test]
#[serial_test::serial]
#[allow(unsafe_code)]
async fn sorla_source_from_env_some_when_url_set_even_if_sor_unreachable() {
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars cleaned up at the end.
unsafe {
std::env::remove_var("GREENTIC_AW_SORLA_TOOLS");
// Nothing listens here: `SorxHttpInvoker::fetch` must degrade to an
// empty-ops invoker (logged) rather than failing, so the source is
// still `Some` — a down/unreachable SoR must never block startup.
std::env::set_var("GREENTIC_AW_SORX_URL", "http://127.0.0.1:1");
}
let source = super::sorla_source_from_env().await;
unsafe {
std::env::remove_var("GREENTIC_AW_SORX_URL");
}
assert!(
source.is_some(),
"a configured URL yields Some(source) even when the SoR is unreachable"
);
}
/// The LLM-key env vars `EnvLlmPort::from_env` reads. Process-global, so
/// these tests serialize and restore them to avoid cross-test bleed.
#[cfg(feature = "greentic-llm-backend")]
const LLM_ENV_VARS: &[&str] = &[
"GREENTIC_LLM_API_KEY",
"OPENAI_API_KEY",
"GREENTIC_LLM_PROVIDER",
"GREENTIC_LLM_MODEL",
"GREENTIC_LLM_BASE_URL",
];
/// Run `body` with every LLM env var cleared, restoring prior values
/// afterwards. Keeps the `EnvLlmPort` tests hermetic and side-effect-free.
#[cfg(feature = "greentic-llm-backend")]
#[allow(unsafe_code)]
fn with_clean_llm_env(body: impl FnOnce()) {
let saved: Vec<(&str, Option<String>)> = LLM_ENV_VARS
.iter()
.map(|name| (*name, std::env::var(name).ok()))
.collect();
// SAFETY: #[serial] serializes env-mutating tests (crate convention),
// so no concurrent test observes a torn env; vars restored at the end.
unsafe {
for name in LLM_ENV_VARS {
std::env::remove_var(name);
}
}
body();
unsafe {
for (name, value) in saved {
match value {
Some(value) => std::env::set_var(name, value),
None => std::env::remove_var(name),
}
}
}
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
#[serial_test::serial]
fn env_llm_port_none_without_key() {
with_clean_llm_env(|| {
assert!(
super::EnvLlmPort::from_env().is_none(),
"no LLM key in env => no port (ext-runtime stays 'llm not configured')"
);
});
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn env_llm_port_some_with_key_and_defaults() {
with_clean_llm_env(|| {
// SAFETY: within `with_clean_llm_env` under #[serial].
unsafe {
std::env::set_var("GREENTIC_LLM_API_KEY", "sk-test-key");
}
let port = super::EnvLlmPort::from_env().expect("key present => port");
// Provider/model fall back to the DeepSeek-first defaults.
assert_eq!(port.provider, super::EnvLlmPort::DEFAULT_PROVIDER);
assert_eq!(port.model, super::EnvLlmPort::DEFAULT_MODEL);
});
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn env_llm_port_honours_provider_and_model_overrides() {
with_clean_llm_env(|| {
// OPENAI_API_KEY is the documented fallback for the key.
// SAFETY: within `with_clean_llm_env` under #[serial].
unsafe {
std::env::set_var("OPENAI_API_KEY", "sk-openai");
std::env::set_var("GREENTIC_LLM_PROVIDER", "openai");
std::env::set_var("GREENTIC_LLM_MODEL", "gpt-4o-mini");
}
let port = super::EnvLlmPort::from_env().expect("fallback key present => port");
assert_eq!(port.provider, "openai");
assert_eq!(port.model, "gpt-4o-mini");
});
}
#[cfg(feature = "greentic-llm-backend")]
#[test]
#[serial_test::serial]
#[allow(unsafe_code)]
fn env_llm_port_maps_request_without_network() {
use greentic_aw_runtime::state::ChatMessage;
use greentic_ext_runtime::host_ports::{LlmPortRequest, LlmPortResponseFormat};
with_clean_llm_env(|| {
// SAFETY: within `with_clean_llm_env` under #[serial].
unsafe {
std::env::set_var("GREENTIC_LLM_API_KEY", "sk-test-key");
}
let port = super::EnvLlmPort::from_env().expect("key present => port");
let request = LlmPortRequest {
system_prompt: "be a card generator".into(),
messages: vec![
("user".into(), "hello".into()),
("assistant".into(), "hi".into()),
("system".into(), "note".into()),
("weird".into(), "fallback-to-user".into()),
],
response_format: LlmPortResponseFormat::Json,
};
// Pure mapping — no provider is built, no network call.
let llm_request =
super::port_request_to_llm_request(request, &port.provider, &port.model);
assert_eq!(llm_request.system_prompt, "be a card generator");
assert!(llm_request.tools.is_empty(), "tools not exposed to ext LLM");
assert_eq!(llm_request.provider.provider, "deepseek");
assert_eq!(llm_request.history.len(), 4);
assert!(matches!(llm_request.history[0], ChatMessage::User { .. }));
assert!(matches!(
llm_request.history[1],
ChatMessage::Assistant { .. }
));
assert!(matches!(llm_request.history[2], ChatMessage::System { .. }));
// Unknown role falls back to a user turn.
assert!(matches!(llm_request.history[3], ChatMessage::User { .. }));
});
}
/// A marker `LlmPort` whose only job is to be distinguishable by
/// `Arc::ptr_eq` — these tests assert WHICH tier's candidate was
/// returned, never anything about a port's behaviour.
struct MarkerLlmPort;
impl greentic_ext_runtime::host_ports::LlmPort for MarkerLlmPort {
fn complete(
&self,
_extension_id: &str,
_ctx: &greentic_ext_runtime::host_ports::HostCallContext,
_role: &str,
_request: greentic_ext_runtime::host_ports::LlmPortRequest,
) -> Result<
greentic_ext_runtime::host_ports::LlmPortResponse,
greentic_ext_runtime::host_ports::LlmPortError,
> {
unreachable!("marker port for tier-selection tests; never invoked")
}
}
fn marker_port() -> Arc<dyn greentic_ext_runtime::host_ports::LlmPort> {
Arc::new(MarkerLlmPort)
}
/// Table-driven over all eight `(host, agent, env)` presence
/// combinations, asserting both WHICH TIER won (via the returned
/// `ExtLlmTier`) and which candidate's pointer came back. A test that
/// only ever supplies one candidate at a time (the earlier shape of
/// this test) cannot discriminate the precedence order at all — with
/// a single candidate present, every permutation of `.or()` returns
/// it regardless of order. Every row here has at least the winning
/// candidate plus, for every row but the all-absent one, a losing
/// candidate the function must reject in favour of it.
#[test]
fn select_ext_llm_port_precedence_table() {
use super::ExtLlmTier;
let cases: &[(bool, bool, bool, Option<ExtLlmTier>)] = &[
(true, true, true, Some(ExtLlmTier::Host)),
(true, true, false, Some(ExtLlmTier::Host)),
(true, false, true, Some(ExtLlmTier::Host)),
(true, false, false, Some(ExtLlmTier::Host)),
(false, true, true, Some(ExtLlmTier::Agent)),
(false, true, false, Some(ExtLlmTier::Agent)),
(false, false, true, Some(ExtLlmTier::Env)),
(false, false, false, None),
];
for &(host_present, agent_present, env_present, expected_tier) in cases {
let host = host_present.then(marker_port);
let agent = agent_present.then(marker_port);
let env = env_present.then(marker_port);
let expected_port = match expected_tier {
Some(ExtLlmTier::Host) => host.clone(),
Some(ExtLlmTier::Agent) => agent.clone(),
Some(ExtLlmTier::Env) => env.clone(),
None => None,
};
let picked = super::select_ext_llm_port(host.clone(), agent.clone(), env.clone());
match (picked, expected_tier, expected_port) {
(Some((tier, port)), Some(expected), Some(expected_port)) => {
assert_eq!(
tier, expected,
"host={host_present} agent={agent_present} env={env_present}: wrong tier won"
);
assert!(
Arc::ptr_eq(&port, &expected_port),
"host={host_present} agent={agent_present} env={env_present}: wrong candidate for the winning tier"
);
}
(None, None, None) => {}
(picked, _, _) => panic!(
"host={host_present} agent={agent_present} env={env_present}: expected {expected_tier:?}, got {:?}",
picked.map(|(tier, _)| tier)
),
}
}
}
/// The two `None`s in `build_runtime_with_stores` (the bridge arm's
/// hardcoded one, and the zero-env arm's `if`) both route through
/// `should_attempt_agent_llm_port` — this is the only place either
/// decision is actually exercised by a test, since `ExtensionRuntime`
/// has no `llm_port` accessor to assert on after the fact. All four
/// combinations: the bridge branch (`bridge_extension_configured`)
/// must always refuse regardless of the host port, and the zero-env
/// branch must attempt tier 2 only when the host has not already
/// supplied one.
#[test]
fn should_attempt_agent_llm_port_truth_table() {
let cases: &[(bool, bool, bool)] = &[
// (bridge_extension_configured, host_port_present, expected)
(false, false, true),
(false, true, false),
(true, false, false),
(true, true, false),
];
for &(bridge, host, expected) in cases {
assert_eq!(
super::should_attempt_agent_llm_port(bridge, host),
expected,
"bridge_extension_configured={bridge} host_port_present={host}"
);
}
}
}
}
#[allow(clippy::items_after_test_module)] // helper fn + re-exports follow
#[cfg(test)]
mod gating_tests {
use super::{DwAgentDispatch, dw_agent_dispatch_mode, should_serve_agentic_inproc};
use std::collections::HashMap;
fn env_from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect();
move |key: &str| map.get(key).cloned()
}
#[test]
fn skips_when_opt_in_unset() {
let env = env_from(&[("GREENTIC_EVENTS_NATS_URL", "nats://127.0.0.1:4222")]);
assert!(!should_serve_agentic_inproc(env));
}
#[test]
fn skips_when_nats_url_unset() {
let env = env_from(&[("GREENTIC_AGENTIC_SERVE_INPROC", "1")]);
assert!(!should_serve_agentic_inproc(env));
}
#[test]
fn skips_when_nats_url_blank() {
let env = env_from(&[
("GREENTIC_AGENTIC_SERVE_INPROC", "1"),
("GREENTIC_EVENTS_NATS_URL", " "),
]);
assert!(!should_serve_agentic_inproc(env));
}
#[test]
fn serves_when_both_set() {
for truthy in ["1", "true", "TRUE", "yes", "on"] {
let env = env_from(&[
("GREENTIC_AGENTIC_SERVE_INPROC", truthy),
("GREENTIC_EVENTS_NATS_URL", "nats://127.0.0.1:4222"),
]);
assert!(should_serve_agentic_inproc(env), "{truthy} should enable");
}
}
#[test]
fn skips_on_falsey_opt_in() {
for falsey in ["0", "false", "no", "off", "maybe"] {
let env = env_from(&[
("GREENTIC_AGENTIC_SERVE_INPROC", falsey),
("GREENTIC_EVENTS_NATS_URL", "nats://127.0.0.1:4222"),
]);
assert!(!should_serve_agentic_inproc(env), "{falsey} should skip");
}
}
#[test]
fn dw_agent_dispatch_mode_defaults_inproc_and_parses_nats() {
assert_eq!(dw_agent_dispatch_mode(|_| None), DwAgentDispatch::InProcess);
assert_eq!(
dw_agent_dispatch_mode(|k| (k == "GREENTIC_AW_DISPATCH").then(|| "nats".to_string())),
DwAgentDispatch::Nats
);
assert_eq!(
dw_agent_dispatch_mode(|k| {
(k == "GREENTIC_AW_DISPATCH").then(|| "inproc".to_string())
}),
DwAgentDispatch::InProcess
);
assert_eq!(
dw_agent_dispatch_mode(|k| (k == "GREENTIC_AW_DISPATCH").then(|| "NATS".to_string())),
DwAgentDispatch::Nats
);
}
}
/// Decide whether the runner process should host the agentic-worker NATS
/// service in-process (the opt-in co-host path).
///
/// Returns `true` only when BOTH gates are satisfied:
/// - `GREENTIC_AGENTIC_SERVE_INPROC` is truthy (`1`/`true`/`yes`/`on`,
/// case-insensitive) — opt-in, default OFF; and
/// - `GREENTIC_EVENTS_NATS_URL` is set to a non-empty value (no NATS bus means
/// nothing to serve on).
///
/// Pure over its `get_env` closure so it is unit-testable without touching the
/// real process environment. Feature-independent (no `agentic-worker` gate) so
/// the gating logic stays trivially testable; the actual spawn is gated at the
/// call site.
pub fn should_serve_agentic_inproc(get_env: impl Fn(&str) -> Option<String>) -> bool {
let opt_in = get_env("GREENTIC_AGENTIC_SERVE_INPROC")
.map(|value| {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
})
.unwrap_or(false);
let nats_set = get_env("GREENTIC_EVENTS_NATS_URL")
.map(|value| !value.trim().is_empty())
.unwrap_or(false);
opt_in && nats_set
}
/// How a `dw.agent` flow node executes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)] // consumed by Task 2.2 (engine.rs)
pub enum DwAgentDispatch {
/// Run the agentic step in-process (default; today's behaviour).
InProcess,
/// Publish to the durable agentic NATS path (scale-to-zero compute).
Nats,
}
/// Resolve how `dw.agent` nodes execute. `GREENTIC_AW_DISPATCH=nats` routes them
/// over the out-of-process agentic NATS path; anything else (incl. unset) keeps
/// the in-process path — zero regression by default. Pure over `get_env` for
/// testability (mirrors `should_serve_agentic_inproc`).
#[must_use]
#[allow(dead_code)] // consumed by Task 2.2 (engine.rs)
pub fn dw_agent_dispatch_mode(get_env: impl Fn(&str) -> Option<String>) -> DwAgentDispatch {
match get_env("GREENTIC_AW_DISPATCH") {
Some(v) if v.trim().eq_ignore_ascii_case("nats") => DwAgentDispatch::Nats,
_ => DwAgentDispatch::InProcess,
}
}
#[cfg(feature = "agentic-worker")]
pub use aw::{
AgentNodeWiring, HostConfigProvider, RuntimeAgentNodeHandler, agent_configs_from_manifest,
build_agent_node_handler, build_agent_node_wiring, build_agent_runtime,
load_process_agent_configs, merge_agent_sources, merge_sidecar_into, resolve_billing_meter,
serve_agentic,
};
#[cfg(feature = "desktop-agent-ephemeral")]
pub use aw::{build_agent_node_handler_ephemeral, build_agent_node_wiring_ephemeral};
#[cfg(feature = "agentic-worker")]
pub(crate) use aw::{
EnvSecretsBackend, build_agent_node_wiring_metered, build_ext_runtime, build_llm_backend,
component_source_from_packs, mcp_secrets_manager, mcp_source_from_env,
};
#[cfg(feature = "desktop-agent-ephemeral")]
pub(crate) use aw::build_agent_node_wiring_ephemeral_metered;
// `first_declared_llm_agent` itself needs only `agentic-worker`, but its only
// consumer outside this module is `ext_llm_port`, which is gated on
// `greentic-llm-backend` too — so re-exporting it unconditionally under plain
// `agentic-worker` would trip `unused_imports` on a build that has
// `agentic-worker` without `greentic-llm-backend`.
//
// Shared by every `LlmPort` impl in this crate — `EnvLlmPort` here and
// `crate::runner::ext_llm_port::AgentLlmPort` — so the request mapping and the
// dedicated-thread completion bridge exist in exactly one place. Both need
// `greentic-llm-backend` regardless of who calls them: `EnvLlmPort` already
// does, and `ext_llm_port` is gated on it too (it also needs
// `greentic_llm::ProviderKind`, which is only pulled in by that feature).
#[cfg(feature = "greentic-llm-backend")]
pub(crate) use aw::{complete_on_thread, first_declared_llm_agent, port_request_to_llm_request};
// Only consumed by `runtime.rs`'s in-process operala.call wiring, which is
// itself gated behind `operala-in-process` — re-exporting unconditionally
// under plain `agentic-worker` would trip `unused_imports` on builds that have
// `agentic-worker` without `operala-in-process`.
#[cfg(feature = "operala-in-process")]
pub(crate) use aw::resolve_in_process_llm_key;
// flow_source_from_packs is used only inside the aw module (build_runtime_handler_with_stores
// + tests) so it stays pub(crate) there without a top-level re-export.
// Test-only helpers other `runner` submodules' tests reuse rather than
// re-implementing. Its only consumer today is `ext_llm_port`'s test module
// (which needs an agent config to vary the provider/model on), and that
// module is itself gated on `greentic-llm-backend` (it uses
// `greentic_llm::ProviderKind` directly) — so this module must carry the
// same gate, not just `agentic-worker`, or an `agentic-worker`-only build
// (the crate's own DEFAULT feature set) sees `sample_agent_config` re-exported
// to nobody and trips `unused_imports`. Introduced in the task that added
// `ext_llm_port`; missing this gate broke `cargo clippy --all-targets
// --features agentic-worker -- -D warnings` from that point on, invisible
// until someone actually built test targets in that configuration.
#[cfg(all(test, feature = "agentic-worker", feature = "greentic-llm-backend"))]
pub(crate) mod test_support {
pub(crate) use super::aw::tests::sample_agent_config;
}