rig-core 0.40.0

An opinionated library for building LLM powered applications.
Documentation
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
//! Hooks for observing and steering an agent run.
//!
//! A hook is a single [`AgentHook::on_event`] method that the agent loop calls
//! at every observable point of a run — before each model call, on each model
//! response, around every tool call, on streamed deltas, and when the model
//! emits an invalid tool call. Each call receives a [`HookContext`] (run-scoped
//! identity + a shared scratchpad) and a [`StepEvent`] describing what is
//! happening, and returns a [`Flow`] that lets the hook observe, patch the
//! request, skip a tool, terminate the run early, or (for invalid tool calls)
//! retry/repair/skip recovery.
//!
//! Unlike the old multi-method hook trait, a hook implements one method and
//! matches on the event it cares about — every other event falls through to the
//! default [`Flow::Continue`]. Hooks compose in a [`HookStack`] that runs several
//! hooks in registration order.
//!
//! # Composition: mergeable patches vs. terminal control actions
//!
//! How a [`HookStack`] combines several hooks' [`Flow`] results depends on the
//! event, and this is the central behavior to understand:
//!
//! - **[`StepEvent::CompletionCall`] — accumulate & merge.** Every hook is
//!   consulted. A hook that returns [`Flow::PatchRequest`] does **not** stop the
//!   others: patches from all hooks are merged in registration order into one
//!   effective patch (see [`RequestPatch`] for the per-field merge rules). This
//!   lets a RAG hook, a tool-policy hook, and a provider-param hook all
//!   contribute to the same turn. [`Flow::Terminate`] stops the stack and is
//!   honored; any other (unsupported) flow stops the stack and fails closed,
//!   discarding the accumulated patch.
//! - **[`StepEvent::ToolCall`] / [`StepEvent::ToolResult`] — chain.** Every hook
//!   is consulted; a [`Flow::RewriteArgs`] / [`Flow::RewriteResult`] does not
//!   stop the others — the rewritten value is threaded into the next hook's
//!   event, so hook *N* observes the value as rewritten by hooks *1..N-1* and may
//!   rewrite further (a redaction hook and a truncation hook compose).
//!   [`Flow::Skip`] / [`Flow::Terminate`] are terminal mid-chain.
//! - **Every other event — first non-[`Continue`](Flow::Continue) wins.** These
//!   are observe-only or recovery events ([`CompletionResponse`](StepEvent::CompletionResponse),
//!   [`ModelTurnFinished`](StepEvent::ModelTurnFinished),
//!   [`InvalidToolCall`](StepEvent::InvalidToolCall), the streamed deltas): the
//!   first hook to return a non-[`Continue`](Flow::Continue) result short-circuits
//!   the rest.
//!
//! **Blind merge.** During accumulation/chaining a hook does *not* see earlier
//! hooks' contributions in its event payload for `CompletionCall` (it sees the
//! agent baseline); for `ToolCall`/`ToolResult` it *does* see the running
//! rewritten value. `CompletionCall` patches are declarative with documented
//! conflict rules, so blind merge is sufficient and keeps [`StepEvent`] `Copy`.
//!
//! **Ordering guidance.** Because [`Flow::Terminate`] short-circuits the stack,
//! register observe-only hooks (telemetry) *before* steering hooks so a later
//! terminate cannot hide the run from them. A [`HookStack`] pushed *as a hook*
//! into another stack composes correctly: it returns its own net flow (a merged
//! patch, a threaded rewrite, or a terminal action) which the outer stack folds
//! in again — nesting never reintroduces short-circuiting on mergeable results.
//!
//! # Why a returned [`Flow`], not a `next()`-style middleware
//!
//! A hook returns a typed [`Flow`] rather than receiving a `next` continuation it
//! must invoke. A `next()`/middleware model — where each layer has to call
//! `next(ctx)` to let the rest of the chain *and* the wrapped action run — carries
//! a well-known footgun: forgetting the call silently disables every downstream
//! hook and the action itself, with no error. The declarative returned-[`Flow`]
//! model makes that impossible: proceeding is the explicit [`Flow::Continue`], and
//! any action an event cannot honor is fail-closed (it terminates the run) rather
//! than silently skipped.
//!
//! Hooks are a *driver* concern: they are async, side-effecting and generic over
//! the model, so they live in the [`AgentRunner`](crate::agent::AgentRunner)
//! layer rather than inside the sans-IO, serializable
//! [`AgentRun`](crate::agent::run::AgentRun) state machine.
//!
//! # Migrating from `PromptHook`
//!
//! The previous eight-method `PromptHook<M>` trait is replaced by the single
//! [`AgentHook::on_event`] method. Each old method becomes one match arm on a
//! [`StepEvent`] variant, and the value it used to return becomes the [`Flow`]
//! you return from that arm (every event you don't care about falls through to
//! [`Flow::Continue`]). Every `on_event` now also receives a [`HookContext`]
//! first argument. Attach one or more hooks with `add_hook`.
//!
//! | Old `PromptHook` method | [`StepEvent`] variant | [`Flow`] to return |
//! |---|---|---|
//! | `on_completion_call` | [`CompletionCall`](StepEvent::CompletionCall) `{ prompt, history, turn }` | [`cont`](Flow::cont) / [`patch_request`](Flow::patch_request) / [`terminate`](Flow::terminate) |
//! | `on_completion_response` | [`CompletionResponse`](StepEvent::CompletionResponse) `{ prompt, response }` | [`cont`](Flow::cont) / [`terminate`](Flow::terminate) |
//! | `on_invalid_tool_call` | [`InvalidToolCall`](StepEvent::InvalidToolCall)`(ctx)` | [`fail`](Flow::fail) (default) / [`retry`](Flow::retry) / [`repair`](Flow::repair) / [`skip`](Flow::skip) / [`terminate`](Flow::terminate) |
//! | `on_tool_call` | [`ToolCall`](StepEvent::ToolCall) `{ tool_name, tool_call_id, internal_call_id, args }` | [`cont`](Flow::cont) / [`rewrite_args`](Flow::rewrite_args) / [`skip`](Flow::skip) / [`terminate`](Flow::terminate) |
//! | `on_tool_result` | [`ToolResult`](StepEvent::ToolResult) `{ tool_name, .., result, outcome, extensions }` | [`cont`](Flow::cont) / [`rewrite_result`](Flow::rewrite_result) / [`terminate`](Flow::terminate) |
//! | `on_text_delta` | [`TextDelta`](StepEvent::TextDelta) `{ delta, aggregated }` | [`cont`](Flow::cont) / [`terminate`](Flow::terminate) |
//! | `on_tool_call_delta` | [`ToolCallDelta`](StepEvent::ToolCallDelta) `{ tool_call_id, internal_call_id, tool_name, delta }` | [`cont`](Flow::cont) / [`terminate`](Flow::terminate) |
//! | `on_stream_completion_response_finish` | [`StreamResponseFinish`](StepEvent::StreamResponseFinish) `{ prompt, response }` | [`cont`](Flow::cont) / [`terminate`](Flow::terminate) |
//! | *(new, both surfaces)* | [`ModelTurnFinished`](StepEvent::ModelTurnFinished) `{ turn, content, usage }` | [`cont`](Flow::cont) / [`terminate`](Flow::terminate) |
//!
//! Behavioral notes:
//!
//! - The invalid-tool-call default is still fail-fast: returning
//!   [`Flow::Continue`] for [`StepEvent::InvalidToolCall`] is treated as
//!   [`Flow::fail`], matching the old trait's default `on_invalid_tool_call`.
//! - A hook opts out of an event by returning [`Flow::cont`] from that arm,
//!   instead of leaving a trait method unimplemented.
//! - For per-delta hooks, override [`AgentHook::observes`] to skip the
//!   high-frequency [`TextDelta`](StepEvent::TextDelta) /
//!   [`ToolCallDelta`](StepEvent::ToolCallDelta) events you don't consume.
//!
//! # Steering on structured tool outcomes
//!
//! [`StepEvent::ToolResult`] carries a structured
//! [`ToolOutcome`] alongside the model-visible
//! `result`, so a hook can branch on *why* a tool failed — a timeout vs. a 404 —
//! without parsing strings. The motivating case: abort after repeated timeouts,
//! but let a not-found flow back to the model as recoverable feedback.
//!
//! ```rust,ignore
//! use rig_core::agent::{AgentHook, Flow, HookContext, StepEvent};
//! use rig_core::completion::CompletionModel;
//! use rig_core::tool::ToolFailureKind;
//!
//! #[derive(Clone, Default)]
//! struct TimeoutCount(usize);
//!
//! struct OutcomePolicy;
//!
//! impl<M: CompletionModel> AgentHook<M> for OutcomePolicy {
//!     async fn on_event(&self, ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
//!         if let StepEvent::ToolResult { outcome, .. } = event {
//!             // Repeated timeouts abort the run; a 404 does not.
//!             if outcome.is_error_kind(ToolFailureKind::Timeout) {
//!                 let count = ctx.scratchpad().update(|c: &mut TimeoutCount| {
//!                     c.0 += 1;
//!                     c.0
//!                 });
//!                 if count >= 10 {
//!                     return Flow::terminate("aborting after repeated tool timeouts");
//!                 }
//!             }
//!             // `NotFound` falls through to `Flow::cont`: the model sees the
//!             // error text and may try another path.
//!         }
//!         Flow::cont()
//!     }
//! }
//! ```

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use crate::{
    OneOrMany,
    completion::{CompletionModel, Document, Usage},
    json_utils,
    message::{AssistantContent, Message, ToolChoice},
    tool::{ToolCallExtensions, ToolOutcome, ToolResultExtensions},
    wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync},
};

/// Opaque, process-scoped identifier for a single agent run.
///
/// Minted once when a run's [`HookContext`] is created and stable for the whole
/// run, so a hook can correlate every event it observes (across turns, tool
/// calls and streamed deltas) to one run. It is a short URL-safe string from
/// Rig's internal, non-cryptographic id generator — not globally unique across
/// process restarts, and not security-sensitive.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RunId(String);

impl RunId {
    /// Mint a fresh run id.
    pub(crate) fn generate() -> Self {
        Self(crate::id::generate())
    }

    /// The id as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RunId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// A run-scoped, shared scratchpad passed to every hook via [`HookContext`].
///
/// A type-map with interior mutability: cooperating hooks read and write typed
/// values keyed by type, sharing per-run state (a turn counter, a running
/// budget, a phase flag) without each rolling its own `Arc<Mutex<…>>`. Every
/// hook in a run receives the same [`HookContext`] by shared reference, so they
/// all see one scratchpad (and cloning a `Scratchpad` shares its storage too); a
/// fresh run starts with an empty one.
///
/// Hooks receive `&HookContext` (shared), so every accessor here takes `&self`
/// and mutates through an internal lock. Reads clone the stored value out (the
/// lock cannot hand out a borrow), so store cheaply-cloneable values.
///
/// # Concurrency
///
/// Most events are dispatched sequentially within a run, but at
/// [`tool_concurrency`](crate::agent::AgentRunner::tool_concurrency)` > 1` the
/// [`ToolCall`](StepEvent::ToolCall) / [`ToolResult`](StepEvent::ToolResult)
/// hooks for *different* tools in the same turn may run **concurrently**, all
/// sharing this one scratchpad. Each accessor ([`insert`](Self::insert),
/// [`update`](Self::update), …) is race-free *per operation* (it holds the lock
/// for the whole read-modify-write), but the framework imposes **no
/// deterministic ordering** across those concurrent tool hooks — the order in
/// which two tools' hooks touch the scratchpad depends on tool completion
/// timing. Prefer commutative / idempotent state (a counter, a set union), or
/// key per-tool state by the tool call id / internal call id, rather than
/// relying on the order of concurrent updates.
///
/// # Example
/// ```
/// # use rig_core::agent::hook::Scratchpad;
/// #[derive(Clone, Default)]
/// struct Calls(u32);
///
/// let pad = Scratchpad::default();
/// pad.update(|c: &mut Calls| c.0 += 1);
/// assert_eq!(pad.get::<Calls>().map(|c| c.0), Some(1));
/// ```
#[derive(Clone, Default)]
pub struct Scratchpad {
    // Reuses the tested `ToolCallExtensions` type-map as the storage, wrapped in
    // a shared lock so `&HookContext` hooks can mutate it. Under
    // `tool_concurrency > 1` several tools' `ToolCall`/`ToolResult` hooks may
    // touch this concurrently, so the lock is load-bearing, not decorative.
    inner: Arc<std::sync::Mutex<ToolCallExtensions>>,
}

impl Scratchpad {
    fn lock(&self) -> std::sync::MutexGuard<'_, ToolCallExtensions> {
        // A poisoned scratchpad (a hook panicked while holding the lock) should
        // not cascade into cancelling later hooks or the run; recover the guard.
        self.inner.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Insert a typed value, returning the previous value of the same type.
    pub fn insert<T: Clone + WasmCompatSend + WasmCompatSync + 'static>(
        &self,
        val: T,
    ) -> Option<T> {
        self.lock().insert(val)
    }

    /// Get a clone of the stored value of type `T`, if present.
    pub fn get<T: Clone + WasmCompatSend + WasmCompatSync + 'static>(&self) -> Option<T> {
        self.lock().get::<T>().cloned()
    }

    /// Whether a value of type `T` is present.
    pub fn contains<T: WasmCompatSend + WasmCompatSync + 'static>(&self) -> bool {
        self.lock().contains::<T>()
    }

    /// Remove and return the stored value of type `T`, if present.
    pub fn remove<T: Clone + WasmCompatSend + WasmCompatSync + 'static>(&self) -> Option<T> {
        self.lock().remove::<T>()
    }

    /// Read-modify-write the value of type `T` under one lock acquisition,
    /// starting from [`Default`] when absent. The value is stored back and the
    /// closure's return value is returned.
    ///
    /// The whole read-modify-write is atomic (no lost updates), but at
    /// `tool_concurrency > 1` it imposes **no ordering** across concurrent tool
    /// hooks — see the [type-level concurrency note](Scratchpad#concurrency).
    /// This is the race-free way to bump a counter or accumulate:
    /// ```
    /// # use rig_core::agent::hook::Scratchpad;
    /// # #[derive(Clone, Default)] struct Total(u64);
    /// # let pad = Scratchpad::default();
    /// pad.update(|t: &mut Total| t.0 += 10);
    /// ```
    pub fn update<T, R>(&self, f: impl FnOnce(&mut T) -> R) -> R
    where
        T: Clone + Default + WasmCompatSend + WasmCompatSync + 'static,
    {
        let mut guard = self.lock();
        let mut val = guard.remove::<T>().unwrap_or_default();
        let out = f(&mut val);
        guard.insert(val);
        out
    }
}

impl std::fmt::Debug for Scratchpad {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scratchpad")
            .field("entries", &self.lock().len())
            .finish()
    }
}

/// Run-scoped context passed by shared reference to every [`AgentHook::on_event`]
/// call.
///
/// Carries the run's identity and a shared [`Scratchpad`]. It is a *driver*
/// construct built once per run by [`AgentRunner`](crate::agent::AgentRunner);
/// nothing here reaches the sans-IO [`AgentRun`](crate::agent::run::AgentRun)
/// state machine. Hooks hold it by `&`, so all fields are read via accessors and
/// run-scoped mutation goes through [`scratchpad`](Self::scratchpad).
///
/// One `HookContext` is shared by every hook invocation in a run. At
/// [`tool_concurrency`](crate::agent::AgentRunner::tool_concurrency)` > 1` the
/// [`ToolCall`](StepEvent::ToolCall) / [`ToolResult`](StepEvent::ToolResult)
/// hooks for different tools in a turn can run concurrently against this shared
/// context — see the [`Scratchpad` concurrency note](Scratchpad#concurrency) for
/// how to store run-scoped state safely under that concurrency.
#[derive(Debug)]
pub struct HookContext {
    run_id: RunId,
    // Interior-mutable so the driver can advance it each turn while hooks hold a
    // shared `&HookContext`; also the reason the context is `Sync`.
    turn: AtomicUsize,
    is_streaming: bool,
    agent_name: Option<String>,
    scratchpad: Scratchpad,
}

impl HookContext {
    /// Build a fresh run-scoped context. `is_streaming` records which surface is
    /// driving ([`run`](crate::agent::AgentRunner::run) vs.
    /// [`stream`](crate::agent::AgentRunner::stream)).
    pub(crate) fn new(is_streaming: bool, agent_name: Option<String>) -> Self {
        Self {
            run_id: RunId::generate(),
            turn: AtomicUsize::new(0),
            is_streaming,
            agent_name,
            scratchpad: Scratchpad::default(),
        }
    }

    /// Record the current one-based model-call index (set by the driver before
    /// each turn), so events that don't carry a turn still see it.
    pub(crate) fn set_turn(&self, turn: usize) {
        self.turn.store(turn, Ordering::Relaxed);
    }

    /// The run's stable identifier.
    pub fn run_id(&self) -> &RunId {
        &self.run_id
    }

    /// The current one-based model-call index (0 before the first turn).
    pub fn turn(&self) -> usize {
        self.turn.load(Ordering::Relaxed)
    }

    /// Whether this run is driven by the streaming surface.
    pub fn is_streaming(&self) -> bool {
        self.is_streaming
    }

    /// The agent's configured name, if any.
    pub fn agent_name(&self) -> Option<&str> {
        self.agent_name.as_deref()
    }

    /// The run-scoped shared scratchpad.
    pub fn scratchpad(&self) -> &Scratchpad {
        &self.scratchpad
    }
}

// `&HookContext` is borrowed across `.await` points in async hook dispatch, so
// on native targets `HookContext` must stay `Sync` (and `Send`). This fails to
// compile if a future change drops the property.
#[cfg(not(target_family = "wasm"))]
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<HookContext>();
};

/// Context passed to a hook on a [`StepEvent::InvalidToolCall`] event when the
/// model emits a tool call that Rig would reject before normal tool-call
/// handling or execution.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct InvalidToolCallContext {
    /// Tool name emitted by the model.
    pub tool_name: String,
    /// Provider-supplied tool call ID, when available.
    pub tool_call_id: Option<String>,
    /// Internal Rig call ID, when available.
    pub internal_call_id: Option<String>,
    /// JSON arguments emitted for the tool call, when available.
    pub args: Option<String>,
    /// Executable Rig tools advertised to the provider for this turn.
    pub available_tools: Vec<String>,
    /// Tools allowed by the active [`ToolChoice`] for this turn.
    pub allowed_tools: Vec<String>,
    /// Active tool choice for this turn.
    pub tool_choice: Option<ToolChoice>,
    /// Diagnostic chat history including the rejected model output when available.
    pub chat_history: Vec<Message>,
    /// Whether the rejected call came from the streaming path.
    pub is_streaming: bool,
}

/// Recovery action for an invalid tool call, used internally by
/// [`AgentRun`](crate::agent::run::AgentRun). Hooks express recovery via
/// [`Flow`]; the [`AgentRunner`](crate::agent::AgentRunner) translates a `Flow`
/// returned for a [`StepEvent::InvalidToolCall`] into this type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InvalidToolCallHookAction {
    /// Preserve Rig's default fail-fast behavior.
    Fail,
    /// Retry the model turn with corrective feedback.
    Retry { feedback: String },
    /// Rewrite only the emitted tool name. The repaired name is revalidated
    /// against registered tools and the current `ToolChoice` before use.
    Repair { tool_name: String },
    /// Treat an invalid structured tool call as skipped by returning synthetic
    /// feedback as its tool result. This does not execute the invalid tool.
    Skip { reason: String },
}

impl InvalidToolCallHookAction {
    /// Preserve Rig's default fail-fast behavior.
    pub fn fail() -> Self {
        Self::Fail
    }

    /// Retry the model turn with corrective feedback.
    pub fn retry(feedback: impl Into<String>) -> Self {
        Self::Retry {
            feedback: feedback.into(),
        }
    }

    /// Repair the emitted tool name.
    pub fn repair(tool_name: impl Into<String>) -> Self {
        Self::Repair {
            tool_name: tool_name.into(),
        }
    }

    /// Skip the invalid call with a synthetic tool result.
    pub fn skip(reason: impl Into<String>) -> Self {
        Self::Skip {
            reason: reason.into(),
        }
    }
}

/// An observable point in an agent run, passed to [`AgentHook::on_event`].
///
/// `StepEvent` borrows everything it carries (it is `Copy`), so a hook may
/// inspect the event without taking ownership and a [`HookStack`] can forward
/// the same event to each hook in turn.
///
/// The streaming-only variants ([`TextDelta`](StepEvent::TextDelta),
/// [`ToolCallDelta`](StepEvent::ToolCallDelta) and
/// [`StreamResponseFinish`](StepEvent::StreamResponseFinish)) are emitted only
/// by [`AgentRunner::stream`](crate::agent::AgentRunner::stream).
#[non_exhaustive]
pub enum StepEvent<'a, M: CompletionModel> {
    /// Before a completion request is sent to the model. Honors
    /// [`Flow::Continue`], [`Flow::PatchRequest`] (patch this turn's request) and
    /// [`Flow::Terminate`]. Across a [`HookStack`], every hook's
    /// [`PatchRequest`](Flow::PatchRequest) is merged (see the module docs).
    CompletionCall {
        /// The prompt message for this turn.
        prompt: &'a Message,
        /// The chat history preceding `prompt`.
        history: &'a [Message],
        /// One-based index of this model call within the run.
        turn: usize,
    },
    /// After a non-streaming completion response is received. Suppressed for
    /// turns recovered by invalid tool-call repair, skip, or retry. Honors
    /// [`Flow::Continue`] and [`Flow::Terminate`]. The medium-specific
    /// (non-streaming) counterpart of [`ModelTurnFinished`](Self::ModelTurnFinished),
    /// carrying the raw provider response.
    CompletionResponse {
        /// The prompt message for this turn.
        prompt: &'a Message,
        /// The model's completion response.
        response: &'a crate::completion::CompletionResponse<M::Response>,
    },
    /// After a model turn is accepted into the run, on **both** surfaces,
    /// regardless of whether the turn produced text, tool calls, reasoning, or
    /// mixed content. This is the normalized, medium-neutral counterpart of
    /// [`CompletionResponse`](Self::CompletionResponse) (non-streaming) and
    /// [`StreamResponseFinish`](Self::StreamResponseFinish) (streaming) — use it
    /// for telemetry that must fire once per turn everywhere, including a
    /// streamed tool-only turn that fires no `StreamResponseFinish`. Suppressed
    /// for turns recovered by invalid tool-call repair, skip, or retry, and
    /// fired *after* the medium-specific raw event when one fires. Observe-only:
    /// honors [`Flow::Continue`] and [`Flow::Terminate`].
    ModelTurnFinished {
        /// One-based index of this model call within the run.
        turn: usize,
        /// The model's assistant content for this turn — the canonical committed
        /// model output. For an ordinary turn this is exactly what is recorded
        /// into the run. On a structured-output Tool-mode turn that finalizes by
        /// calling the output tool, this is the model-emitted content **including**
        /// that output-tool call; the run then persists the turn as assistant text
        /// (the structured output) with the tool call dropped, so the persisted
        /// message differs from this content.
        content: &'a OneOrMany<AssistantContent>,
        /// Token usage for this turn (zeroed if the provider reported none).
        usage: Usage,
    },
    /// The model emitted a tool call that is unknown or disallowed for this
    /// turn. Honors [`Flow::Fail`] (the default), [`Flow::Retry`],
    /// [`Flow::Repair`], [`Flow::Skip`] and [`Flow::Terminate`];
    /// [`Flow::Continue`] is treated as [`Flow::Fail`].
    InvalidToolCall(&'a InvalidToolCallContext),
    /// Before a tool is executed. Honors [`Flow::Continue`],
    /// [`Flow::RewriteArgs`] (execute the tool with rewritten arguments),
    /// [`Flow::Skip`] (return `reason` as the tool result without executing) and
    /// [`Flow::Terminate`]. Across a [`HookStack`], [`RewriteArgs`](Flow::RewriteArgs)
    /// is chained: `args` reflects prior hooks' rewrites (see the module docs).
    ToolCall {
        /// Name of the tool about to be called.
        tool_name: &'a str,
        /// Provider-supplied tool call ID, when available.
        tool_call_id: Option<&'a str>,
        /// Internal Rig call ID correlating this call's events.
        internal_call_id: &'a str,
        /// JSON arguments for the call.
        args: &'a str,
    },
    /// After a tool has produced a result (or a [`ToolCall`](Self::ToolCall) hook
    /// [skipped](Flow::Skip) it). Honors [`Flow::Continue`],
    /// [`Flow::RewriteResult`] (substitute the result the model sees) and
    /// [`Flow::Terminate`].
    ///
    /// `result` is the model-visible output, and `outcome` / `extensions` are the
    /// **structured** execution result — the machine-visible half a hook inspects
    /// without parsing `result`. `outcome` distinguishes success from a classified
    /// [`ToolFailure`](crate::tool::ToolFailure) (timeout, not-found, …), a
    /// [`Skipped`](crate::tool::ToolOutcome::Skipped) call, or a
    /// [`Denied`](crate::tool::ToolOutcome::Denied) one; `extensions` carries
    /// provider/application metadata the tool attached that is never sent to the
    /// model.
    ///
    /// For the first hook, `result` is the tool's actual output and `outcome` its
    /// raw structured outcome; across a [`HookStack`],
    /// [`RewriteResult`](Flow::RewriteResult) is chained so a later hook sees the
    /// prior hook's replacement in `result`. A rewrite changes only `result` (the
    /// model-visible text) — `outcome` and `extensions` are the tool's raw
    /// structured result throughout, so a redaction hook cannot mask the true
    /// outcome from a later policy hook (see the module docs).
    ToolResult {
        /// Name of the tool that was called.
        tool_name: &'a str,
        /// Provider-supplied tool call ID, when available.
        tool_call_id: Option<&'a str>,
        /// Internal Rig call ID correlating this call's events.
        internal_call_id: &'a str,
        /// JSON arguments for the call.
        args: &'a str,
        /// The model-visible tool result. Reflects any earlier hook's
        /// [`RewriteResult`](Flow::RewriteResult); the first hook sees the tool's
        /// actual output.
        result: &'a str,
        /// The structured outcome of the execution (success / classified error /
        /// skipped / denied). The raw outcome, unaffected by `RewriteResult`.
        outcome: &'a ToolOutcome,
        /// Metadata the tool attached to its result, never sent to the model.
        extensions: &'a ToolResultExtensions,
    },
    /// Streaming only: a text delta was received. `aggregated` is the full text
    /// accumulated for the turn so far. Honors [`Flow::Continue`] and
    /// [`Flow::Terminate`].
    TextDelta {
        /// The newly received text fragment.
        delta: &'a str,
        /// All text accumulated for the turn so far.
        aggregated: &'a str,
    },
    /// Streaming only: a tool-call delta was received. `tool_name` is `Some` on
    /// the first delta for a tool call and `None` on subsequent deltas. Honors
    /// [`Flow::Continue`] and [`Flow::Terminate`].
    ToolCallDelta {
        /// Provider-supplied tool call ID.
        tool_call_id: &'a str,
        /// Internal Rig call ID correlating this call's events.
        internal_call_id: &'a str,
        /// Tool name, present on the first delta only.
        tool_name: Option<&'a str>,
        /// The newly received argument fragment.
        delta: &'a str,
    },
    /// Streaming only: the provider finished streaming a completion response.
    /// This is the streaming counterpart of [`CompletionResponse`](Self::CompletionResponse)
    /// and, like it, is suppressed for turns recovered by invalid tool-call
    /// repair, skip, or retry. Note one medium-specific difference from
    /// `CompletionResponse`: it fires only on turns that streamed assistant
    /// **text** — a turn that emits only a tool call (or only reasoning) does
    /// not fire it. For a per-turn event that fires on *every* turn on both
    /// surfaces, use [`ModelTurnFinished`](Self::ModelTurnFinished). Honors
    /// [`Flow::Continue`] and [`Flow::Terminate`].
    StreamResponseFinish {
        /// The prompt message for this turn.
        prompt: &'a Message,
        /// The provider's final streaming response.
        response: &'a M::StreamingResponse,
    },
}

// `StepEvent` only holds shared references and `Copy` scalars, so it is `Copy`.
// These are hand-written to avoid `derive` adding a spurious `M: Clone`/`M: Copy`
// bound (the generic parameter never appears by value).
impl<M: CompletionModel> Clone for StepEvent<'_, M> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<M: CompletionModel> Copy for StepEvent<'_, M> {}

/// The discriminant of a [`StepEvent`].
///
/// Passed to [`AgentHook::observes`] so a hook can declare which events it cares
/// about without the runner building the (sometimes expensive) event payload —
/// in particular the high-frequency streaming [`TextDelta`](StepEventKind::TextDelta)
/// and [`ToolCallDelta`](StepEventKind::ToolCallDelta) events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StepEventKind {
    /// [`StepEvent::CompletionCall`].
    CompletionCall,
    /// [`StepEvent::CompletionResponse`].
    CompletionResponse,
    /// [`StepEvent::ModelTurnFinished`].
    ModelTurnFinished,
    /// [`StepEvent::InvalidToolCall`].
    InvalidToolCall,
    /// [`StepEvent::ToolCall`].
    ToolCall,
    /// [`StepEvent::ToolResult`].
    ToolResult,
    /// [`StepEvent::TextDelta`].
    TextDelta,
    /// [`StepEvent::ToolCallDelta`].
    ToolCallDelta,
    /// [`StepEvent::StreamResponseFinish`].
    StreamResponseFinish,
}

impl<M: CompletionModel> StepEvent<'_, M> {
    /// The [`StepEventKind`] discriminant of this event.
    pub fn kind(&self) -> StepEventKind {
        match self {
            StepEvent::CompletionCall { .. } => StepEventKind::CompletionCall,
            StepEvent::CompletionResponse { .. } => StepEventKind::CompletionResponse,
            StepEvent::ModelTurnFinished { .. } => StepEventKind::ModelTurnFinished,
            StepEvent::InvalidToolCall(_) => StepEventKind::InvalidToolCall,
            StepEvent::ToolCall { .. } => StepEventKind::ToolCall,
            StepEvent::ToolResult { .. } => StepEventKind::ToolResult,
            StepEvent::TextDelta { .. } => StepEventKind::TextDelta,
            StepEvent::ToolCallDelta { .. } => StepEventKind::ToolCallDelta,
            StepEvent::StreamResponseFinish { .. } => StepEventKind::StreamResponseFinish,
        }
    }
}

/// A partial patch over the model request for a single turn, returned by a hook
/// via [`Flow::PatchRequest`] on a [`StepEvent::CompletionCall`] event.
///
/// Every field is optional: a `Some` value overrides the agent's configured
/// value for this turn, a `None` value inherits it. The patch is **per-turn and
/// non-sticky** — it never changes the agent's baseline, so the next turn
/// re-fires [`CompletionCall`](StepEvent::CompletionCall) and resolves from the
/// baseline again.
///
/// # Merge behavior
///
/// Two kinds of merge apply. When several hooks in a [`HookStack`] each return a
/// patch, they are combined **hook ⊕ hook in registration order** with these
/// per-field rules; the effective patch is then applied **patch → baseline**.
///
/// | Field | hook ⊕ hook (registration order) | patch → baseline |
/// |---|---|---|
/// | `extra_context` | append (earlier hooks' docs first) | append after static + dynamic context |
/// | `additional_params` | shallow-merge top-level keys, later hook wins | shallow-merge onto baseline params |
/// | `preamble` | last writer wins (warns on conflict) | replaces |
/// | `temperature`, `max_tokens`, `tool_choice` | last writer wins (warns on conflict) | replaces |
/// | `active_tools` | set **intersection** (warns when empty) | narrows the advertised set |
/// | `history` | last writer wins (warns on conflict) | replaces the messages sent this turn |
///
/// `active_tools` intersects rather than last-writer-wins because it is an
/// allow-list guardrail: two narrowing hooks must compose as *narrowing*. All
/// last-writer-wins conflicts emit a `tracing::warn!` so composition stays
/// debuggable — additive guidance belongs in `extra_context` documents, not in
/// preamble concatenation.
///
/// Build one with the setters:
///
/// ```rust,ignore
/// Flow::patch_request(
///     RequestPatch::new()
///         .tool_choice(ToolChoice::Required)
///         .active_tools(["search"])
///         .temperature(0.0),
/// )
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct RequestPatch {
    /// Override the system prompt / preamble for this turn.
    pub preamble: Option<String>,
    /// Override the sampling temperature for this turn.
    pub temperature: Option<f64>,
    /// Override the max output tokens for this turn.
    pub max_tokens: Option<u64>,
    /// Override the tool choice for this turn.
    pub tool_choice: Option<ToolChoice>,
    /// Restrict the advertised tools to this allow-list (by name) for this turn.
    /// `Some(vec![])` advertises no executable tools; `None` keeps the full set.
    pub active_tools: Option<Vec<String>>,
    /// Provider-passthrough params shallow-merged onto the agent's for this turn.
    pub additional_params: Option<serde_json::Value>,
    /// Extra context documents appended (after static and dynamic context) for
    /// this turn only. The passive-RAG injection point.
    pub extra_context: Vec<Document>,
    /// Replace the prior chat history sent to the provider **this turn only**.
    /// The persisted transcript and the run state are untouched, and RAG's query
    /// text still derives from the original prompt/history — this changes only
    /// what messages are sent. `None` sends the real history. The enabling
    /// primitive for context-window compaction / summarization middleware.
    pub history: Option<Vec<Message>>,
}

/// Last-writer-wins merge for a scalar patch field, warning on a real conflict.
fn merge_last_wins<T>(earlier: Option<T>, later: Option<T>, field: &str) -> Option<T> {
    match (earlier, later) {
        (Some(_), Some(l)) => {
            tracing::warn!(
                patch_field = field,
                "two hooks set `{field}` on the same turn; the later hook wins"
            );
            Some(l)
        }
        (earlier, later) => later.or(earlier),
    }
}

impl RequestPatch {
    /// An empty patch — a no-op, identical to returning [`Flow::cont`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the system prompt / preamble for this turn.
    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
        self.preamble = Some(preamble.into());
        self
    }

    /// Override the sampling temperature for this turn.
    pub fn temperature(mut self, temperature: f64) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Override the max output tokens for this turn.
    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// Override the tool choice for this turn.
    ///
    /// Not every provider honors `tool_choice`: some in-core providers (e.g.
    /// Ollama, Hyperbolic, Mira, Perplexity) ignore it and log a warning, so
    /// forcing a tool this way is a no-op there. A choice a provider cannot
    /// represent (e.g. a multi-name [`ToolChoice::Specific`] on Anthropic, which
    /// forces a single tool) surfaces as a request error rather than being
    /// silently downgraded.
    pub fn tool_choice(mut self, tool_choice: ToolChoice) -> Self {
        self.tool_choice = Some(tool_choice);
        self
    }

    /// Restrict the advertised tools to this allow-list (by name) for this turn.
    ///
    /// This narrows the executable tool set, so it composes with `tool_choice`:
    /// if the effective tool choice is a [`ToolChoice::Specific`] naming a tool
    /// that `active_tools` filters out (e.g. the agent's baseline choice is
    /// inherited because this patch didn't set its own), the request fails
    /// closed with a request error rather than silently forcing a dropped tool.
    /// When narrowing the set, set a compatible `tool_choice` in the same patch.
    pub fn active_tools<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.active_tools = Some(names.into_iter().map(Into::into).collect());
        self
    }

    /// Shallow-merge these provider-passthrough params onto the agent's for this
    /// turn.
    pub fn additional_params(mut self, additional_params: serde_json::Value) -> Self {
        self.additional_params = Some(additional_params);
        self
    }

    /// Append extra context documents for this turn (the passive-RAG injection
    /// point). Documents are appended after the agent's static and dynamic
    /// (vector-store) context, in the order added.
    pub fn extra_context<I>(mut self, docs: I) -> Self
    where
        I: IntoIterator<Item = Document>,
    {
        self.extra_context.extend(docs);
        self
    }

    /// Append a single extra context document for this turn.
    pub fn context(mut self, doc: Document) -> Self {
        self.extra_context.push(doc);
        self
    }

    /// Replace the prior chat history sent to the provider **this turn only**.
    /// The persisted transcript is untouched; RAG query text still derives from
    /// the original history. Use for context-window compaction / summarization.
    pub fn history<I>(mut self, history: I) -> Self
    where
        I: IntoIterator<Item = Message>,
    {
        self.history = Some(history.into_iter().collect());
        self
    }

    /// Whether this patch has no effect (all fields unset).
    pub(crate) fn is_empty(&self) -> bool {
        self.preamble.is_none()
            && self.temperature.is_none()
            && self.max_tokens.is_none()
            && self.tool_choice.is_none()
            && self.active_tools.is_none()
            && self.additional_params.is_none()
            && self.extra_context.is_empty()
            && self.history.is_none()
    }

    /// Merge a later hook's patch onto this one (registration order: `self` is
    /// the accumulated earlier hooks, `later` is the next hook). See the struct
    /// docs for the per-field rules.
    pub(crate) fn merge(mut self, later: RequestPatch) -> RequestPatch {
        // extra_context: append (earlier hooks' documents first).
        self.extra_context.extend(later.extra_context);

        // additional_params: shallow-merge when both are objects (later wins per
        // key), otherwise the later non-None value wins wholesale — mirroring the
        // patch → baseline behavior in request assembly.
        self.additional_params = match (self.additional_params.take(), later.additional_params) {
            (Some(base), Some(patch)) if base.is_object() && patch.is_object() => {
                Some(json_utils::merge(base, patch))
            }
            (base, patch) => patch.or(base),
        };

        // Scalars + preamble + history: last writer wins, warn on real conflict.
        self.preamble = merge_last_wins(self.preamble, later.preamble, "preamble");
        self.temperature = merge_last_wins(self.temperature, later.temperature, "temperature");
        self.max_tokens = merge_last_wins(self.max_tokens, later.max_tokens, "max_tokens");
        self.tool_choice = merge_last_wins(self.tool_choice, later.tool_choice, "tool_choice");
        self.history = merge_last_wins(self.history, later.history, "history");

        // active_tools: set intersection (two narrowing guardrails compose as
        // narrowing). One-sided keeps the present allow-list.
        self.active_tools = match (self.active_tools.take(), later.active_tools) {
            (Some(earlier), Some(later)) => {
                let later_set: std::collections::BTreeSet<&String> = later.iter().collect();
                let intersection: Vec<String> = earlier
                    .into_iter()
                    .filter(|name| later_set.contains(name))
                    .collect();
                if intersection.is_empty() {
                    tracing::warn!(
                        "two hooks' `active_tools` allow-lists have an empty intersection; \
                         no executable tools will be advertised this turn"
                    );
                }
                Some(intersection)
            }
            (earlier, later) => earlier.or(later),
        };

        self
    }
}

/// Control-flow result returned by [`AgentHook::on_event`].
///
/// Each [`StepEvent`] honors a specific subset of variants (documented on each
/// event). The runner is **fail-closed**: an action an event cannot honor never
/// silently proceeds — it terminates the run with a diagnostic error. In
/// particular, a blocking action such as [`Flow::Fail`] returned for a
/// [`StepEvent::ToolCall`] stops the run rather than letting the tool execute.
/// Returning [`Flow::Continue`] is always the way to "do nothing".
///
/// `Flow` is `PartialEq` but not `Eq`, because [`Flow::PatchRequest`] carries a
/// [`RequestPatch`] whose `temperature` is an `f64`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Flow {
    /// Proceed normally.
    Continue,
    /// Terminate the agent run early, surfacing `reason`.
    Terminate {
        /// Why the run is being terminated.
        reason: String,
    },
    /// Skip the action: for [`StepEvent::ToolCall`], return `reason` as the tool
    /// result without executing the tool; for [`StepEvent::InvalidToolCall`],
    /// record `reason` as a synthetic result for the invalid call.
    Skip {
        /// The message returned to the model in place of the tool result. It is
        /// delivered verbatim, so it doubles as a prompt: state that the tool did
        /// not run and, unless you want the model to try again, tell it not to
        /// retry — a bare `"denied"` often makes the model re-emit the same call.
        reason: String,
    },
    /// [`StepEvent::ToolCall`] only: rewrite the tool-call arguments, then
    /// execute the tool with the replacement. This is the steering action for
    /// guardrails that normalize, clamp, redirect, or inject scoped parameters
    /// before a tool runs.
    ///
    /// The rewritten arguments are what the tool is invoked with, what the
    /// following [`StepEvent::ToolResult`] reports, and what the
    /// `gen_ai.tool.call.arguments` span field records.
    ///
    /// This rewrites only what the tool *executes against*, not the model's
    /// transcript: the assistant message that recorded the original tool call is
    /// unchanged and keeps the model's original arguments. It is therefore an
    /// execution-args rewrite (inject defaults, clamp a range, redirect a path),
    /// **not** a history redactor — it does not scrub a value the model already
    /// emitted from the conversation.
    ///
    /// Across a [`HookStack`], rewrites **chain**: the rewritten arguments are
    /// threaded into the next hook's [`ToolCall`](StepEvent::ToolCall) event, so
    /// several hooks can each refine the arguments in registration order.
    RewriteArgs {
        /// The JSON arguments the tool is invoked with, in place of the ones the
        /// model emitted.
        args: serde_json::Value,
    },
    /// [`StepEvent::ToolResult`] only: replace the tool's result with this string
    /// before the model sees it. The post-execution counterpart of
    /// [`RewriteArgs`](Flow::RewriteArgs) — for guardrails that redact, truncate,
    /// or normalize a tool's output.
    ///
    /// The replacement is what the model receives as the tool result and what the
    /// `gen_ai.tool.call.result` span field records. As with
    /// [`RewriteArgs`](Flow::RewriteArgs), this changes only what the model
    /// *sees*: the tool still ran and produced its real output (which the first
    /// hook's [`ToolResult`](StepEvent::ToolResult) event observed before this
    /// replacement is applied). It does not scrub the tool's output from logs.
    ///
    /// The replacement is delivered to the model verbatim — it is not re-parsed
    /// as structured/multimodal tool output, so a JSON-shaped replacement reaches
    /// the model as literal text.
    ///
    /// Across a [`HookStack`], rewrites **chain**: the replacement is threaded
    /// into the next hook's [`ToolResult`](StepEvent::ToolResult) event, so a
    /// redaction hook and a truncation hook can compose in registration order.
    RewriteResult {
        /// The result delivered to the model in place of the tool's actual
        /// output.
        result: String,
    },
    /// [`StepEvent::CompletionCall`] only: patch fields of the model request for
    /// this turn before it is sent. The per-turn request-steering action — for
    /// hooks that adjust the system prompt, sampling, tool choice, the advertised
    /// tool set, or inject context documents from run state (force a tool on the
    /// first turn, lower the temperature on a critical step, add RAG context).
    ///
    /// The patch is partial ([`RequestPatch`]): each set field replaces (or, for
    /// `additional_params`/`extra_context`, merges onto) the agent's configured
    /// value; unset fields are inherited. It applies to *this turn only* and does
    /// not change the agent's baseline — the next turn re-fires
    /// [`CompletionCall`](StepEvent::CompletionCall) and re-resolves from it.
    ///
    /// Across a [`HookStack`], patches from all hooks **accumulate** and merge in
    /// registration order (see [`RequestPatch`] and the module docs); this action
    /// therefore does *not* short-circuit later hooks.
    PatchRequest {
        /// The partial request patch applied to this turn.
        patch: RequestPatch,
    },
    /// [`StepEvent::InvalidToolCall`] only: fail the run fast (the default for
    /// invalid tool calls).
    Fail,
    /// [`StepEvent::InvalidToolCall`] only: retry the model turn with corrective
    /// feedback.
    Retry {
        /// Feedback appended to the conversation before re-prompting.
        feedback: String,
    },
    /// [`StepEvent::InvalidToolCall`] only: rewrite the emitted tool name, which
    /// is then revalidated against the allowed tools.
    Repair {
        /// The corrected tool name.
        tool_name: String,
    },
}

impl Flow {
    /// Continue the agent loop as normal.
    pub fn cont() -> Self {
        Self::Continue
    }

    /// Terminate the agent run early with a reason.
    pub fn terminate(reason: impl Into<String>) -> Self {
        Self::Terminate {
            reason: reason.into(),
        }
    }

    /// Skip the current tool call (or invalid call) with the provided reason.
    ///
    /// `reason` is delivered to the model verbatim as the tool result, so it
    /// doubles as a prompt — tell the model the tool did not run and whether to
    /// retry, or it may re-emit the identical call:
    ///
    /// ```rust,ignore
    /// Flow::skip("Not executed (denied by policy). Do not retry unless the user asks.")
    /// ```
    pub fn skip(reason: impl Into<String>) -> Self {
        Self::Skip {
            reason: reason.into(),
        }
    }

    /// Rewrite a tool call's arguments, then execute the tool with the
    /// replacement (tool calls only).
    ///
    /// Accepts anything convertible into a [`serde_json::Value`] — most often
    /// the [`serde_json::json!`] macro or a value built from the parsed original
    /// arguments. To rewrite from a typed value instead, use
    /// [`try_rewrite_args`](Flow::try_rewrite_args).
    ///
    /// ```rust,ignore
    /// // Inject a scoped parameter the model never sees, leaving the rest intact.
    /// let mut args: serde_json::Value = serde_json::from_str(emitted_args)?;
    /// args["account_id"] = serde_json::json!(session.account_id);
    /// Flow::rewrite_args(args)
    /// ```
    pub fn rewrite_args(args: impl Into<serde_json::Value>) -> Self {
        Self::RewriteArgs { args: args.into() }
    }

    /// Rewrite a tool call's arguments from a serializable value (tool calls
    /// only), serializing it to JSON.
    ///
    /// This is the typed convenience over [`rewrite_args`](Flow::rewrite_args)
    /// for callers that hold a Rust args struct. It only fails if the value
    /// cannot be serialized to JSON; a hook typically maps that error to
    /// [`Flow::terminate`]:
    ///
    /// ```rust,ignore
    /// Flow::try_rewrite_args(&new_args).unwrap_or_else(|e| Flow::terminate(e.to_string()))
    /// ```
    pub fn try_rewrite_args<T: serde::Serialize>(value: &T) -> Result<Self, serde_json::Error> {
        Ok(Self::RewriteArgs {
            args: serde_json::to_value(value)?,
        })
    }

    /// Replace a tool's result with `result` before the model sees it (tool
    /// results only).
    ///
    /// The post-execution counterpart of [`rewrite_args`](Flow::rewrite_args),
    /// for guardrails that redact, truncate, or normalize a tool's output:
    ///
    /// ```rust,ignore
    /// // Redact a secret from the tool output before it reaches the model.
    /// Flow::rewrite_result(redact(tool_output))
    /// ```
    pub fn rewrite_result(result: impl Into<String>) -> Self {
        Self::RewriteResult {
            result: result.into(),
        }
    }

    /// Patch fields of the model request for this turn (completion calls only).
    /// See [`RequestPatch`] for the partial-patch, per-turn, mergeable semantics.
    pub fn patch_request(patch: RequestPatch) -> Self {
        Self::PatchRequest { patch }
    }

    /// Fail fast on an invalid tool call (the default).
    pub fn fail() -> Self {
        Self::Fail
    }

    /// Retry the model turn with corrective feedback (invalid tool calls only).
    ///
    /// A common recovery is to let the model self-correct by naming the valid
    /// tools, built from the diagnostics in [`InvalidToolCallContext`]:
    ///
    /// ```rust,ignore
    /// // On the `StepEvent::InvalidToolCall(ctx)` arm of `on_event`:
    /// Flow::retry(format!(
    ///     "`{}` is not a valid tool. Call one of: [{}].",
    ///     ctx.tool_name,
    ///     ctx.available_tools.join(", "),
    /// ))
    /// ```
    ///
    /// Without such a hook the invalid-call default stays fail-closed
    /// ([`Flow::Continue`] is treated as [`Flow::fail`]).
    pub fn retry(feedback: impl Into<String>) -> Self {
        Self::Retry {
            feedback: feedback.into(),
        }
    }

    /// Repair the emitted tool name (invalid tool calls only).
    pub fn repair(tool_name: impl Into<String>) -> Self {
        Self::Repair {
            tool_name: tool_name.into(),
        }
    }
}

/// A per-run hook that observes and steers an agent run.
///
/// Implement [`on_event`](AgentHook::on_event) and match on the [`StepEvent`]
/// variants you care about; every other event falls through to the default
/// [`Flow::Continue`]. Hooks must be cheap to share (`Clone` is not required —
/// hooks are held behind an `Arc` once registered).
///
/// # Example
/// ```rust,ignore
/// use rig_core::agent::{AgentHook, Flow, HookContext, StepEvent};
/// use rig_core::completion::CompletionModel;
///
/// #[derive(Clone)]
/// struct Logger;
///
/// impl<M: CompletionModel> AgentHook<M> for Logger {
///     async fn on_event(&self, ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
///         if let StepEvent::ToolCall { tool_name, args, .. } = event {
///             println!("[run {}] calling {tool_name}({args})", ctx.run_id());
///         }
///         Flow::cont()
///     }
/// }
/// ```
pub trait AgentHook<M>: WasmCompatSend + WasmCompatSync
where
    M: CompletionModel,
{
    /// Called at every observable point of the agent run (subject to
    /// [`observes`](Self::observes)). Receives the run-scoped [`HookContext`] and
    /// the [`StepEvent`]. The default implementation is a no-op: it ignores every
    /// event and returns [`Flow::Continue`]. It does **not** narrow
    /// [`observes`](Self::observes) (which defaults to `true`), so a hook that
    /// takes this default is still dispatched every event — override `observes`
    /// to skip the high-frequency delta events. (The `()` no-op hook overrides
    /// `observes` to `false`, so the runner skips dispatching those delta events
    /// to it; it still receives, and returns [`Flow::Continue`] for, every other
    /// event.)
    fn on_event(
        &self,
        ctx: &HookContext,
        event: StepEvent<'_, M>,
    ) -> impl Future<Output = Flow> + WasmCompatSend {
        let _ = (ctx, event);
        async { Flow::Continue }
    }

    /// Resolve a [`ToolCall`](StepEvent::ToolCall) for this hook, returning its
    /// [`Flow`] plus any tool-argument rewrite that must be **salvaged** when the
    /// hook short-circuits — so a nested [`HookStack`] never loses an inner
    /// [`Flow::RewriteArgs`] behind a later inner
    /// [`Flow::Skip`]/[`Flow::Terminate`].
    ///
    /// The default — correct for any leaf hook — dispatches the `ToolCall` event
    /// to [`on_event`](Self::on_event) and reports **no** salvaged rewrite: a
    /// single hook returns exactly one [`Flow`], so it can either rewrite (via
    /// [`Flow::RewriteArgs`]) or short-circuit, never both. [`HookStack`]
    /// overrides this to compose its members' resolutions, preserving an inner
    /// rewrite across a short-circuit. This is an internal composition hook;
    /// implementing it is only necessary for a custom composite hook that wraps
    /// other hooks and needs the same rewrite-preserving behavior.
    #[doc(hidden)]
    fn resolve_tool_call(
        &self,
        ctx: &HookContext,
        tool_name: &str,
        tool_call_id: Option<&str>,
        internal_call_id: &str,
        args: &str,
    ) -> impl Future<Output = (Flow, Option<serde_json::Value>)> + WasmCompatSend {
        async move {
            let flow = self
                .on_event(
                    ctx,
                    StepEvent::ToolCall {
                        tool_name,
                        tool_call_id,
                        internal_call_id,
                        args,
                    },
                )
                .await;
            (flow, None)
        }
    }

    /// Whether this hook observes events of the given [`StepEventKind`].
    ///
    /// This is a **performance hint for the high-frequency streaming
    /// [`TextDelta`](StepEventKind::TextDelta) /
    /// [`ToolCallDelta`](StepEventKind::ToolCallDelta) events**, which otherwise
    /// cost one boxed future per delta. The runner skips building and
    /// dispatching a delta event only when *no* hook in the stack observes it
    /// (interest is OR-combined across the stack), so a hook may still be
    /// invoked for a delta a sibling observes — `on_event` must therefore stay
    /// total (return [`Flow::Continue`] for events it ignores) rather than
    /// assume it is only called for observed kinds.
    ///
    /// Control flow is **never** changed by `observes`: the shared, steering
    /// events ([`ToolCall`](StepEventKind::ToolCall),
    /// [`InvalidToolCall`](StepEventKind::InvalidToolCall), …) fire identically
    /// regardless of this method, so `run()` and `stream()` stay in lock-step.
    /// The default observes everything.
    fn observes(&self, kind: StepEventKind) -> bool {
        let _ = kind;
        true
    }
}

/// The no-op hook: observes nothing, never alters control flow.
impl<M> AgentHook<M> for ()
where
    M: CompletionModel,
{
    /// Observe nothing, so the runner skips building/dispatching the
    /// high-frequency streaming delta events (`TextDelta` / `ToolCallDelta`,
    /// the only events gated on `observes`) for a `()` hook.
    fn observes(&self, _kind: StepEventKind) -> bool {
        false
    }
}

/// Object-safe shim over [`AgentHook`] so a [`HookStack`] can hold a
/// heterogeneous list of hooks behind `Arc`.
trait DynAgentHook<M>: WasmCompatSend + WasmCompatSync
where
    M: CompletionModel,
{
    fn on_event_boxed<'a>(
        &'a self,
        ctx: &'a HookContext,
        event: StepEvent<'a, M>,
    ) -> WasmBoxedFuture<'a, Flow>
    where
        M: 'a;

    /// Object-safe [`AgentHook::resolve_tool_call`]. Preserves an inner
    /// [`Flow::RewriteArgs`] across a short-circuit so nested [`HookStack`]s
    /// compose correctly.
    fn resolve_tool_call_boxed<'a>(
        &'a self,
        ctx: &'a HookContext,
        tool_name: &'a str,
        tool_call_id: Option<&'a str>,
        internal_call_id: &'a str,
        args: &'a str,
    ) -> WasmBoxedFuture<'a, (Flow, Option<serde_json::Value>)>
    where
        M: 'a;

    fn observes_dyn(&self, kind: StepEventKind) -> bool;
}

impl<M, H> DynAgentHook<M> for H
where
    M: CompletionModel,
    H: AgentHook<M>,
{
    fn on_event_boxed<'a>(
        &'a self,
        ctx: &'a HookContext,
        event: StepEvent<'a, M>,
    ) -> WasmBoxedFuture<'a, Flow>
    where
        M: 'a,
    {
        Box::pin(self.on_event(ctx, event))
    }

    fn resolve_tool_call_boxed<'a>(
        &'a self,
        ctx: &'a HookContext,
        tool_name: &'a str,
        tool_call_id: Option<&'a str>,
        internal_call_id: &'a str,
        args: &'a str,
    ) -> WasmBoxedFuture<'a, (Flow, Option<serde_json::Value>)>
    where
        M: 'a,
    {
        Box::pin(self.resolve_tool_call(ctx, tool_name, tool_call_id, internal_call_id, args))
    }

    fn observes_dyn(&self, kind: StepEventKind) -> bool {
        self.observes(kind)
    }
}

/// An ordered list of hooks run as one hook.
///
/// Each hook is consulted in registration order. How their [`Flow`] results
/// combine depends on the event (see the [module docs](self)):
/// [`CompletionCall`](StepEvent::CompletionCall) patches **accumulate**;
/// [`ToolCall`](StepEvent::ToolCall) / [`ToolResult`](StepEvent::ToolResult)
/// rewrites **chain**; every other event uses **first non-[`Continue`](Flow::Continue)
/// wins**. Because the runner is fail-closed, a non-`Continue` action always
/// takes effect or terminates the run — it is never silently ignored. An empty
/// stack is the no-op hook and [`observes`](HookStack::observes) nothing, so the
/// runner skips event dispatch for it entirely.
///
/// This is the default hook type carried by an
/// [`Agent`](crate::agent::Agent) and an
/// [`AgentRunner`](crate::agent::AgentRunner); build one with
/// [`add_hook`](crate::agent::AgentRunner::add_hook).
pub struct HookStack<M>
where
    M: CompletionModel,
{
    hooks: Vec<Arc<dyn DynAgentHook<M>>>,
}

// Hand-written so the impls do not require `M: Clone`/`M: Default`: `M` only
// appears inside `Arc<dyn DynAgentHook<M>>`, never by value.
impl<M> Clone for HookStack<M>
where
    M: CompletionModel,
{
    fn clone(&self) -> Self {
        Self {
            hooks: self.hooks.clone(),
        }
    }
}

impl<M> Default for HookStack<M>
where
    M: CompletionModel,
{
    fn default() -> Self {
        Self { hooks: Vec::new() }
    }
}

impl<M> std::fmt::Debug for HookStack<M>
where
    M: CompletionModel,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HookStack")
            .field("len", &self.hooks.len())
            .finish()
    }
}

impl<M> HookStack<M>
where
    M: CompletionModel,
{
    /// An empty stack (the no-op hook).
    pub fn new() -> Self {
        Self::default()
    }

    /// A stack containing a single hook.
    pub fn with<H>(hook: H) -> Self
    where
        H: AgentHook<M> + 'static,
    {
        let mut stack = Self::new();
        stack.push(hook);
        stack
    }

    /// Append a hook to the end of the stack.
    pub fn push<H>(&mut self, hook: H)
    where
        H: AgentHook<M> + 'static,
    {
        self.hooks.push(Arc::new(hook));
    }

    /// Whether the stack contains no hooks.
    pub fn is_empty(&self) -> bool {
        self.hooks.is_empty()
    }

    /// Number of hooks in the stack.
    pub fn len(&self) -> usize {
        self.hooks.len()
    }
}

impl<M> AgentHook<M> for HookStack<M>
where
    M: CompletionModel,
{
    /// Compose the stack's members' [`ToolCall`](StepEvent::ToolCall)
    /// resolutions, threading tool-arg rewrites through the chain **and**
    /// preserving them across a short-circuit — including for a member that is
    /// itself a [`HookStack`], which is why members are consulted via
    /// [`resolve_tool_call`](AgentHook::resolve_tool_call) rather than
    /// [`on_event`](AgentHook::on_event) (the latter can only return a single
    /// [`Flow`], losing an inner rewrite behind an inner `Skip`/`Terminate`).
    ///
    /// When the chain proceeds, any rewrite is carried by the returned [`Flow`]
    /// itself ([`RewriteArgs`](Flow::RewriteArgs) for a rewriting chain,
    /// [`Continue`](Flow::Continue) otherwise) and the second element is `None`.
    /// When a member short-circuits with [`Flow::Skip`] / [`Flow::Terminate`] (or
    /// a fail-closed action), that action is returned in the first element while
    /// the accumulated rewrite is salvaged into the second element, so the caller
    /// (`run_single_tool`) can still report the rewritten args on the resulting
    /// [`ToolResult`](StepEvent::ToolResult) event and in tracing rather than
    /// leaking the model's original (pre-rewrite) args. The two are therefore
    /// mutually exclusive: the [`Flow`] is [`RewriteArgs`](Flow::RewriteArgs) only
    /// when the second element is `None`.
    async fn resolve_tool_call(
        &self,
        ctx: &HookContext,
        tool_name: &str,
        tool_call_id: Option<&str>,
        internal_call_id: &str,
        args: &str,
    ) -> (Flow, Option<serde_json::Value>) {
        let mut effective: Option<serde_json::Value> = None;
        for hook in &self.hooks {
            let rewritten = effective.as_ref().map(json_utils::value_to_json_string);
            let args_for_hook = rewritten.as_deref().unwrap_or(args);
            let (flow, salvaged) = hook
                .resolve_tool_call_boxed(
                    ctx,
                    tool_name,
                    tool_call_id,
                    internal_call_id,
                    args_for_hook,
                )
                .await;
            // A member (e.g. a nested `HookStack`) may have rewritten the args
            // before short-circuiting; adopt that rewrite so it is not lost.
            if let Some(rewrite) = salvaged {
                effective = Some(rewrite);
            }
            match flow {
                Flow::Continue => {}
                Flow::RewriteArgs { args } => effective = Some(args),
                // A short-circuit drops the accumulated rewrite from the returned
                // flow, so salvage it in the second element for the caller.
                other => return (other, effective),
            }
        }
        // The chain proceeded: surface any rewrite through the flow itself.
        match effective {
            Some(args) => (Flow::RewriteArgs { args }, None),
            None => (Flow::Continue, None),
        }
    }

    async fn on_event(&self, ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
        match event {
            // Accumulate mergeable request patches from every hook (registration
            // order); short-circuit on `Terminate` or any flow the event cannot
            // honor (fail-closed downstream, discarding the accumulated patch).
            // Hooks see the agent baseline, not earlier hooks' patches (blind
            // merge), which keeps `StepEvent` `Copy`.
            StepEvent::CompletionCall { .. } => {
                let mut merged: Option<RequestPatch> = None;
                for hook in &self.hooks {
                    match hook.on_event_boxed(ctx, event).await {
                        Flow::Continue => {}
                        Flow::PatchRequest { patch } => {
                            merged = Some(match merged {
                                Some(acc) => acc.merge(patch),
                                None => patch,
                            });
                        }
                        other => return other,
                    }
                }
                match merged {
                    Some(patch) if !patch.is_empty() => Flow::PatchRequest { patch },
                    _ => Flow::Continue,
                }
            }
            // Chain tool-arg rewrites: thread the effective arguments through
            // each hook so a later hook observes (and may further rewrite) the
            // value produced by earlier hooks. A proceeding chain surfaces the
            // rewrite as `RewriteArgs`; `Skip`/`Terminate` are terminal and any
            // other flow is returned for fail-closed handling. The salvaged
            // rewrite (second element) matters only to `run_single_tool`, which
            // must report it on a short-circuited `ToolResult`; it is dropped
            // here (this result is observe-only).
            StepEvent::ToolCall {
                tool_name,
                tool_call_id,
                internal_call_id,
                args,
            } => {
                self.resolve_tool_call(ctx, tool_name, tool_call_id, internal_call_id, args)
                    .await
                    .0
            }
            // Chain tool-result rewrites: thread the effective (model-visible)
            // result through each hook (the first hook sees the tool's real
            // output). The structured `outcome`/`extensions` are the tool's raw
            // result and are passed unchanged to every hook — a rewrite alters
            // only the model-visible text, never the outcome a later policy sees.
            StepEvent::ToolResult {
                tool_name,
                tool_call_id,
                internal_call_id,
                args,
                result,
                outcome,
                extensions,
            } => {
                let mut effective: Option<String> = None;
                for hook in &self.hooks {
                    let result_for_hook = effective.as_deref().unwrap_or(result);
                    let per_hook = StepEvent::ToolResult {
                        tool_name,
                        tool_call_id,
                        internal_call_id,
                        args,
                        result: result_for_hook,
                        outcome,
                        extensions,
                    };
                    match hook.on_event_boxed(ctx, per_hook).await {
                        Flow::Continue => {}
                        Flow::RewriteResult { result } => effective = Some(result),
                        other => return other,
                    }
                }
                match effective {
                    Some(result) => Flow::RewriteResult { result },
                    None => Flow::Continue,
                }
            }
            // Observe-only / recovery events: first non-`Continue` wins.
            _ => {
                for hook in &self.hooks {
                    match hook.on_event_boxed(ctx, event).await {
                        Flow::Continue => {}
                        other => return other,
                    }
                }
                Flow::Continue
            }
        }
    }

    /// The stack observes an event kind if any of its hooks does (so an empty
    /// stack observes nothing).
    fn observes(&self, kind: StepEventKind) -> bool {
        self.hooks.iter().any(|hook| hook.observes_dyn(kind))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use super::{
        AgentHook, Flow, HookContext, HookStack, RequestPatch, Scratchpad, StepEvent, StepEventKind,
    };
    use crate::test_utils::MockCompletionModel;

    type M = MockCompletionModel;

    fn ctx() -> HookContext {
        HookContext::new(false, Some("test-agent".to_string()))
    }

    /// Pushes its label when invoked and returns `Continue` or `Terminate`.
    struct Recorder {
        label: u32,
        log: Arc<Mutex<Vec<u32>>>,
        stop: bool,
    }

    impl AgentHook<M> for Recorder {
        async fn on_event(&self, _ctx: &HookContext, _event: StepEvent<'_, M>) -> Flow {
            self.log.lock().expect("log").push(self.label);
            if self.stop {
                Flow::terminate("stop")
            } else {
                Flow::cont()
            }
        }
    }

    /// Observes exactly one event kind (used to probe stack-level `observes`).
    struct ObservesOnly(StepEventKind);

    impl AgentHook<M> for ObservesOnly {
        async fn on_event(&self, _ctx: &HookContext, _event: StepEvent<'_, M>) -> Flow {
            Flow::cont()
        }

        fn observes(&self, kind: StepEventKind) -> bool {
            kind == self.0
        }
    }

    /// A hook that returns a fixed patch on `CompletionCall`, and records its
    /// label so we can prove every hook ran.
    struct Patcher {
        label: u32,
        log: Arc<Mutex<Vec<u32>>>,
        patch: RequestPatch,
    }

    impl AgentHook<M> for Patcher {
        async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
            self.log.lock().expect("log").push(self.label);
            if matches!(event, StepEvent::CompletionCall { .. }) {
                Flow::patch_request(self.patch.clone())
            } else {
                Flow::cont()
            }
        }
    }

    /// A cheap, M-agnostic event to dispatch (no model response required).
    fn tool_call_event() -> StepEvent<'static, M> {
        StepEvent::ToolCall {
            tool_name: "add",
            tool_call_id: Some("tc1"),
            internal_call_id: "ic1",
            args: "{}",
        }
    }

    fn completion_call_event() -> StepEvent<'static, M> {
        static PROMPT: std::sync::OnceLock<crate::message::Message> = std::sync::OnceLock::new();
        let prompt = PROMPT.get_or_init(|| crate::message::Message::user("hi"));
        StepEvent::CompletionCall {
            prompt,
            history: &[],
            turn: 1,
        }
    }

    #[tokio::test]
    async fn runs_hooks_in_registration_order_and_consults_all_on_continue() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut stack = HookStack::<M>::with(Recorder {
            label: 1,
            log: log.clone(),
            stop: false,
        });
        stack.push(Recorder {
            label: 2,
            log: log.clone(),
            stop: false,
        });

        let flow = stack.on_event(&ctx(), tool_call_event()).await;

        assert!(matches!(flow, Flow::Continue));
        assert_eq!(*log.lock().expect("log"), vec![1, 2]);
    }

    #[tokio::test]
    async fn first_terminate_short_circuits_on_chained_tool_call() {
        // For a tool-call (a chained event), `Terminate` is terminal mid-chain,
        // so a later hook must not run once an earlier hook terminates.
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut stack = HookStack::<M>::with(Recorder {
            label: 1,
            log: log.clone(),
            stop: true,
        });
        stack.push(Recorder {
            label: 2,
            log: log.clone(),
            stop: false,
        });

        let flow = stack.on_event(&ctx(), tool_call_event()).await;

        assert!(matches!(flow, Flow::Terminate { .. }));
        assert_eq!(
            *log.lock().expect("log"),
            vec![1],
            "a later hook must not run after an earlier hook terminates"
        );
    }

    #[tokio::test]
    async fn first_terminate_short_circuits_on_observe_only_events() {
        // For an observe-only event (the `_ =>` first-non-`Continue`-wins arm,
        // here a `TextDelta`), the first hook to terminate must short-circuit the
        // rest — this exercises the arm the chained tool-call test does not.
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut stack = HookStack::<M>::with(Recorder {
            label: 1,
            log: log.clone(),
            stop: true,
        });
        stack.push(Recorder {
            label: 2,
            log: log.clone(),
            stop: false,
        });

        let flow = stack
            .on_event(
                &ctx(),
                StepEvent::TextDelta {
                    delta: "hi",
                    aggregated: "hi",
                },
            )
            .await;

        assert!(matches!(flow, Flow::Terminate { .. }));
        assert_eq!(
            *log.lock().expect("log"),
            vec![1],
            "a later hook must not run after an earlier hook terminates an observe-only event"
        );
    }

    #[tokio::test]
    async fn completion_call_patches_accumulate_and_consult_every_hook() {
        // The core composability fix: a patch from hook 1 must NOT skip hook 2.
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut stack = HookStack::<M>::with(Patcher {
            label: 1,
            log: log.clone(),
            patch: RequestPatch::new().temperature(0.1),
        });
        stack.push(Patcher {
            label: 2,
            log: log.clone(),
            patch: RequestPatch::new().max_tokens(256),
        });

        let flow = stack.on_event(&ctx(), completion_call_event()).await;

        assert_eq!(
            *log.lock().expect("log"),
            vec![1, 2],
            "both hooks must run; a mergeable patch does not short-circuit"
        );
        match flow {
            Flow::PatchRequest { patch } => {
                assert_eq!(patch.temperature, Some(0.1));
                assert_eq!(patch.max_tokens, Some(256));
            }
            other => panic!("expected a merged PatchRequest, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn completion_call_terminate_short_circuits_and_discards_patch() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut stack = HookStack::<M>::with(Patcher {
            label: 1,
            log: log.clone(),
            patch: RequestPatch::new().temperature(0.1),
        });
        // A terminating recorder in the middle.
        stack.push(Recorder {
            label: 2,
            log: log.clone(),
            stop: true,
        });
        stack.push(Patcher {
            label: 3,
            log: log.clone(),
            patch: RequestPatch::new().max_tokens(256),
        });

        let flow = stack.on_event(&ctx(), completion_call_event()).await;

        assert!(matches!(flow, Flow::Terminate { .. }));
        assert_eq!(
            *log.lock().expect("log"),
            vec![1, 2],
            "hook 3 must not run after a terminate"
        );
    }

    #[tokio::test]
    async fn nested_stack_composes_patches_without_inner_short_circuit() {
        // A HookStack pushed as a hook must not reintroduce short-circuiting:
        // the inner stack returns its own merged patch, which the outer stack
        // merges again.
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut inner = HookStack::<M>::with(Patcher {
            label: 1,
            log: log.clone(),
            patch: RequestPatch::new().temperature(0.2),
        });
        inner.push(Patcher {
            label: 2,
            log: log.clone(),
            patch: RequestPatch::new().max_tokens(128),
        });

        let mut outer = HookStack::<M>::with(inner);
        outer.push(Patcher {
            label: 3,
            log: log.clone(),
            patch: RequestPatch::new().preamble("outer"),
        });

        let flow = outer.on_event(&ctx(), completion_call_event()).await;

        assert_eq!(
            *log.lock().expect("log"),
            vec![1, 2, 3],
            "every hook, including both inner-stack hooks, must run"
        );
        match flow {
            Flow::PatchRequest { patch } => {
                assert_eq!(patch.temperature, Some(0.2));
                assert_eq!(patch.max_tokens, Some(128));
                assert_eq!(patch.preamble.as_deref(), Some("outer"));
            }
            other => panic!("expected a merged PatchRequest, got {other:?}"),
        }
    }

    #[test]
    fn stack_observes_is_the_or_of_its_members() {
        let mut stack = HookStack::<M>::with(ObservesOnly(StepEventKind::ToolCall));
        stack.push(ObservesOnly(StepEventKind::ToolResult));

        assert!(stack.observes(StepEventKind::ToolCall));
        assert!(stack.observes(StepEventKind::ToolResult));
        assert!(
            !stack.observes(StepEventKind::TextDelta),
            "no member observes TextDelta, so the stack must not either"
        );
    }

    #[tokio::test]
    async fn empty_stack_continues_and_observes_nothing() {
        let stack = HookStack::<M>::new();

        assert!(stack.is_empty());
        assert!(!stack.observes(StepEventKind::ToolCall));
        assert!(!stack.observes(StepEventKind::TextDelta));
        assert!(matches!(
            stack.on_event(&ctx(), tool_call_event()).await,
            Flow::Continue
        ));
    }

    #[test]
    fn unit_hook_observes_no_event_kind() {
        // `impl AgentHook for ()` is the no-op hook: it must report interest in
        // *no* event kind, so the runner can skip building and dispatching even
        // the high-frequency delta events for it. The trait-default `observes`
        // returns `true`; `()` deliberately overrides it to `false`, so this is
        // the regression guard that the override stays in place.
        let all_kinds = [
            StepEventKind::CompletionCall,
            StepEventKind::CompletionResponse,
            StepEventKind::ModelTurnFinished,
            StepEventKind::InvalidToolCall,
            StepEventKind::ToolCall,
            StepEventKind::ToolResult,
            StepEventKind::TextDelta,
            StepEventKind::ToolCallDelta,
            StepEventKind::StreamResponseFinish,
        ];
        let unit_stack = HookStack::<M>::with(());
        for kind in all_kinds {
            assert!(
                !<() as AgentHook<M>>::observes(&(), kind),
                "the `()` no-op hook must not observe {kind:?}"
            );
            // A stack wrapping only `()` inherits that: it observes nothing, so
            // the runner skips delta dispatch for it too.
            assert!(
                !unit_stack.observes(kind),
                "a HookStack::with(()) must not observe {kind:?} either"
            );
        }
    }

    // --- RequestPatch merge unit tests ---

    #[test]
    fn merge_appends_extra_context_in_order() {
        let doc = |id: &str| crate::completion::Document {
            id: id.to_string(),
            text: String::new(),
            additional_props: Default::default(),
        };
        let a = RequestPatch::new().context(doc("a"));
        let b = RequestPatch::new().context(doc("b"));
        let merged = a.merge(b);
        let ids: Vec<&str> = merged.extra_context.iter().map(|d| d.id.as_str()).collect();
        assert_eq!(ids, vec!["a", "b"]);
    }

    #[test]
    fn merge_shallow_merges_additional_params_later_wins() {
        let a = RequestPatch::new().additional_params(serde_json::json!({"x": 1, "y": 2}));
        let b = RequestPatch::new().additional_params(serde_json::json!({"y": 3, "z": 4}));
        let merged = a.merge(b);
        assert_eq!(
            merged.additional_params,
            Some(serde_json::json!({"x": 1, "y": 3, "z": 4}))
        );
    }

    #[test]
    fn merge_scalar_last_writer_wins() {
        let a = RequestPatch::new().temperature(0.1);
        let b = RequestPatch::new().temperature(0.9);
        assert_eq!(a.merge(b).temperature, Some(0.9));
    }

    #[test]
    fn merge_active_tools_intersects() {
        let a = RequestPatch::new().active_tools(["search", "add", "sub"]);
        let b = RequestPatch::new().active_tools(["add", "sub", "mul"]);
        let merged = a.merge(b);
        assert_eq!(
            merged.active_tools,
            Some(vec!["add".to_string(), "sub".to_string()])
        );
    }

    #[test]
    fn merge_active_tools_empty_intersection_yields_empty() {
        let a = RequestPatch::new().active_tools(["search"]);
        let b = RequestPatch::new().active_tools(["add"]);
        let merged = a.merge(b);
        assert_eq!(merged.active_tools, Some(vec![]));
    }

    #[test]
    fn merge_one_sided_active_tools_keeps_the_present_list() {
        let a = RequestPatch::new().active_tools(["search"]);
        let b = RequestPatch::new();
        assert_eq!(a.merge(b).active_tools, Some(vec!["search".to_string()]));
    }

    // --- Scratchpad tests ---

    #[test]
    fn scratchpad_insert_get_update() {
        #[derive(Clone, Default, Debug, PartialEq)]
        struct Count(u32);

        let pad = Scratchpad::default();
        assert_eq!(pad.get::<Count>(), None);
        pad.update(|c: &mut Count| c.0 += 1);
        pad.update(|c: &mut Count| c.0 += 1);
        assert_eq!(pad.get::<Count>(), Some(Count(2)));
        assert!(pad.contains::<Count>());
        assert_eq!(pad.remove::<Count>(), Some(Count(2)));
        assert!(!pad.contains::<Count>());
    }

    #[test]
    fn scratchpad_is_shared_across_clones() {
        let pad = Scratchpad::default();
        let clone = pad.clone();
        pad.insert(7u32);
        // The clone shares the same underlying storage.
        assert_eq!(clone.get::<u32>(), Some(7));
    }

    #[test]
    fn hook_context_reports_identity_and_turn() {
        let ctx = HookContext::new(true, Some("agent".to_string()));
        assert!(ctx.is_streaming());
        assert_eq!(ctx.agent_name(), Some("agent"));
        assert_eq!(ctx.turn(), 0);
        ctx.set_turn(3);
        assert_eq!(ctx.turn(), 3);
        assert!(!ctx.run_id().as_str().is_empty());
    }

    /// Nested `HookStack` composition of the `ToolCall` chain: a rewrite inside an
    /// inner stack must survive a later short-circuit even though the inner stack
    /// is dispatched as a single hook. Regression coverage for the bug where
    /// `resolve_tool_call` consulted members via `on_event` (one `Flow`, so an
    /// inner rewrite was dropped behind an inner `Skip`/`Terminate`).
    mod nested_tool_call_resolution {
        use super::super::{AgentHook, Flow, HookContext, HookStack, StepEvent};
        use super::{M, ctx};
        use serde_json::{Value, json};

        /// Rewrites the tool args to a fixed value on `ToolCall`.
        struct RewriteHook(Value);
        impl AgentHook<M> for RewriteHook {
            async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
                if let StepEvent::ToolCall { .. } = event {
                    Flow::rewrite_args(self.0.clone())
                } else {
                    Flow::cont()
                }
            }
        }

        /// Skips on `ToolCall`.
        struct SkipHook;
        impl AgentHook<M> for SkipHook {
            async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
                if let StepEvent::ToolCall { .. } = event {
                    Flow::skip("denied")
                } else {
                    Flow::cont()
                }
            }
        }

        /// Terminates on `ToolCall`.
        struct TerminateHook;
        impl AgentHook<M> for TerminateHook {
            async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
                if let StepEvent::ToolCall { .. } = event {
                    Flow::terminate("stop")
                } else {
                    Flow::cont()
                }
            }
        }

        /// Returns `Flow::Fail` on `ToolCall` — not honored there, so it is
        /// fail-closed by `run_single_tool`; `resolve_tool_call` returns it verbatim.
        struct FailHook;
        impl AgentHook<M> for FailHook {
            async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
                if let StepEvent::ToolCall { .. } = event {
                    Flow::fail()
                } else {
                    Flow::cont()
                }
            }
        }

        /// Records the `args` each hook observes on `ToolCall`, to prove the
        /// rewritten args are threaded to hooks *after* the rewrite.
        #[derive(Clone, Default)]
        struct ArgsSpy(std::sync::Arc<std::sync::Mutex<Vec<String>>>);
        impl AgentHook<M> for ArgsSpy {
            async fn on_event(&self, _ctx: &HookContext, event: StepEvent<'_, M>) -> Flow {
                if let StepEvent::ToolCall { args, .. } = event {
                    self.0.lock().expect("spy").push(args.to_string());
                }
                Flow::cont()
            }
        }

        async fn resolve(stack: &HookStack<M>) -> (Flow, Option<Value>) {
            stack
                .resolve_tool_call(&ctx(), "add", Some("tc1"), "ic1", "{}")
                .await
        }

        #[tokio::test]
        async fn nested_rewrite_then_skip_preserves_rewrite() {
            // Inner stack: rewrite args, then skip. The rewrite must be salvaged.
            let mut inner = HookStack::<M>::new();
            inner.push(RewriteHook(json!({ "x": 41 })));
            inner.push(SkipHook);

            let mut outer = HookStack::<M>::new();
            outer.push(inner);

            let (flow, salvaged) = resolve(&outer).await;
            assert!(matches!(flow, Flow::Skip { .. }), "got {flow:?}");
            assert_eq!(
                salvaged,
                Some(json!({ "x": 41 })),
                "the inner rewrite must survive the inner skip through a nested stack"
            );
        }

        #[tokio::test]
        async fn nested_rewrite_then_terminate_preserves_rewrite() {
            let mut inner = HookStack::<M>::new();
            inner.push(RewriteHook(json!({ "x": 7 })));
            inner.push(TerminateHook);
            let mut outer = HookStack::<M>::new();
            outer.push(inner);

            let (flow, salvaged) = resolve(&outer).await;
            assert!(matches!(flow, Flow::Terminate { .. }), "got {flow:?}");
            assert_eq!(salvaged, Some(json!({ "x": 7 })));
        }

        #[tokio::test]
        async fn nested_rewrite_then_fail_closed_preserves_rewrite() {
            let mut inner = HookStack::<M>::new();
            inner.push(RewriteHook(json!({ "x": 9 })));
            inner.push(FailHook);
            let mut outer = HookStack::<M>::new();
            outer.push(inner);

            let (flow, salvaged) = resolve(&outer).await;
            // `Fail` is not honored for a tool call, but resolution returns it
            // verbatim (run_single_tool fail-closes it); the rewrite still survives.
            assert!(matches!(flow, Flow::Fail), "got {flow:?}");
            assert_eq!(salvaged, Some(json!({ "x": 9 })));
        }

        #[tokio::test]
        async fn outer_rewrite_then_nested_skip_preserves_outer_rewrite() {
            // Outer rewrite, then a nested stack that skips (without its own
            // rewrite). The outer rewrite must be salvaged, and the nested stack
            // must observe the outer-rewritten args.
            let spy = ArgsSpy::default();
            let mut inner = HookStack::<M>::new();
            inner.push(spy.clone());
            inner.push(SkipHook);

            let mut outer = HookStack::<M>::new();
            outer.push(RewriteHook(json!({ "x": 1, "y": 2 })));
            outer.push(inner);

            let (flow, salvaged) = resolve(&outer).await;
            assert!(matches!(flow, Flow::Skip { .. }), "got {flow:?}");
            assert_eq!(salvaged, Some(json!({ "x": 1, "y": 2 })));
            // The nested stack saw the outer-rewritten args, not the original `{}`.
            assert_eq!(
                spy.0.lock().expect("spy").as_slice(),
                [serde_json::to_string(&json!({ "x": 1, "y": 2 })).unwrap()],
            );
        }

        #[tokio::test]
        async fn deeply_nested_rewrite_then_skip_preserves_rewrite() {
            // Three levels: level3 rewrites+skips, wrapped twice.
            let mut level3 = HookStack::<M>::new();
            level3.push(RewriteHook(json!({ "deep": true })));
            level3.push(SkipHook);
            let mut level2 = HookStack::<M>::new();
            level2.push(level3);
            let mut level1 = HookStack::<M>::new();
            level1.push(level2);

            let (flow, salvaged) = resolve(&level1).await;
            assert!(matches!(flow, Flow::Skip { .. }), "got {flow:?}");
            assert_eq!(salvaged, Some(json!({ "deep": true })));
        }

        #[tokio::test]
        async fn nested_proceeding_rewrite_surfaces_as_rewrite_args() {
            // An inner stack that only rewrites (no short-circuit) surfaces the
            // rewrite through the flow itself, with no salvaged second element.
            let mut inner = HookStack::<M>::new();
            inner.push(RewriteHook(json!({ "x": 5 })));
            let mut outer = HookStack::<M>::new();
            outer.push(inner);

            let (flow, salvaged) = resolve(&outer).await;
            assert_eq!(
                flow,
                Flow::RewriteArgs {
                    args: json!({ "x": 5 })
                }
            );
            assert_eq!(salvaged, None);
        }
    }
}