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
//! Plan-Act-Observe agent loop. Spec §5.3.
use std::collections::HashSet;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tracing::warn;
// Spelled `feature, test` (not `test, feature`) so the source-pinning tests
// that split this file at the first `all(test, feature = "test-mock")` marker
// still see the whole production half.
#[cfg(all(feature = "test-mock", test))]
#[path = "loop_resilience_tests.rs"]
mod resilience_tests;
use crate::error::{AgentError, LlmError, StateError, TerminationReason};
use crate::llm::{LlmBackend, LlmRequest};
use crate::state::ChatMessage;
use crate::telemetry::StepTelemetryCtx;
use crate::tenant::TenantContext;
use crate::tools::is_tool_allowed;
use crate::{AgentInput, AgentOutput, AgentRuntime, AgentStep, StepObserver, StepUsage};
/// Agents already warned about unavailable tools, so the loud preflight warning
/// fires once per agent per process (the loop resolves tools every iteration —
/// we must not warn on each one).
static PREFLIGHT_WARNED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
/// Emit one loud, actionable warning when an agent declares tools that will not
/// reach the LLM. No-op when nothing is missing; deduplicated per agent.
///
/// Without this the runtime drops unresolved tools silently and the agent runs
/// with a reduced — or empty — tool set, then fabricates tool results.
fn preflight_warn_tools(agent_id: &str, missing: &[crate::tools::MissingTool], declared: usize) {
if missing.is_empty() {
return;
}
let mut seen = PREFLIGHT_WARNED
.get_or_init(|| Mutex::new(HashSet::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !seen.insert(agent_id.to_string()) {
return;
}
let details = missing
.iter()
.map(|m| format!(" - {}/{}: {}", m.extension_id, m.tool_name, m.reason))
.collect::<Vec<_>>()
.join("\n");
let message = format!(
"agentic worker tools unavailable — the agent will hallucinate tool results \
until fixed:\n{details}\n fix: install the extension as a signed pack (with \
manifest.json) from the store, or run a dev-allow-unsigned runner with \
GREENTIC_EXT_ALLOW_UNSIGNED=1"
);
warn!(
agent = %agent_id,
missing = missing.len(),
declared,
"{}",
message
);
}
/// Await the per-step ledger read and tool-catalog resolve together while
/// keeping the session `lock` alive.
///
/// Both run under the lock, and a cold catalog resolve can outlast its TTL (90 s):
/// a local-wasm MCP pull is allowed `PULL_TIMEOUT` = 300 s and every other
/// server `PROBE_TIMEOUT` = 5 s. A lapsed lock is `LockLost` at the next
/// `ensure_lock_held`, which killed the turn (and JetStream acked it as
/// `invoke_failed`). So refresh every `every`, like every other long await in
/// this loop.
async fn resolve_under_lock<L, C>(
lock: &crate::state::SessionLock,
every: std::time::Duration,
ledger_read: L,
catalogs: C,
) -> (L::Output, C::Output)
where
L: std::future::Future,
C: std::future::Future,
{
crate::lock_keepalive::keep_alive(lock, every, async { tokio::join!(ledger_read, catalogs) })
.await
}
/// Stop the step when its session lock is no longer ours.
///
/// A refresh that fails for a transient reason only logs (losing one
/// extension is preferable to aborting a partially-complete turn), but a lock
/// that is genuinely gone means another worker may now own the session:
/// carrying on would let two turns race and the last save win.
async fn ensure_lock_held(lock: &crate::state::SessionLock) -> Result<(), AgentError> {
match lock.refresh().await {
Ok(()) => Ok(()),
Err(StateError::LockLost) => {
warn!("session lock lost mid-step; aborting without saving");
Err(AgentError::LockLost)
}
Err(e) => {
warn!(error = %e, "lock refresh failed; continuing");
Ok(())
}
}
}
/// Whether `call` addresses a host built-in tool (`recall_memory`,
/// `remember`, `recall`, `end_conversation`): the reserved `host` extension AND
/// the tool name. Matching the name alone would let any MCP/component tool
/// that happens to be called `recall` be silently routed to host memory.
fn is_host_tool(call: &crate::state::ToolCallRecord, tool_name: &str) -> bool {
call.extension_id == HOST_EXTENSION_ID && call.tool_name == tool_name
}
/// Extension id the host built-in tools are declared under.
const HOST_EXTENSION_ID: &str = "host";
/// Record the telemetry for a step that ends in an error. Without this an
/// LLM failure or a lost lock left no trace in the step metrics.
#[allow(clippy::too_many_arguments)]
fn record_error_exit(
runtime: &AgentRuntime,
tenant: &TenantContext,
session_id: &str,
agent_id: &str,
iterations: u32,
total_tokens: u64,
started: Instant,
) {
runtime.telemetry.record_step(&StepTelemetryCtx {
tenant_id: tenant.tenant_id.clone(),
env_id: tenant.env_id.clone(),
session_id: session_id.to_string(),
agent_id: agent_id.to_string(),
terminated_by: TerminationReason::Error,
iterations,
total_tokens,
duration: started.elapsed(),
});
}
/// One agent turn.
///
/// When a run context is open, the turn runs under a re-scoped copy whose
/// `caller_policy` is THIS agent's bindings, so every nested call it makes —
/// a new `flow:` call, the resume of a parked one, a `playbook:` call — is
/// judged against the agent that made it. This is the only place that sets
/// the policy for an agent turn. A context bound to another tenant is
/// replaced by a detached one, so nothing below can reach its trace.
pub async fn run_step(
runtime: &AgentRuntime,
tenant: TenantContext,
session_id: &str,
agent_id: &str,
message: AgentInput,
observer: Arc<dyn StepObserver>,
) -> Result<AgentOutput, AgentError> {
let Some(ctx) = crate::run_trace::RunContext::current() else {
return run_step_scoped(runtime, tenant, session_id, agent_id, message, observer).await;
};
let ctx = if ctx.tenant_id() == tenant.tenant_id {
ctx.with_caller_policy(runtime.share_modes_for(agent_id))
} else {
warn!(
context_tenant = ctx.tenant_id(),
step_tenant = %tenant.tenant_id,
"ignoring a run context bound to another tenant"
);
crate::run_trace::RunContext::detached(tenant.tenant_id.clone())
};
crate::run_trace::RunContext::scope(
ctx,
run_step_scoped(runtime, tenant, session_id, agent_id, message, observer),
)
.await
}
async fn run_step_scoped(
runtime: &AgentRuntime,
tenant: TenantContext,
session_id: &str,
agent_id: &str,
message: AgentInput,
observer: Arc<dyn StepObserver>,
) -> Result<AgentOutput, AgentError> {
let started = Instant::now();
let config = runtime
.config_provider
.agent_config(&tenant, agent_id)
.await?;
// The run this step belongs to, if the caller opened one (see
// `RunContext::scope`). `run_step` has already replaced a context bound to
// another tenant with a detached one; the tenant check stays as a second
// guard. A `none`-mode context is treated exactly like no context.
let run_ctx = crate::run_trace::RunContext::current().filter(|c| {
c.tenant_id() == tenant.tenant_id && c.mode() != crate::share_policy::ShareMode::None
});
let run_trace = run_ctx.as_ref().map(|c| c.trace().clone());
// Only a read-write context records; a read-only one shows the view.
let record_to = run_ctx
.as_ref()
.filter(|c| c.mode() == crate::share_policy::ShareMode::ReadWrite)
.map(|c| c.trace().clone());
// Who this step is, for the owned tool outcomes it records and the view it
// reads: a raw result is shown only to the step that called the tool.
let step_id = crate::run_trace::StepId::fresh();
// --- Cost budget gate (spec Decision 14) ---
if let Some(cap) = config.limits.daily_token_cap_per_tenant {
let used = runtime.token_meter.current(&tenant).await?;
if used >= u64::from(cap) {
return Err(AgentError::TokenBudgetExceeded);
}
}
// --- Credit balance gate (Slice D2): fail-open on billing unavailability ---
if runtime.billing_meter.over_budget(&tenant).await {
return Err(AgentError::CreditBudgetExceeded);
}
// --- Acquire distributed lock (default wait 5s) ---
let lock = runtime
.state_store
.acquire_lock(&tenant, session_id, Duration::from_secs(5))
.await
.map_err(|e| match e {
crate::error::StateError::LockTimeout(_) => AgentError::LockTimeout,
other => AgentError::from_state_error(other),
})?;
// --- Load state ---
// Only a stored state or a genuinely missing key (the store returns an
// empty state for that) may start the turn. Any other failure (backend
// blip, undecodable or too-new state) aborts WITHOUT saving: starting
// empty would let the end-of-turn save overwrite the stored conversation.
let mut state = match runtime.state_store.load(&tenant, session_id).await {
Ok(s) => s,
Err(e) => {
warn!(error = %e, "state load failed; aborting the turn without saving");
return Err(AgentError::from_state_error(e));
}
};
// --- Opening-message short-circuit ---
// On the FIRST turn with no user text (the flow entered the agent via a
// button/card rather than a typed message), reply with the author-configured
// opening message instead of spending an LLM call to fabricate a greeting.
// Recorded in state so the conversation has context; `FinalReply` so a
// conversational agent then parks, awaiting the user's real first message.
if state.messages.is_empty()
&& message.text.trim().is_empty()
&& let Some(opening) = config
.opening_message
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
let opening = opening.to_string();
state.messages.push(ChatMessage::Assistant {
content: opening.clone(),
tool_calls: vec![],
});
if let Err(e) = runtime.state_store.save(&tenant, session_id, &state).await {
warn!(error = %e, "state save failed after opening message");
}
return Ok(AgentOutput {
reply: opening,
trail: Vec::new(),
terminated_by: TerminationReason::FinalReply,
usage: StepUsage::default(),
pending_presentation: None,
side_turn: false,
});
}
// --- A flow tool parked on the user last turn ---
// Its `call_id` has no tool result in history yet, and nothing may reach
// the LLM until it does. Either resume the flow with the user's answer
// (below, once the tool catalogs are resolved) or cancel it here.
let (resuming, cancelled_step, side_pending) = match crate::flow_suspend::take_pending(
&mut state,
message.resume_payload.clone(),
chrono::Utc::now(),
observer.as_ref(),
config.on_text_while_parked,
) {
crate::flow_suspend::Taken::Nothing => (None, None, false),
crate::flow_suspend::Taken::Resume(resume) => (Some(resume), None, false),
crate::flow_suspend::Taken::Cancelled(step) => (None, Some(step), false),
// The park stays; this turn answers the typed message and re-offers it.
crate::flow_suspend::Taken::Side => (None, None, true),
};
let resumed_after_side_turns = resuming
.as_ref()
.is_some_and(|resume| resume.pending.side_turns > 0);
// --- Assemble guardrail chain (once per step, before any message push) ---
// Mandatory refs from the platform policy are resolved first; if any
// mandatory guardrail cannot be resolved the agent is blocked (fail-closed).
let guardrail_chain = {
let registry = runtime.ext_runtime.capability_registry();
let mandatory = match runtime.guardrail_policy.mandatory_guardrails(&tenant).await {
Ok(m) => m,
Err(e) => {
warn!(error = %e, "mandatory guardrail policy unavailable; failing closed");
return Err(AgentError::GuardrailDenied {
direction: crate::guardrail::GuardrailDirection::Inbound,
code: "internal".to_string(),
message: "A required guardrail is unavailable.".to_string(),
details: serde_json::to_string(
&serde_json::json!({ "policy_unavailable": true }),
)
.ok(),
});
}
};
match crate::guardrail::assemble_chain(®istry, &mandatory, &config.guardrails) {
Ok(chain) => chain,
Err(unresolved) => {
return Err(AgentError::GuardrailDenied {
direction: crate::guardrail::GuardrailDirection::Inbound,
code: "internal".to_string(),
message: "A required guardrail is unavailable.".to_string(),
details: serde_json::to_string(
&serde_json::json!({ "unresolved_mandatory": unresolved }),
)
.ok(),
});
}
}
};
let guardrail_ctx = crate::guardrail::GuardrailRunCtx {
agent_id: agent_id.to_string(),
session_id: session_id.to_string(),
tenant_id: tenant.tenant_id.clone(),
env_id: tenant.env_id.clone(),
};
// --- User ledger (shared context, Phase C): what this signed-in user did
// in any unit of the environment. Off unless the host installed a ledger,
// the pack names this agent, the caller is provider-verified and this is
// a TOP-LEVEL step (`turn_for` refuses inside a tool call frame, i.e. a
// nested agent of a `flow:` tool). `turn_for` must run here, on the
// step's own task: the nested check reads a task-local that a
// `tokio::spawn` would lose. The read runs alongside the catalog
// resolution (same task, no spawn) so the lock-held wait it can add is at
// most `READ_TIMEOUT` minus that time; a slow, failing or suspended
// ledger injects nothing and never fails the turn.
//
// Not subject to the #828 share modes in this version: the ledger is
// keyed by the verified caller, not by the run, and nested agents never
// see it. The view goes into this step's system prompt only and is never
// appended to the run trace.
//
// Decided here, before the inbound guardrail consumes `message.text`:
// `turn_for` judges the RAW input, and a turn the visitor did not take
// (blank text, no submit payload — a channel's auto-start turn) gets a
// handle that reads but never appends (`user_ledger::visitor_spoke`).
let ledger_turn = runtime
.user_ledger
.as_ref()
.and_then(|binding| binding.turn_for(&tenant, agent_id, &message));
// --- Inbound guardrail hook ---
// Skipped when resuming a parked flow tool: the user's answer goes to the
// flow, not the LLM, and returns as a tool result like any other tool's.
let attachments = message.attachments;
// The answer to a parked flow goes to the flow, which takes no files: the
// count is kept so the agent is told after the resume, never silently.
let resume_attachment_count = if resuming.is_some() {
attachments.len()
} else {
0
};
let user_message = if resuming.is_some() {
crate::flow_suspend::last_user_text(&state)
} else {
let user_text = match crate::guardrail::run_chain_blocking(
&guardrail_chain,
crate::guardrail::GuardrailDirection::Inbound,
message.text,
&guardrail_ctx,
runtime.guardrail_evaluator.clone(),
)
.await
{
crate::guardrail::ChainOutcome::Pass {
content,
observations,
} => {
for obs in &observations {
observer.on_guardrail(obs);
}
content
}
crate::guardrail::ChainOutcome::Denied {
info,
direction,
observation,
} => {
observer.on_guardrail(&observation);
return Err(AgentError::GuardrailDenied {
direction,
code: info.code,
message: info.message,
details: info.details,
});
}
};
// Keep user_message for long-term memory recall query below.
let user_message = user_text.clone();
state.messages.push(ChatMessage::User {
content: user_text,
attachments,
});
user_message
};
// The SAME inbound chain that checked the message text checks every
// attachment document's text, inside the backend, before it reaches the
// prompt (once per turn: it runs within the per-turn attachment memo).
// ALSO on a resume: no new user message is pushed then, but the last user
// message still carries its attachments, and the backend materialises
// them again for this turn, so they must pass the chain again. Only the
// message-text chain is skipped on a resume (the answer goes to the flow).
let attachment_text_guard = crate::attachment_guard::InboundChainGuard::for_turn(
&guardrail_chain,
&guardrail_ctx,
runtime.guardrail_evaluator.clone(),
observer.clone(),
);
// Whether long-term memory is active for this turn (provider wired + the
// agent's binding enabled). Drives recall-inject, the `recall_memory` tool,
// and background ingest below.
let lt_active = crate::long_term::long_term_active(runtime.long_term_memory.is_some(), &config);
// Whether short-term ("working") memory is active for this turn (provider
// wired + the agent's binding enabled). Drives `remember`/`recall` tools.
let st_active =
crate::short_term::short_term_active(runtime.short_term_memory.is_some(), &config);
// Whether the `end_conversation` tool + system-prompt note are offered
// this turn. Enabled when EITHER the agent's own config opts in OR this
// invocation does (the flow node marked `conversational` — SP3). The node
// drives the engine park-loop, so it must also let the agent end it.
let conv_active =
message.conversational || crate::end_conversation::conversational_active(&config);
// --- Long-term recall: inject relevant facts into this turn's prompt ---
let system_prompt = if lt_active {
let facts = runtime
.recall_long_term(
&tenant,
crate::long_term::RecallQuery {
query: user_message.clone(),
limit: Some(crate::long_term::AUTO_INJECT_K),
},
)
.await
.unwrap_or_else(|e| {
warn!(
agent_id = %config.agent_id,
error = %e,
"long-term recall failed; the turn proceeds without recalled facts"
);
Default::default()
});
crate::long_term::augment_system_prompt(&config.system_prompt, &facts)
} else {
config.system_prompt.clone()
};
// --- Knowledge retrieval: inject relevant corpus chunks (RAG-as-context,
// D3). Distinct seam from long-term memory (`cap://dw.knowledge`); both may
// augment the same turn, the knowledge block appended after the LT facts.
// Retrieval failures degrade to no injection rather than failing the turn.
let kn_active = crate::knowledge::knowledge_active(runtime.knowledge.is_some(), &config);
// The chunks injected this step are kept alongside the prompt so they can be
// recorded in the trail (`AgentStep::KnowledgeRetrieval`) once it exists.
let (system_prompt, retrieved_chunks) = if kn_active {
// The agent's own knowledge binding, threaded through so a backend that
// delegates retrieval to a per-worker target can read its ids from the
// binding's `params` (see `Knowledge::search_bound`).
let binding = config.knowledge.as_ref().and_then(|k| k.knowledge.as_ref());
let outcome = runtime
.search_knowledge(
&tenant,
crate::knowledge::KnowledgeQuery {
query: user_message.clone(),
limit: Some(crate::knowledge::auto_top_k(&config)),
},
binding,
)
.await;
// A retrieval failure still degrades to no injection — a dead backend
// must not fail the turn — but it is no longer SILENT. This used to end
// `.unwrap_or_default()`, which turned every `Err` into an empty vector
// with no log, no trace, and nothing to tell "the corpus held nothing
// relevant" apart from "the backend did not answer". The worker then
// answered confidently from nothing, and with a third-party retrieval
// service — which can be down, rate-limited, or holding a rotated
// credential — that case stops being rare.
let chunks = match outcome {
Ok(chunks) => {
// Surface the retrieval in the live trace (test-chat "Tools used")
// so the operator sees which chunks were pulled in. Observer-only
// — not the trail.
crate::knowledge::emit_retrieval_trace(observer.as_ref(), &user_message, &chunks);
chunks
}
// The normal state of every worker without a knowledge backend
// wired, so it must not warn — `knowledge_active` can be true from
// config alone while the host mounted nothing.
Err(e @ crate::knowledge::KnowledgeError::NotConfigured) => {
tracing::debug!(agent_id = %config.agent_id, error = %e, "knowledge retrieval skipped");
Vec::new()
}
Err(e) => {
tracing::warn!(
agent_id = %config.agent_id,
error = %e,
"knowledge retrieval failed; the turn proceeds with no retrieved context"
);
crate::knowledge::emit_retrieval_failure_trace(
observer.as_ref(),
&user_message,
&e,
);
Vec::new()
}
};
let augmented = crate::knowledge::augment_system_prompt(&system_prompt, &chunks);
(augmented, chunks)
} else {
(system_prompt, Vec::new())
};
// --- Conversational note: tell the model the `end_conversation` tool
// exists and when to call it. Applied only for conversational agents. ---
let system_prompt = if conv_active {
crate::end_conversation::augment_system_prompt(&system_prompt)
} else {
system_prompt
};
// The turn that resumes a flow after side turns tells the model the step
// just finished (its history ends in the last side answer otherwise).
let system_prompt = if resumed_after_side_turns {
format!(
"{system_prompt}\n\n{}",
crate::flow_suspend::RESUME_AFTER_SIDE_TURNS_NOTE
)
} else {
system_prompt
};
// A side turn tells the model a form step is pending.
let system_prompt = if side_pending {
format!("{system_prompt}\n\n{}", crate::flow_suspend::SIDE_TURN_NOTE)
} else {
system_prompt
};
// Resolve the per-tenant tool catalogs (MCP, component, flow, playbook,
// SoRLa, A2A)
// once per step. Every source is infallible (degrades to an empty catalog
// on any admin/server failure) and TTL-cached, so a stable config does not
// re-hit the network across iterations. `None` source → no tools of that
// prefix. `ToolCatalogs` is shared with `AgentRuntime::tool_session`, so
// an external loop resolves exactly what this one does. The user ledger
// read (above) runs alongside it.
let ledger_read = async {
match &ledger_turn {
Some(turn) => turn.read_view().await,
None => None,
}
};
let (ledger_view, catalogs) = resolve_under_lock(
&lock,
crate::lock_keepalive::LOCK_KEEPALIVE_INTERVAL,
ledger_read,
crate::tool_session::ToolCatalogs::resolve(runtime, &tenant, &config.tools, &config.llm),
)
.await;
// Prompt block order: the agent's prompt, long-term facts, knowledge
// chunks, the conversational note, then `<user_history>` (bounded by
// `user_ledger::MAX_VIEW_CHARS`), and last, per iteration, the run
// context `<run_context>` (bounded by `run_trace::MAX_VIEW_CHARS`).
let system_prompt =
crate::run_trace::augment_system_prompt(&system_prompt, ledger_view.as_deref());
// Preflight: surface declared tools that won't reach the LLM. Without this
// the runtime drops unresolved tools silently (per-tool debug warns) and the
// agent runs with a smaller — or empty — tool set, then hallucinates tool
// results. Warn loudly, once per agent per process, with the reason + fix.
preflight_warn_tools(
&config.agent_id,
&catalogs.missing(&runtime.ext_runtime, &config.tools),
config.tools.len(),
);
let mut total_tokens: u64 = 0;
// Separate in/out accumulators surfaced on `AgentOutput.usage` (total is
// still tracked for telemetry/metering below).
let mut tokens_in_total: u64 = 0;
let mut tokens_out_total: u64 = 0;
let mut trail: Vec<AgentStep> = Vec::new();
// Record the built-in knowledge retrieval FIRST: it happened before any LLM
// call, and it is the only place a knowledge-grounded answer's sources are
// written down (the observer trace is live-only and never persisted).
if !retrieved_chunks.is_empty() {
trail.push(AgentStep::KnowledgeRetrieval {
chunks: retrieved_chunks,
});
}
let mut terminated_by = TerminationReason::MaxIterations;
let mut iterations: u32 = 0;
let mut reply = String::new();
// Turn-scoped: set once any tool the agent tried failed (dispatch error or
// allow-list block). A tool failure often lands one iteration BEFORE the
// model decides to give up and call `end_conversation`, so this flag must
// survive across iterations of the Plan-Act-Observe loop. Consumed by the
// `end_conversation` short-circuit below to keep a conversational agent
// PARKED (surface the blocker) instead of silently ending the conversation.
let mut turn_had_tool_error = false;
if let Some(step) = cancelled_step {
trail.push(step);
}
// Set when a `flow:` tool parks on the user: the presentation to show.
// Ends the turn with `AwaitingToolInput`.
let mut suspension: Option<serde_json::Value> = None;
let mut first_iter: u32 = 0;
if let Some(resume) = resuming {
first_iter = resume.pending.iterations_used;
iterations = first_iter;
let resumed_call_id = resume.pending.call_id.clone();
let carried_attachments = resume.pending.unannounced_attachments as usize;
suspension = crate::flow_suspend::resume_pending(
runtime,
&lock,
&tenant,
session_id,
&catalogs,
&mut state,
&mut trail,
observer.as_ref(),
resume,
)
.await;
if suspension.is_some() {
terminated_by = TerminationReason::AwaitingToolInput;
}
// Files sent with the answer go nowhere (the flow takes none): the
// agent is told IN the resumed call's result (fixed text, a count
// only), so truncation removes the note with its group. On a re-park
// the model is not called: the count waits on the pending call.
match state.pending_tool.as_mut() {
Some(pending) if suspension.is_some() => {
pending.unannounced_attachments = pending
.unannounced_attachments
.saturating_add(u32::try_from(resume_attachment_count).unwrap_or(u32::MAX));
}
_ => crate::flow_suspend::announce_unread_attachments(
&mut state,
&resumed_call_id,
carried_attachments.saturating_add(resume_attachment_count),
),
}
}
// One memo per TURN, shared by every iteration's request (and by a
// retrying backend's re-sends): the current message's attachments are
// fetched once, and the memo is dropped when the turn ends. Never shared
// across turns or conversations (it holds bytes fetched under this turn's
// authorisation).
let turn_attachments = crate::attachments_materialize::TurnAttachments::for_turn();
// A turn resumed from a park continues the parked turn's budget, but gets
// at least one iteration: a flow that parked on the LAST iteration
// (`first_iter == max_iter`) would otherwise leave an empty range and the
// user's answer would never get a reply.
let iter_end = if first_iter > 0 {
config.limits.max_iter.max(first_iter.saturating_add(1))
} else {
config.limits.max_iter
};
let iter_range = if suspension.is_some() {
0..0
} else {
first_iter..iter_end
};
for iter in iter_range {
iterations = iter + 1;
// Extend the lock TTL each iteration. A transient refresh failure only
// logs; a lock that is no longer ours aborts the step (see
// `ensure_lock_held`).
if let Err(e) = ensure_lock_held(&lock).await {
record_error_exit(
runtime,
&tenant,
session_id,
agent_id,
iterations,
total_tokens,
started,
);
return Err(e);
}
if started.elapsed() >= config.limits.timeout {
terminated_by = TerminationReason::Timeout;
break;
}
// Bound the history BEFORE every LLM call, not only on the success
// path: a session whose history had outgrown the model's context used
// to fail every later call and, since truncation never ran on the
// error paths, could never recover.
state.truncate_history(config.limits.max_history_turns);
let mut tools_schema = catalogs.list_for_llm(&runtime.ext_runtime, &config.tools);
if lt_active {
tools_schema.push(crate::long_term::recall_memory_tool_schema());
}
if st_active {
tools_schema.push(crate::short_term::remember_tool_schema());
tools_schema.push(crate::short_term::recall_tool_schema());
}
if conv_active {
tools_schema.push(crate::end_conversation::end_conversation_tool_schema());
}
let request = LlmRequest {
system_prompt: crate::run_trace::augment_system_prompt(
&system_prompt,
run_trace
.as_ref()
.and_then(|t| t.render_view_for(Some(step_id)))
.as_deref(),
),
history: state.messages.clone(),
tools: tools_schema,
provider: config.llm.clone(),
turn_attachments: turn_attachments.clone(),
attachment_text_guard: attachment_text_guard.clone(),
};
// Stream only when the observer actually consumes deltas. A
// non-streaming caller (the default `step` path, `NoopStepObserver`)
// stays on `complete`, preserving the exact request wire shape — no
// `stream: true` — that every pre-streaming caller relied on.
// On a mid-stream error the provider may have billed for partial
// tokens, but usage only arrives in the stream's final chunk; those
// partial tokens are NOT metered here. This matches the blocking
// path, which likewise meters nothing when complete() errors.
//
// The call goes through the retry decorator configured by the agent's
// `llm_retry_*` limits and is bounded by what is left of the step's
// wall-clock budget.
let retrying = crate::llm::retrying_for(&runtime.llm, &config.limits);
let remaining = config.limits.timeout.saturating_sub(started.elapsed());
let llm_call = async {
if observer.wants_streaming() {
let obs = observer.clone();
let on_delta: crate::llm::OnDelta =
Box::new(move |chunk: &str| obs.on_token_delta(chunk));
retrying.complete_streaming(request, on_delta).await
} else {
retrying.complete(request).await
}
};
// The call can outlast the 90 s lock TTL (retries, long streams), so
// the lock is kept alive while it is pending.
let llm_result = match tokio::time::timeout(
remaining,
crate::lock_keepalive::keep_alive(
&lock,
crate::lock_keepalive::LOCK_KEEPALIVE_INTERVAL,
llm_call,
),
)
.await
{
Ok(result) => result,
Err(_) => {
warn!(agent_id = %agent_id, "llm call exceeded the step timeout");
terminated_by = TerminationReason::Timeout;
break;
}
};
let mut response = match llm_result {
Ok(r) => r,
Err(e) => {
// Persist the (bounded) history so far; a failed save is
// logged, not swallowed.
state.truncate_history(config.limits.max_history_turns);
// A lapsed lock means a newer turn may own the session: do
// not save over it.
if ensure_lock_held(&lock).await.is_ok()
&& let Err(save_err) =
runtime.state_store.save(&tenant, session_id, &state).await
{
warn!(error = %save_err, "state save failed after llm error");
}
record_error_exit(
runtime,
&tenant,
session_id,
agent_id,
iterations,
total_tokens,
started,
);
return Err(match e {
LlmError::ServiceUnavailable => AgentError::LlmProviderUnavailable,
other => AgentError::Llm(other),
});
}
};
let step_tokens = u64::from(response.tokens_in) + u64::from(response.tokens_out);
total_tokens += step_tokens;
tokens_in_total += u64::from(response.tokens_in);
tokens_out_total += u64::from(response.tokens_out);
// Per-call trace: record this LLM iteration's assistant content + token
// cost (before its tool calls) so a caller can show a per-message
// breakdown, not just the aggregate `AgentOutput.usage`.
trail.push(AgentStep::LlmCall {
content: response.content.clone().unwrap_or_default(),
tokens_in: u64::from(response.tokens_in),
tokens_out: u64::from(response.tokens_out),
});
// Stream the per-iteration token trace (a streaming consumer renders a
// per-message LLM/token line even when the turn calls no tools).
observer.on_llm_call(
u64::from(response.tokens_in),
u64::from(response.tokens_out),
);
if let Err(e) = runtime.token_meter.add(&tenant, step_tokens).await {
warn!(error = %e, "token meter add failed; continuing");
}
// Fire-and-forget billing emit: never blocks the agent step.
if let Err(e) = runtime
.billing_meter
.emit(
&tenant,
u64::from(response.tokens_in),
u64::from(response.tokens_out),
agent_id,
&config.llm.model,
)
.await
{
warn!(error = %e, "billing meter emit failed; continuing");
}
// --- Mixed text + tool_calls: tool_calls win (spec Decision 12) ---
if !response.tool_calls.is_empty() {
// Empty / repeated provider call ids would alias ledger entries and
// break the call <-> result pairing in history.
crate::tools::ensure_unique_call_ids(&mut response.tool_calls);
// --- Host built-in: `end_conversation` (conversational agents) ---
// Agent-driven exit signal (SP1). Short-circuit BEFORE recording the
// multi-tool assistant message so saved history carries no dangling
// tool_call. Any co-occurring tool calls are ignored — the agent
// chose to end the conversation.
if conv_active
&& let Some(end_call) = response
.tool_calls
.iter()
.find(|c| is_host_tool(c, crate::end_conversation::END_CONVERSATION_TOOL))
{
observer.on_tool_call(&end_call.tool_name, &end_call.call_id, &end_call.args);
let closing = end_call
.args
.get("final_message")
.and_then(|v| v.as_str())
.map(str::to_string)
.filter(|s| !s.is_empty())
.or_else(|| response.content.clone())
.unwrap_or_default();
let ok = serde_json::json!({ "ok": true });
observer.on_tool_result(&end_call.tool_name, &end_call.call_id, &ok);
trail.push(AgentStep::ToolCall {
name: end_call.tool_name.clone(),
call_id: end_call.call_id.clone(),
args: end_call.args.clone(),
result: ok,
duration_ms: 0,
});
reply = closing;
// Blocker guard: if a tool/backend failed earlier this turn, the
// model often gives up and asks to end. Honouring that would
// silently advance the flow past the failure with the user none
// the wiser. Instead keep the conversation PARKED (FinalReply,
// not ConversationEnded) so the closing message — which explains
// the failure — is shown and the user can respond or retry.
terminated_by = if turn_had_tool_error {
TerminationReason::FinalReply
} else {
TerminationReason::ConversationEnded
};
break;
}
// Record the assistant's tool-call turn BEFORE the tool results.
// OpenAI requires every `tool` message to follow an assistant
// message carrying the matching `tool_calls`; without this the next
// turn 400s ("messages with role 'tool' must be a response to a
// preceeding message with 'tool_calls'").
state.messages.push(ChatMessage::Assistant {
content: response.content.clone().unwrap_or_default(),
tool_calls: response.tool_calls.clone(),
});
// Set once a tool call exhausted the step's time budget: later calls
// in the batch are answered with an error instead of run.
let mut step_timed_out = false;
for call in response.tool_calls {
if step_timed_out {
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: serde_json::json!({
"error": "step timed out before this tool ran"
}),
});
continue;
}
// --- The model's arguments were not valid JSON ---
// Never run the tool on made-up (empty) arguments: tell the
// model so it can re-issue the call correctly.
if let Some(raw) = call.args.get(crate::llm::MALFORMED_ARGS_KEY) {
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let err_obs = serde_json::json!({
"error": "tool arguments were not valid JSON; re-issue the call with a valid JSON object",
"received": raw,
});
observer.on_tool_failed(&call.tool_name, &call.call_id, &err_obs);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: err_obs.clone(),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id.clone(),
args: call.args.clone(),
result: err_obs,
duration_ms: 0,
});
turn_had_tool_error = true;
continue;
}
// --- A flow tool earlier in this batch parked on the user ---
// Every later call still gets a result so no tool_call dangles
// in history, but none of them runs: the user must answer first.
// A side turn must not start a second flow while one is parked.
if suspension.is_some() || (side_pending && call.extension_id.starts_with("flow:"))
{
crate::flow_suspend::refuse_behind_suspension(
&mut state,
&mut trail,
observer.as_ref(),
&call,
);
continue;
}
// --- Host built-in: `recall_memory` (long-term lookup) ---
// Intercepted before the allow-list + WASM dispatch; routed to
// the runtime's long-term backend instead of an extension.
if lt_active && is_host_tool(&call, crate::long_term::RECALL_MEMORY_TOOL) {
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let t0 = Instant::now();
let result = host_recall_memory(runtime, &tenant, &call).await;
let duration_ms = t0.elapsed().as_millis() as u64;
observer.on_tool_result(&call.tool_name, &call.call_id, &result);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: result.clone(),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id,
args: call.args.clone(),
result,
duration_ms,
});
continue;
}
// --- Host built-in: short-term `remember` / `recall` ---
// Intercepted before the allow-list + WASM dispatch; routed to
// the runtime's short-term backend instead of an extension.
if st_active && is_host_tool(&call, crate::short_term::REMEMBER_TOOL) {
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let t0 = Instant::now();
let result = host_remember(runtime, &tenant, session_id, &call).await;
let duration_ms = t0.elapsed().as_millis() as u64;
observer.on_tool_result(&call.tool_name, &call.call_id, &result);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: result.clone(),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id,
args: call.args.clone(),
result,
duration_ms,
});
continue;
}
if st_active && is_host_tool(&call, crate::short_term::RECALL_TOOL) {
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let t0 = Instant::now();
let result = host_recall(runtime, &tenant, session_id, &call).await;
let duration_ms = t0.elapsed().as_millis() as u64;
observer.on_tool_result(&call.tool_name, &call.call_id, &result);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: result.clone(),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id,
args: call.args.clone(),
result,
duration_ms,
});
continue;
}
if !is_tool_allowed(&call, &config.tools) {
let reason = "not in allow-list";
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let err_obs = serde_json::json!({ "error": reason });
observer.on_tool_failed(&call.tool_name, &call.call_id, &err_obs);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: serde_json::json!({ "error": "tool not allowed for this agent" }),
});
trail.push(AgentStep::ToolCallBlocked {
name: call.tool_name.clone(),
reason: reason.into(),
});
turn_had_tool_error = true;
continue;
}
// --- Idempotency: reuse a previously-recorded result ---
let ledger_id = crate::tools::ledger_call_id(&call);
match runtime.ledger.get(&tenant, session_id, &ledger_id).await {
// A cached failure report is not a result worth replaying.
Ok(Some(cached)) if !crate::tools::is_error_result(&cached) => {
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
observer.on_tool_result(&call.tool_name, &call.call_id, &cached);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: crate::state::cap_tool_result_for(cached, &call.tool_name),
});
trail.push(AgentStep::ToolCallReused {
name: call.tool_name.clone(),
call_id: call.call_id.clone(),
});
continue;
}
Ok(_) => {} // fall through to dispatch
Err(e) => {
warn!(error = %e, "ledger get failed; dispatching without idempotency");
}
}
// --- Dispatch (blocking WASM via spawn_blocking) ---
// Tool dispatch errors are NOT termination (spec §6): surface
// the error as a Tool observation so the LLM can react, then
// continue. Failed calls are NOT recorded in the ledger
// (they should remain retryable on the next turn).
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
let t0 = Instant::now();
// Bound to a `let` before the `match` on purpose: a `&mut`
// borrow of `state.a2a` inside a match scrutinee lives to the
// end of the match, and the error arm below pushes onto
// `state.messages`.
//
// A `flow:` tool may PARK on the user (a card). It is the one
// prefix dispatched interactively; the rest stay one-shot.
let dispatched = if let Some(flow_ref) = call.extension_id.strip_prefix("flow:") {
// The host running this flow derives a nested agent's
// session from the caller's session and this call id, and
// its caller from the host-stamped one (`tool_call_frame`).
//
// The call can run a whole nested agent turn, so the lock
// is kept alive while it is pending.
match crate::lock_keepalive::keep_alive(
&lock,
crate::lock_keepalive::LOCK_KEEPALIVE_INTERVAL,
crate::tool_call_frame::within(
crate::tool_call_frame::ToolCallFrame::new(
Some(session_id),
&call.call_id,
)
.with_caller(tenant.caller_or_anonymous()),
crate::tools::dispatch_flow_tool_interactive(
catalogs.flows.as_deref(),
flow_ref,
&call,
),
),
)
.await
{
crate::tools::FlowToolDispatch::Value(value) => Ok(value),
crate::tools::FlowToolDispatch::Suspend {
snapshot,
presentation,
} => {
state.pending_tool = Some(crate::state::PendingToolCall {
call_id: call.call_id.clone(),
tool_name: call.tool_name.clone(),
extension_id: call.extension_id.clone(),
args: call.args.clone(),
flow_ref: flow_ref.to_string(),
flow_snapshot: snapshot,
iterations_used: iterations,
expires_at: crate::state::PendingToolCall::expiry_from(
chrono::Utc::now(),
),
presentation: Some(presentation.clone()),
parked_at: Some(chrono::Utc::now()),
side_turns: 0,
unannounced_attachments: 0,
});
if config.on_text_while_parked
== crate::config::ParkedTextPolicy::SideTurn
{
// Answer the parked call now so side turns can
// be appended after it without breaking the
// provider's tool-call pairing; resume or
// cancel patches this result in place.
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: serde_json::json!({
"status": crate::flow_suspend::AWAITING_PLACEHOLDER
}),
});
}
suspension = Some(presentation);
continue;
}
}
} else {
let remaining = config.limits.timeout.saturating_sub(started.elapsed());
// At-least-once caveat: when the timeout fires, this future is
// dropped mid-flight. The tool may already have produced a
// remote side effect that is NOT recorded in any ledger, so
// a retried turn can perform it again. Tools with side
// effects must be idempotent.
// `limits.timeout` may exceed the 90 s lock TTL, so the
// lock is kept alive while the call is pending.
match tokio::time::timeout(
remaining,
crate::lock_keepalive::keep_alive(
&lock,
crate::lock_keepalive::LOCK_KEEPALIVE_INTERVAL,
catalogs.dispatch(
runtime.ext_runtime.clone(),
call.clone(),
&tenant,
Some(&mut state.a2a),
),
),
)
.await
{
Ok(result) => result,
Err(_) => {
step_timed_out = true;
Err(AgentError::ToolDispatch(
"tool call exceeded the step timeout".into(),
))
}
}
};
let result = match dispatched {
Ok(r) => r,
Err(e) => {
let duration_ms = t0.elapsed().as_millis() as u64;
warn!(
error = %e, tool = %call.tool_name,
"tool dispatch failed; recording as observation and continuing"
);
let err_obs = serde_json::json!({ "error": e.to_string() });
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: err_obs.clone(),
});
// Surface the failure so audit/stream observers see a matching
// outcome instead of a dangling call.
observer.on_tool_failed(&call.tool_name, &call.call_id, &err_obs);
if let Some(t) = &record_to {
t.append_tool_outcome(
step_id,
agent_id,
&call.tool_name,
crate::run_trace::ToolOutcome::Failed,
&crate::run_trace::summarise_result(&call.tool_name, &err_obs),
);
}
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id.clone(),
args: call.args.clone(),
result: err_obs,
duration_ms,
});
turn_had_tool_error = true;
continue;
}
};
let duration_ms = t0.elapsed().as_millis() as u64;
observer.on_tool_result(&call.tool_name, &call.call_id, &result);
if let Some(t) = &record_to {
t.append_tool_outcome(
step_id,
agent_id,
&call.tool_name,
crate::run_trace::ToolOutcome::of(&result),
&crate::run_trace::summarise_result(&call.tool_name, &result),
);
}
// Record successful result in ledger (best-effort). A tool that
// reports failure as `{"error": ...}` stays retryable.
if !crate::tools::is_error_result(&result)
&& let Err(e) = runtime
.ledger
.record(&tenant, session_id, &ledger_id, result.clone())
.await
{
warn!(error = %e, "ledger record failed; continuing");
}
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: crate::state::cap_tool_result_for(result.clone(), &call.tool_name),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id,
args: call.args.clone(),
result,
duration_ms,
});
}
if step_timed_out {
terminated_by = TerminationReason::Timeout;
break;
}
if suspension.is_some() {
// The turn ends here, waiting on the user. The assistant text
// that accompanied the tool call (if any) is the reply.
reply = response.content.unwrap_or_default();
terminated_by = TerminationReason::AwaitingToolInput;
break;
}
continue; // next LLM turn with tool observations
}
// --- No tool calls: final reply ---
reply = response.content.unwrap_or_default();
// NOTE: the assistant ChatMessage push and trail push are deferred
// until AFTER the outbound guardrail chain so history reflects the
// guarded reply, not the raw LLM output.
terminated_by = TerminationReason::FinalReply;
break;
}
// --- Outbound guardrail hook (FinalReply only) ---
// The outbound chain is intentionally skipped when the loop terminated via
// Timeout or MaxIterations: in those cases `reply` is an empty string, and
// running an outbound guardrail against an empty string could trigger a
// policy deny that masks the true termination reason from the caller.
// Only a real final reply (where the LLM produced content) is subject to
// outbound policy; the assistant message and audit trail are written only
// after this check passes, so saved state reflects the guarded reply.
if matches!(
terminated_by,
TerminationReason::FinalReply | TerminationReason::ConversationEnded
) {
let reply = match crate::guardrail::run_chain_blocking(
&guardrail_chain,
crate::guardrail::GuardrailDirection::Outbound,
reply,
&guardrail_ctx,
runtime.guardrail_evaluator.clone(),
)
.await
{
crate::guardrail::ChainOutcome::Pass {
content,
observations,
} => {
for obs in &observations {
observer.on_guardrail(obs);
}
content
}
crate::guardrail::ChainOutcome::Denied {
info,
direction,
observation,
} => {
observer.on_guardrail(&observation);
return Err(AgentError::GuardrailDenied {
direction,
code: info.code,
message: info.message,
details: info.details,
});
}
};
let side_turn = side_pending
&& crate::flow_suspend::finish_side_turn(
&mut state,
&mut terminated_by,
&mut suspension,
);
state.messages.push(ChatMessage::Assistant {
content: reply.clone(),
tool_calls: vec![],
});
trail.push(AgentStep::Reply {
text: reply.clone(),
});
state.truncate_history(config.limits.max_history_turns);
ensure_lock_held(&lock).await?;
if let Err(e) = runtime.state_store.save(&tenant, session_id, &state).await {
warn!(error = %e, "state save failed at end of step");
}
// --- Long-term ingest (fire-and-forget): persist this turn as an episode.
// Runs on the FinalReply path — the only path with a non-empty reply. It
// previously sat after this branch's early return and so never executed. ---
if !reply.is_empty()
&& lt_active
&& let Some(memory) = runtime.long_term_memory.clone()
{
match crate::long_term::to_types_tenant(&tenant) {
Ok(ctx) => {
let episode = crate::long_term::EpisodeIngest {
name: format!("{session_id}:turn"),
body: format!("{user_message}\n\n{reply}"),
source: crate::long_term::EpisodeSource::Message,
source_description: Some("agentic-worker turn".into()),
reference_time: chrono::Utc::now(),
};
// Bounded: a slow memory backend must not pile up one task
// (holding the whole episode) per turn.
crate::background::long_term_gate().try_spawn("long-term ingest", async move {
if let Err(e) = memory.ingest_episode(&ctx, episode).await {
warn!(error = %e, "background long-term ingest failed");
}
});
}
Err(e) => {
warn!(error = %e, "long-term ingest skipped: tenant conversion failed");
}
}
}
if !reply.is_empty()
&& let Some(t) = &record_to
{
t.append(agent_id, "reply", &reply);
}
// The GUARDED reply only (spec 4.1): never tool results, arguments or
// the user's message. Background, bounded, never fails the turn.
// `ledger_turn` was decided on this task before anything spawned; the
// append itself may spawn. Only a read-write binding appends.
if !reply.is_empty()
&& let Some(turn) = &ledger_turn
{
turn.record_reply(&reply);
}
runtime.telemetry.record_step(&StepTelemetryCtx {
tenant_id: tenant.tenant_id.clone(),
env_id: tenant.env_id.clone(),
session_id: session_id.to_string(),
agent_id: agent_id.to_string(),
terminated_by: terminated_by.clone(),
iterations,
total_tokens,
duration: started.elapsed(),
});
return Ok(AgentOutput {
reply,
trail,
terminated_by,
usage: StepUsage {
tokens_in: tokens_in_total,
tokens_out: tokens_out_total,
iterations,
},
pending_presentation: suspension,
side_turn,
});
}
let side_turn = side_pending
&& crate::flow_suspend::finish_side_turn(&mut state, &mut terminated_by, &mut suspension);
state.truncate_history(config.limits.max_history_turns);
ensure_lock_held(&lock).await?;
if let Err(e) = runtime.state_store.save(&tenant, session_id, &state).await {
warn!(error = %e, "state save failed at end of step");
}
runtime.telemetry.record_step(&StepTelemetryCtx {
tenant_id: tenant.tenant_id.clone(),
env_id: tenant.env_id.clone(),
session_id: session_id.to_string(),
agent_id: agent_id.to_string(),
terminated_by: terminated_by.clone(),
iterations,
total_tokens,
duration: started.elapsed(),
});
Ok(AgentOutput {
reply,
trail,
terminated_by,
usage: StepUsage {
tokens_in: tokens_in_total,
tokens_out: tokens_out_total,
iterations,
},
pending_presentation: suspension,
side_turn,
})
}
/// Handle a host built-in `recall_memory` tool call: parse `query`/`limit` from
/// the call args, query long-term memory, and return the facts as JSON (or an
/// error object the LLM can observe and react to).
async fn host_recall_memory(
runtime: &AgentRuntime,
tenant: &TenantContext,
call: &crate::state::ToolCallRecord,
) -> serde_json::Value {
let query = call
.args
.get("query")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let limit = call
.args
.get("limit")
.and_then(serde_json::Value::as_u64)
.map(|n| n as usize)
.unwrap_or(crate::long_term::TOOL_LIMIT);
match runtime
.recall_long_term(
tenant,
crate::long_term::RecallQuery {
query,
limit: Some(limit),
},
)
.await
{
Ok(facts) => serde_json::json!({ "facts": facts }),
Err(e) => serde_json::json!({ "error": e.to_string() }),
}
}
/// Handle a host built-in `remember` call: store `{key, value}` into short-term
/// memory for this `(tenant, session)`. Returns `{"ok": true}` or `{"error": ...}`.
async fn host_remember(
runtime: &AgentRuntime,
tenant: &TenantContext,
session_id: &str,
call: &crate::state::ToolCallRecord,
) -> serde_json::Value {
let Some(provider) = runtime.short_term_memory.as_ref() else {
return serde_json::json!({ "error": "short-term memory not configured" });
};
let key = call
.args
.get("key")
.and_then(|v| v.as_str())
.unwrap_or_default();
let value = call
.args
.get("value")
.and_then(|v| v.as_str())
.unwrap_or_default();
if key.is_empty() {
return serde_json::json!({ "error": "missing 'key'" });
}
if value.is_empty() {
return serde_json::json!({ "error": "missing 'value'" });
}
let record = crate::memory::MemoryRecord {
key: key.to_string(),
value: value.to_string(),
};
match provider.remember(tenant, session_id, record).await {
Ok(()) => serde_json::json!({ "ok": true }),
Err(e) => serde_json::json!({ "error": e.to_string() }),
}
}
/// Handle a host built-in `recall` call: read a value back by `key`. Returns
/// `{"value": <string|null>}` or `{"error": ...}`.
async fn host_recall(
runtime: &AgentRuntime,
tenant: &TenantContext,
session_id: &str,
call: &crate::state::ToolCallRecord,
) -> serde_json::Value {
let Some(provider) = runtime.short_term_memory.as_ref() else {
return serde_json::json!({ "error": "short-term memory not configured" });
};
let key = call
.args
.get("key")
.and_then(|v| v.as_str())
.unwrap_or_default();
if key.is_empty() {
return serde_json::json!({ "error": "missing 'key'" });
}
let query = crate::memory::MemoryQuery {
key: key.to_string(),
};
match provider.recall(tenant, session_id, &query).await {
Ok(Some(record)) => serde_json::json!({ "value": record.value }),
Ok(None) => serde_json::json!({ "value": serde_json::Value::Null }),
Err(e) => serde_json::json!({ "error": e.to_string() }),
}
}
#[cfg(all(test, feature = "test-mock"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use std::sync::Arc;
use crate::config::{AgentConfig, AgentLimits, LlmProviderRef};
use crate::error::{AgentError, LlmError, TerminationReason};
use crate::llm::LlmResponse;
use crate::mock::{MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockTelemetry};
use crate::tenant::TenantContext;
use crate::{AgentInput, AgentRuntime, AgentStep};
fn cfg() -> AgentConfig {
AgentConfig {
agent_id: "a".into(),
system_prompt: "sys".into(),
tools: vec![],
guardrails: vec![],
llm: LlmProviderRef {
provider: "openai".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(),
}
}
/// Happy-path loop test: one LLM call → reply, telemetry recorded.
#[tokio::test]
async fn happy_path_returns_llm_reply() {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("hi from llm".into()),
tool_calls: vec![],
tokens_in: 10,
tokens_out: 20,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
cp.insert(&tc, "a", cfg());
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(
cp,
store,
ext,
llm,
telemetry.clone(),
token_meter,
ledger,
None,
);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hello".into(),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(out.reply, "hi from llm");
assert_eq!(telemetry.recorded.lock().unwrap().len(), 1);
// Per-turn usage is surfaced on the output (one LLM call: 10 in / 20 out).
assert_eq!(out.usage.tokens_in, 10);
assert_eq!(out.usage.tokens_out, 20);
assert_eq!(out.usage.iterations, 1);
// The trail records the LLM call (per-message breakdown) before the reply.
assert!(matches!(
out.trail.first(),
Some(crate::AgentStep::LlmCall {
tokens_in: 10,
tokens_out: 20,
..
})
));
}
/// An empty wallet must stop the run BEFORE any LLM spend. The mock backend is
/// primed with zero responses: if the gate were removed, the loop would reach
/// the LLM and fail with an LLM error instead of `CreditBudgetExceeded`.
#[tokio::test]
async fn empty_wallet_refuses_the_run_before_any_llm_call() {
let llm = Arc::new(MockLlmBackend::new(vec![]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
cp.insert(&tc, "a", cfg());
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(
cp,
store,
ext,
llm,
telemetry.clone(),
token_meter,
ledger,
None,
)
.with_billing_meter(Arc::new(crate::mock::MockBillingMeter::new(true)));
let err = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hello".into(),
..Default::default()
},
)
.await
.expect_err("an empty wallet must refuse the run");
assert!(
matches!(err, AgentError::CreditBudgetExceeded),
"expected CreditBudgetExceeded, got {err:?}"
);
assert!(
telemetry.recorded.lock().unwrap().is_empty(),
"nothing should have been executed"
);
}
#[tokio::test]
async fn opening_message_short_circuits_first_empty_turn() {
// The mock LLM would reply "from llm" if called — but an opening message
// on an empty FIRST turn must be returned verbatim WITHOUT an LLM call.
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("from llm".into()),
tool_calls: vec![],
tokens_in: 5,
tokens_out: 5,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
let mut c = cfg();
c.opening_message = Some("Welcome to support!".into());
cp.insert(&tc, "a", c);
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(cp, store, ext, llm, telemetry, token_meter, ledger, None);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
// Blank input (whitespace only) — e.g. a button click, no message.
AgentInput {
text: " ".into(),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(out.reply, "Welcome to support!");
// No LLM call → zero usage, empty trail.
assert_eq!(out.usage.tokens_in, 0);
assert_eq!(out.usage.tokens_out, 0);
assert!(out.trail.is_empty());
}
#[tokio::test]
async fn opening_message_ignored_when_user_typed() {
// With actual user text, the opening message is NOT used — the LLM runs.
let (runtime, tc) = {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("real answer".into()),
tool_calls: vec![],
tokens_in: 3,
tokens_out: 4,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
let mut c = cfg();
c.opening_message = Some("Welcome!".into());
cp.insert(&tc, "a", c);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let runtime = AgentRuntime::new(
Arc::new(cp),
store,
ext,
llm,
telemetry,
Arc::new(crate::cost::MockTokenMeter::new(0)),
Arc::new(crate::mock::NoopToolLedger),
None,
);
(runtime, tc)
};
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "track my order".into(),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(out.reply, "real answer");
}
/// Build a runtime whose mock LLM replays `responses` in order, for a
/// conversational agent with the given allow-listed `tools`.
fn conversational_runtime(
responses: Vec<Result<LlmResponse, LlmError>>,
tools: Vec<crate::config::ToolRef>,
) -> (AgentRuntime, TenantContext) {
runtime_with_config_conversational(responses, tools, true)
}
/// Like [`conversational_runtime`] but the agent CONFIG's `conversational`
/// is caller-controlled, so tests can exercise the node/invocation flag
/// (`AgentInput.conversational`) independently of the config default.
fn runtime_with_config_conversational(
responses: Vec<Result<LlmResponse, LlmError>>,
tools: Vec<crate::config::ToolRef>,
config_conversational: bool,
) -> (AgentRuntime, TenantContext) {
let llm = Arc::new(MockLlmBackend::new(responses));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
let mut c = cfg();
c.conversational = config_conversational;
c.tools = tools;
cp.insert(&tc, "a", c);
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(cp, store, ext, llm, telemetry, token_meter, ledger, None);
(runtime, tc)
}
fn end_conversation_call(final_message: &str) -> crate::state::ToolCallRecord {
crate::state::ToolCallRecord {
call_id: "end-call".into(),
extension_id: "host".into(),
tool_name: crate::end_conversation::END_CONVERSATION_TOOL.into(),
args: serde_json::json!({ "final_message": final_message }),
}
}
/// Blocker guard: when a tool fails during the turn, the model's subsequent
/// `end_conversation` request must NOT end the conversation — it parks
/// (`FinalReply`) so the closing message (which explains the failure) is
/// shown and the flow does not silently advance past the blocker.
#[tokio::test]
async fn conversational_tool_error_then_end_conversation_stays_parked() {
// Iteration 1: the model calls a tool that is not in the allow-list →
// recorded as a tool failure. Iteration 2: it gives up and asks to end.
let responses = vec![
Ok(LlmResponse {
content: Some("let me look that up".into()),
tool_calls: vec![crate::state::ToolCallRecord {
call_id: "c1".into(),
extension_id: "greentic.test".into(),
tool_name: "lookup".into(),
args: serde_json::json!({}),
}],
tokens_in: 1,
tokens_out: 1,
}),
Ok(LlmResponse {
content: Some("reasoning".into()),
tool_calls: vec![end_conversation_call("Sorry, my systems are unavailable.")],
tokens_in: 1,
tokens_out: 1,
}),
];
// Empty allow-list → the `lookup` call is blocked (a tool failure).
let (runtime, tc) = conversational_runtime(responses, vec![]);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(out.terminated_by, TerminationReason::FinalReply);
assert_eq!(out.reply, "Sorry, my systems are unavailable.");
}
/// Control: with no tool failure in the turn, `end_conversation` ends the
/// conversation normally (`ConversationEnded`) so the flow routes onward.
#[tokio::test]
async fn conversational_clean_end_conversation_ends() {
let responses = vec![Ok(LlmResponse {
content: Some("reasoning".into()),
tool_calls: vec![end_conversation_call("All set — goodbye!")],
tokens_in: 1,
tokens_out: 1,
})];
let (runtime, tc) = conversational_runtime(responses, vec![]);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(out.terminated_by, TerminationReason::ConversationEnded);
assert_eq!(out.reply, "All set — goodbye!");
}
/// SP3: the flow node's `conversational` flag (carried on `AgentInput`) must
/// enable the host `end_conversation` tool EVEN WHEN the agent's own config
/// default is non-conversational — so a node-marked-conversational segment
/// can be ended by the agent (and the engine advances past the park-loop).
#[tokio::test]
async fn node_conversational_input_enables_end_conversation_over_config() {
let responses = vec![Ok(LlmResponse {
content: Some("bye".into()),
tool_calls: vec![end_conversation_call("Take care!")],
tokens_in: 1,
tokens_out: 1,
})];
// Agent CONFIG is NON-conversational; only the invocation opts in.
let (runtime, tc) = runtime_with_config_conversational(responses, vec![], false);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hi".into(),
conversational: true,
resume_payload: None,
attachments: Vec::new(),
},
)
.await
.unwrap();
// end_conversation was honoured because the invocation flag turned
// conv_active on despite the config default.
assert_eq!(out.terminated_by, TerminationReason::ConversationEnded);
assert_eq!(out.reply, "Take care!");
}
/// Control: a non-conversational config AND a non-conversational invocation
/// means `end_conversation` is NOT offered, so the model's call is treated as
/// an ordinary (disallowed) tool and the turn ends as a normal FinalReply.
#[tokio::test]
async fn non_conversational_ignores_end_conversation() {
let responses = vec![
Ok(LlmResponse {
content: Some("trying to end".into()),
tool_calls: vec![end_conversation_call("bye")],
tokens_in: 1,
tokens_out: 1,
}),
Ok(LlmResponse {
content: Some("final answer".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
}),
];
let (runtime, tc) = runtime_with_config_conversational(responses, vec![], false);
let out = runtime
.step(
tc.clone(),
"sess-1",
"a",
AgentInput {
text: "hi".into(),
conversational: false,
resume_payload: None,
attachments: Vec::new(),
},
)
.await
.unwrap();
assert_eq!(out.terminated_by, TerminationReason::FinalReply);
}
/// 4b: when a knowledge backend is wired and the agent's binding is enabled,
/// retrieved chunks are injected into the system prompt the LLM sees.
#[tokio::test]
async fn knowledge_chunks_inject_into_system_prompt() {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("ok".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
// Config with an enabled knowledge binding (top_k = 3).
let mut c = cfg();
c.knowledge = Some(crate::config::KnowledgeSettings {
knowledge: Some(crate::config::MemoryProviderRef {
provider: "provider.knowledge.chronicle".into(),
capability: "cap://dw.knowledge".into(),
params: serde_json::Map::new(),
credential_ref: None,
}),
embedding: None,
top_k: 3,
});
cp.insert(&tc, "a", c);
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let kb = Arc::new(crate::mock::MockKnowledge::new(vec![
crate::knowledge::RetrievedChunk {
text: "Refunds are processed within 5 business days.".into(),
score: 0.9,
doc_id: None,
chunk_index: None,
metadata: serde_json::Map::new(),
},
]));
let runtime = AgentRuntime::new(
cp,
store,
ext,
llm.clone(),
telemetry,
token_meter,
ledger,
None,
)
.with_knowledge(kb);
let out = runtime
.step(
tc,
"sess-k",
"a",
AgentInput {
text: "do I get refunds?".into(),
..Default::default()
},
)
.await
.unwrap();
// #770: the retrieval is recorded in the trail, ahead of the LLM call,
// with the chunk exactly as retrieved — this is what lets a consumer
// cite a knowledge-grounded answer.
assert!(
matches!(
out.trail.first(),
Some(AgentStep::KnowledgeRetrieval { .. })
),
"first trail step must be KnowledgeRetrieval: {:?}",
out.trail
);
let chunks = out
.trail
.iter()
.find_map(|s| match s {
AgentStep::KnowledgeRetrieval { chunks } => Some(chunks),
_ => None,
})
.expect("retrieval step");
assert_eq!(chunks.len(), 1);
assert_eq!(
chunks[0].text,
"Refunds are processed within 5 business days."
);
assert!((chunks[0].score - 0.9).abs() < f64::EPSILON);
assert_eq!(
out.trail
.iter()
.filter(|s| matches!(s, AgentStep::KnowledgeRetrieval { .. }))
.count(),
1,
"one retrieval per step: {:?}",
out.trail
);
let prompts = llm.seen_system_prompts.lock().unwrap();
assert_eq!(prompts.len(), 1);
assert!(
prompts[0].contains("<knowledge>"),
"knowledge block missing from system prompt: {}",
prompts[0]
);
assert!(
prompts[0].contains("Refunds are processed within 5 business days."),
"retrieved chunk missing from system prompt: {}",
prompts[0]
);
}
/// #770: a retrieval that returns nothing injected nothing, so it has
/// nothing to cite and must not add an (empty) `KnowledgeRetrieval` step.
#[tokio::test]
async fn empty_knowledge_retrieval_records_no_trail_step() {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("ok".into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]));
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
let mut c = cfg();
c.knowledge = Some(crate::config::KnowledgeSettings {
knowledge: Some(crate::config::MemoryProviderRef {
provider: "provider.knowledge.chronicle".into(),
capability: "cap://dw.knowledge".into(),
params: serde_json::Map::new(),
credential_ref: None,
}),
embedding: None,
top_k: 3,
});
cp.insert(&tc, "a", c);
let runtime = AgentRuntime::new(
Arc::new(cp),
Arc::new(MockAgentStateStore::new()),
Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap()),
llm,
Arc::new(MockTelemetry::new()),
Arc::new(crate::cost::MockTokenMeter::new(0)),
Arc::new(crate::mock::NoopToolLedger),
None,
)
.with_knowledge(Arc::new(crate::mock::MockKnowledge::new(Vec::new())));
let out = runtime
.step(
tc,
"sess-k0",
"a",
AgentInput {
text: "anything?".into(),
..Default::default()
},
)
.await
.unwrap();
assert!(
!out.trail
.iter()
.any(|s| matches!(s, AgentStep::KnowledgeRetrieval { .. })),
"empty retrieval must not be recorded: {:?}",
out.trail
);
}
#[derive(Default)]
struct Collecting {
deltas: std::sync::Mutex<Vec<String>>,
tool_calls: std::sync::Mutex<Vec<String>>,
}
impl crate::StepObserver for Collecting {
fn wants_streaming(&self) -> bool {
true
}
fn on_token_delta(&self, chunk: &str) {
self.deltas.lock().expect("lock").push(chunk.to_string());
}
fn on_tool_call(&self, name: &str, _call_id: &str, _args: &serde_json::Value) {
self.tool_calls.lock().expect("lock").push(name.to_string());
}
}
/// `step_with_observer` mirrors `happy_path_returns_llm_reply` but
/// drives a collecting observer; the default-impl single-delta path
/// (MockLlmBackend uses the trait default) must forward the full reply
/// to `on_token_delta`.
#[tokio::test]
async fn step_with_observer_streams_reply_deltas() {
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("hi from llm".into()),
tool_calls: vec![],
tokens_in: 10,
tokens_out: 20,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
cp.insert(&tc, "a", cfg());
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(
cp,
store,
ext,
llm,
telemetry.clone(),
token_meter,
ledger,
None,
);
let obs = Arc::new(Collecting::default());
let out = runtime
.step_with_observer(
tc.clone(),
"sess-2",
"a",
AgentInput {
text: "hello".into(),
..Default::default()
},
obs.clone(),
)
.await
.unwrap();
assert_eq!(out.reply, "hi from llm");
assert_eq!(*obs.deltas.lock().unwrap(), vec!["hi from llm".to_string()]);
}
/// A non-streaming observer (default `wants_streaming() == false`) must
/// keep `step` on the `complete` path: no token deltas are produced, and
/// the reply is still returned. This is the regression guard for callers
/// (and mocks) that speak the non-streaming OpenAI wire shape — turning
/// streaming on unconditionally would send `stream: true` and break them.
#[tokio::test]
async fn non_streaming_observer_emits_no_deltas() {
#[derive(Default)]
struct CountOnly {
deltas: std::sync::Mutex<u32>,
}
impl crate::StepObserver for CountOnly {
fn on_token_delta(&self, _chunk: &str) {
*self.deltas.lock().expect("lock") += 1;
}
}
let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some("hi from llm".into()),
tool_calls: vec![],
tokens_in: 10,
tokens_out: 20,
})]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
cp.insert(&tc, "a", cfg());
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(cp, store, ext, llm, telemetry, token_meter, ledger, None);
let obs = Arc::new(CountOnly::default());
let out = runtime
.step_with_observer(
tc.clone(),
"sess-3",
"a",
AgentInput {
text: "hello".into(),
..Default::default()
},
obs.clone(),
)
.await
.unwrap();
assert_eq!(out.reply, "hi from llm");
assert_eq!(
*obs.deltas.lock().unwrap(),
0,
"no deltas on the non-streaming path"
);
}
/// A tool call for a tool NOT in the agent's allow-list must still fire
/// `on_tool_call` (so a chip renders with real args) followed by
/// `on_tool_failed` (so it renders as failed/blocked) — NOT
/// `on_tool_result`, which would make a blocked tool look like it
/// succeeded.
#[tokio::test]
async fn blocked_tool_fires_on_tool_call_then_on_tool_failed() {
use crate::state::ToolCallRecord;
#[derive(Default)]
struct ToolEvents {
calls: std::sync::Mutex<Vec<(String, String, serde_json::Value)>>,
results: std::sync::Mutex<Vec<(String, String, serde_json::Value)>>,
failures: std::sync::Mutex<Vec<(String, String, serde_json::Value)>>,
}
impl crate::StepObserver for ToolEvents {
fn on_tool_call(&self, name: &str, call_id: &str, args: &serde_json::Value) {
self.calls.lock().unwrap().push((
name.to_string(),
call_id.to_string(),
args.clone(),
));
}
fn on_tool_result(&self, name: &str, call_id: &str, result: &serde_json::Value) {
self.results.lock().unwrap().push((
name.to_string(),
call_id.to_string(),
result.clone(),
));
}
fn on_tool_failed(&self, name: &str, call_id: &str, error: &serde_json::Value) {
self.failures.lock().unwrap().push((
name.to_string(),
call_id.to_string(),
error.clone(),
));
}
}
let llm = Arc::new(MockLlmBackend::new(vec![
Ok(LlmResponse {
content: None,
tool_calls: vec![ToolCallRecord {
call_id: "call_1".into(),
extension_id: "http".into(),
tool_name: "fetch".into(),
args: serde_json::json!({"url": "https://example.com"}),
}],
tokens_in: 10,
tokens_out: 5,
}),
Ok(LlmResponse {
content: Some("done".into()),
tool_calls: vec![],
tokens_in: 3,
tokens_out: 2,
}),
]));
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
let tc = TenantContext::new("acme", "prod");
// `cfg()` has an empty tools allow-list, so the tool call is blocked.
cp.insert(&tc, "a", cfg());
let cp = Arc::new(cp);
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
let token_meter = Arc::new(crate::cost::MockTokenMeter::new(0));
let ledger = Arc::new(crate::mock::NoopToolLedger);
let runtime = AgentRuntime::new(cp, store, ext, llm, telemetry, token_meter, ledger, None);
let obs = Arc::new(ToolEvents::default());
let out = runtime
.step_with_observer(
tc.clone(),
"sess-4",
"a",
AgentInput {
text: "please fetch".into(),
..Default::default()
},
obs.clone(),
)
.await
.unwrap();
assert_eq!(out.reply, "done");
let calls = obs.calls.lock().unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].0, "fetch");
assert_eq!(calls[0].1, "call_1");
assert_eq!(
calls[0].2,
serde_json::json!({"url": "https://example.com"})
);
drop(calls);
assert!(
obs.results.lock().unwrap().is_empty(),
"a blocked tool must not fire on_tool_result"
);
let failures = obs.failures.lock().unwrap();
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].0, "fetch");
assert_eq!(failures[0].1, "call_1");
assert_eq!(
failures[0].2,
serde_json::json!({"error": "not in allow-list"})
);
}
// --- StepObserver::on_guardrail wiring ------------------------------
//
// A genuine `run_step` integration test would need a `ResolvedGuardrail`
// chain entry whose capability actually resolves, which in turn needs a
// populated `CapabilityRegistry` on the `ExtensionRuntime`. There is no
// public seam to inject offerings directly: `ExtensionRuntime::for_test()`
// builds an empty registry, and the only way to populate one is
// `register_loaded_from_dir`, which requires a real, signed WASM
// extension on disk (see `tests/guardrail_e2e.rs`, which does exactly
// that for the full e2e suite — real component-guardrail-pii binary,
// ephemeral Ed25519 signing key, tempdir). That is too heavy for a
// focused unit test of the observer seam, so per the plan's authorised
// fallback these tests exercise `run_chain` directly and apply the exact
// notify pattern the two `run_step` call sites use (mirrored above),
// without building a full `AgentRuntime`. This still proves the
// regression this task guards against: a BLOCKED denial (Enforce) must
// reach the observer, not just a Monitored one.
#[derive(Default)]
struct RecordingObserver {
guardrails: std::sync::Mutex<Vec<crate::guardrail::GuardrailObservation>>,
}
impl crate::StepObserver for RecordingObserver {
fn on_guardrail(&self, obs: &crate::guardrail::GuardrailObservation) {
self.guardrails.lock().unwrap().push(obs.clone());
}
}
struct DenyingEvaluator {
code: String,
message: String,
}
impl crate::guardrail::GuardrailEvaluator for DenyingEvaluator {
fn evaluate(
&self,
_extension_id: &str,
_input: &crate::guardrail::GuardrailInput,
) -> Result<crate::guardrail::GuardrailVerdict, crate::guardrail::GuardrailInvokeError>
{
Ok(crate::guardrail::GuardrailVerdict::Deny(
crate::guardrail::GuardrailDenyInfo {
code: self.code.clone(),
message: self.message.clone(),
details: None,
},
))
}
}
fn guardrail_run_ctx() -> crate::guardrail::GuardrailRunCtx {
crate::guardrail::GuardrailRunCtx {
agent_id: "a".into(),
session_id: "s1".into(),
tenant_id: "acme".into(),
env_id: "prod".into(),
}
}
/// Mirrors the notify logic at the loop.rs guardrail call sites: forward
/// every `Pass` observation, or the `Denied` observation, to the observer.
fn run_chain_and_notify(
chain: &[crate::guardrail::ResolvedGuardrail],
direction: crate::guardrail::GuardrailDirection,
content: String,
observer: &dyn crate::StepObserver,
evaluator: &dyn crate::guardrail::GuardrailEvaluator,
) -> Result<String, crate::error::AgentError> {
match crate::guardrail::run_chain(
chain,
direction,
content,
&guardrail_run_ctx(),
evaluator,
) {
crate::guardrail::ChainOutcome::Pass {
content,
observations,
} => {
for obs in &observations {
observer.on_guardrail(obs);
}
Ok(content)
}
crate::guardrail::ChainOutcome::Denied {
info,
direction,
observation,
} => {
observer.on_guardrail(&observation);
Err(AgentError::GuardrailDenied {
direction,
code: info.code,
message: info.message,
details: info.details,
})
}
}
}
// NOTE: these two tests pin the notify *pattern* mirrored above (call
// `on_guardrail` for every `Pass` observation, or for a `Denied`
// observation) — they do NOT exercise `run_step`'s real wiring of that
// pattern (see the module doc above for why a genuine `run_step`
// integration test isn't feasible as a focused unit test here). The real
// `run_step` → `observer.on_guardrail` wiring is covered by
// `crates/greentic-aw-runtime/tests/guardrail_e2e.rs`, and the
// `CompositeObserver` fan-out regression (dropping `on_guardrail` when
// fanning out to multiple observers) is covered by
// `crates/greentic-runner-host/src/http/agent_stream.rs`'s
// `composite_fans_out_to_all_members_and_ors_streaming` test.
#[test]
fn guardrail_notify_pattern_reports_a_monitored_denial() {
// A recording observer proves the observation escapes run_chain and
// reaches the seam the host emits from.
let observer = RecordingObserver::default();
let chain = vec![crate::guardrail::ResolvedGuardrail {
extension_id: "ext-pii".into(),
cap_id: "greentic:guardrail/pii".into(),
mandatory: false,
mode: crate::config::GuardrailMode::Monitor,
config: serde_json::Value::Null,
}];
let evaluator = DenyingEvaluator {
code: "pii".into(),
message: "blocked pii".into(),
};
let out = run_chain_and_notify(
&chain,
crate::guardrail::GuardrailDirection::Inbound,
"hi".into(),
&observer,
&evaluator,
);
assert!(out.is_ok(), "monitor mode must not fail the turn");
let seen = observer.guardrails.lock().unwrap();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].action, crate::guardrail::GuardrailAction::Monitored);
}
#[test]
fn guardrail_notify_pattern_reports_a_blocked_denial() {
let observer = RecordingObserver::default();
let chain = vec![crate::guardrail::ResolvedGuardrail {
extension_id: "ext-pii".into(),
cap_id: "greentic:guardrail/pii".into(),
mandatory: false,
mode: crate::config::GuardrailMode::Enforce,
config: serde_json::Value::Null,
}];
let evaluator = DenyingEvaluator {
code: "pii".into(),
message: "blocked pii".into(),
};
let out = run_chain_and_notify(
&chain,
crate::guardrail::GuardrailDirection::Inbound,
"hi".into(),
&observer,
&evaluator,
);
assert!(matches!(out, Err(AgentError::GuardrailDenied { .. })));
let seen = observer.guardrails.lock().unwrap();
assert_eq!(seen.len(), 1, "a blocked denial must still be observed");
assert_eq!(seen[0].action, crate::guardrail::GuardrailAction::Blocked);
}
fn runtime_for_prompt_tests(llm: Arc<MockLlmBackend>, tc: &TenantContext) -> AgentRuntime {
let store = Arc::new(MockAgentStateStore::new());
let telemetry = Arc::new(MockTelemetry::new());
let cp = MockConfigProvider::new();
cp.insert(tc, "a", cfg());
let ext = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
AgentRuntime::new(
Arc::new(cp),
store,
ext,
llm,
telemetry,
Arc::new(crate::cost::MockTokenMeter::new(0)),
Arc::new(crate::mock::NoopToolLedger),
None,
)
}
fn one_reply(text: &str) -> Arc<MockLlmBackend> {
Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
content: Some(text.into()),
tool_calls: vec![],
tokens_in: 1,
tokens_out: 1,
})]))
}
/// The reply recorded on the run trace must be the GUARDED one, so the
/// record has to come after the outbound chain. A behavioural test needs a
/// real guardrail WASM (`tests/guardrail_e2e.rs`, skipped when it is not
/// built); this pins the ordering in the source so the pin holds without it.
#[test]
fn the_reply_is_recorded_after_the_outbound_guardrail_chain() {
let src = include_str!("loop.rs");
let prod = &src[..src
.find("#[cfg(all(test, feature = \"test-mock\"))]")
.unwrap()];
let outbound = prod
.find("crate::guardrail::GuardrailDirection::Outbound,")
.expect("outbound chain call");
let record = prod
.find("t.append(agent_id, \"reply\", &reply)")
.expect("reply record");
assert!(
outbound < record,
"the reply must be recorded after the outbound chain"
);
assert_eq!(
prod.matches("t.append(agent_id, \"reply\"").count(),
1,
"exactly one reply record"
);
}
#[tokio::test]
async fn a_run_trace_view_is_injected_into_the_system_prompt() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
let trace = Arc::new(crate::run_trace::RunTrace::new());
trace.append("outer", "tool", "refund flow approved 40 USD");
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("acme", trace),
runtime.step(
tc.clone(),
"sess-trace",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
),
)
.await
.unwrap();
let prompts = llm.seen_system_prompts.lock().unwrap();
assert!(prompts[0].starts_with("sys"));
assert!(prompts[0].contains("<run_context>"));
assert!(prompts[0].contains("refund flow approved 40 USD"));
}
#[tokio::test]
async fn without_a_run_ctx_the_prompt_is_unchanged() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
runtime
.step(
tc.clone(),
"sess-none",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
)
.await
.unwrap();
let prompts = llm.seen_system_prompts.lock().unwrap();
assert_eq!(prompts[0], "sys");
}
#[tokio::test]
async fn the_final_reply_is_recorded_on_the_trace() {
let llm = one_reply("all done");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm, &tc);
let trace = Arc::new(crate::run_trace::RunTrace::new());
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("acme", trace.clone()),
runtime.step(
tc.clone(),
"sess-rec",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
),
)
.await
.unwrap();
let events = trace.events();
assert_eq!(events.len(), 1);
assert_eq!(events[0].actor, "a");
assert_eq!(events[0].kind, "reply");
assert_eq!(events[0].summary, "all done");
}
#[tokio::test]
async fn a_context_for_another_tenant_is_ignored() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
let trace = Arc::new(crate::run_trace::RunTrace::new());
trace.append("outer", "tool", "other tenant secret");
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("other", trace.clone()),
runtime.step(
tc.clone(),
"sess-foreign",
"a",
AgentInput {
text: "hi".into(),
..Default::default()
},
),
)
.await
.unwrap();
let prompts = llm.seen_system_prompts.lock().unwrap();
assert_eq!(prompts[0], "sys");
assert_eq!(trace.events().len(), 1, "no event may be recorded");
}
fn seeded_trace() -> Arc<crate::run_trace::RunTrace> {
let t = Arc::new(crate::run_trace::RunTrace::new());
t.append("outer", "reply", "SEED-EVENT");
t
}
fn hi() -> AgentInput {
AgentInput {
text: "hi".into(),
..Default::default()
}
}
#[tokio::test]
async fn a_none_mode_context_neither_injects_nor_records() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
let trace = seeded_trace();
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("acme", trace.clone())
.with_mode(crate::share_policy::ShareMode::None),
runtime.step(tc.clone(), "sess-mode-none", "a", hi()),
)
.await
.unwrap();
assert_eq!(llm.seen_system_prompts.lock().unwrap()[0], "sys");
assert_eq!(trace.events().len(), 1, "a none-mode step records nothing");
}
#[tokio::test]
async fn a_detached_context_shadows_the_open_one() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
let outer = seeded_trace();
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("acme", outer.clone()),
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::detached("acme"),
runtime.step(tc.clone(), "sess-detached", "a", hi()),
),
)
.await
.unwrap();
let prompts = llm.seen_system_prompts.lock().unwrap();
assert_eq!(
prompts[0], "sys",
"the outer view must not leak through the shadow"
);
assert_eq!(outer.events().len(), 1, "nothing reaches the outer trace");
}
#[tokio::test]
async fn a_read_mode_context_injects_but_records_nothing() {
let llm = one_reply("ok");
let tc = TenantContext::new("acme", "prod");
let runtime = runtime_for_prompt_tests(llm.clone(), &tc);
let trace = seeded_trace();
crate::run_trace::RunContext::scope(
crate::run_trace::RunContext::new("acme", trace.clone())
.with_mode(crate::share_policy::ShareMode::Read),
runtime.step(tc.clone(), "sess-read", "a", hi()),
)
.await
.unwrap();
assert!(llm.seen_system_prompts.lock().unwrap()[0].contains("SEED-EVENT"));
assert_eq!(trace.events().len(), 1, "a read-only step records nothing");
}
#[test]
fn the_runtime_hands_out_its_policy_per_agent() {
let tc = TenantContext::new("acme", "prod");
let mut modes = crate::share_policy::BindingModes::new();
modes.insert("flow:x".into(), crate::share_policy::ShareMode::Read);
let mut agents = std::collections::HashMap::new();
agents.insert("a".to_string(), modes);
let runtime = runtime_for_prompt_tests(one_reply("ok"), &tc).with_share_policy(Some(
Arc::new(crate::share_policy::SharePolicy::new(agents)),
));
assert!(runtime.share_policy().is_some());
assert!(runtime.share_modes_for("a").is_some());
assert!(runtime.share_modes_for("b").is_none());
}
/// A catalog resolve (and ledger read) slower than the lock TTL must not
/// lose the lock. Real time, kv backend, 300 ms TTL, 50 ms keep-alive.
#[tokio::test]
async fn a_slow_catalog_resolve_keeps_the_session_lock_alive() {
use crate::state::AgentStateStore;
use std::time::Duration;
let store = crate::state_kv::KvAgentStateStore::new(Arc::new(crate::kv::MemoryKv::new()))
.with_lock_ttl(Duration::from_millis(300));
let tc = TenantContext::new("acme", "prod");
// Control: the same wait WITHOUT a keep-alive lapses the lock, so the
// wrapped case below is a real test of the wrapper.
let bare = store
.acquire_lock(&tc, "bare", Duration::from_millis(50))
.await
.expect("lock");
tokio::time::sleep(Duration::from_millis(900)).await;
assert!(
matches!(
bare.refresh().await,
Err(crate::error::StateError::LockLost)
),
"without keep-alive the 300 ms lock must have lapsed"
);
let lock = store
.acquire_lock(&tc, "held", Duration::from_millis(50))
.await
.expect("lock");
let (ledger, catalogs) = super::resolve_under_lock(
&lock,
Duration::from_millis(50),
async {
tokio::time::sleep(Duration::from_millis(300)).await;
"ledger"
},
async {
// Slower than the TTL: a sequentially probed catalog.
tokio::time::sleep(Duration::from_millis(900)).await;
"catalogs"
},
)
.await;
assert_eq!((ledger, catalogs), ("ledger", "catalogs"));
lock.refresh()
.await
.expect("the lock must still be ours after the slow resolve");
}
}