rig-agent 0.43.0

Rig's classic agent runtime.
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
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
//! Shared agent drive loop, tool dispatch, and turn settlement. Unary and
//! streaming [`TurnSource`] implementations supply model responses; the engine
//! applies lifecycle policy and advances the sans-I/O [`AgentRun`].

use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};
use std::{collections::VecDeque, pin::Pin};

use futures::{Stream, StreamExt, stream};
use tracing::{Instrument, span::Id};

use crate::bus::{DispatchOptions, MemoryHandle};
use rig_core::error::ProviderError;
use rig_core::{
    completion::{FinishReason, ModelRef, ResponseIdentity},
    effect::{EffectId, EffectKind, Outcome},
    error::{ErrorKind, ErrorReport},
    message::{AssistantContent, Message, ToolCall, UserContent},
    telemetry::SpanCombinator,
    wasm_compat::WasmCompatSend,
};

use super::{
    ModelHandle,
    completion::{PreparedCompletionRequest, build_prepared_completion_request},
    hook::{
        AgentHook, CompletionCallAction, CompletionCallEvent, DispatchAction, DispatchEvent,
        HookContext, HookStack, InvalidToolCallAction, ModelSelection, ModelSelectionAction,
        ModelTurnAction, ModelTurnFinished, ObservationAction, OutcomeAction, OutcomeEvent,
        ReasoningDelta, RequestPatch, RunSettled, RunStart, RunStartAction, SettledOutcome,
        StepEventKind, TextDelta, ToolCallDelta,
    },
    run::{
        AgentRun, AgentRunStep, ModelTurn, ModelTurnOutcome, PendingToolCall,
        streamed::{StreamedResolution, StreamedTurnAssembler, StreamedTurnEvent},
    },
    run::{
        response::{MemoryAppend, PromptResponse},
        transcript::{assistant_text_from_choice, is_empty_assistant_turn, tool_result_output},
    },
    runner::AgentRunner,
    streaming::{MultiTurnStreamItem, StreamingError, finalize_streamed_choice},
    telemetry::{build_chat_span, new_execute_tool_span},
};
use crate::run::UnhandledInvalidToolCall;
use crate::{
    completion::{PromptError, Usage},
    json_utils,
    streaming::{Item, StreamEvent, StreamedUserContent},
    tool::{ToolCatalog, ToolResult},
};

/// A boxed, medium-specific item stream for one engine step (model turn or tool
/// batch). Boxed so a generic [`drive_agent`] can forward it without the
/// per-step future leaking into the engine's own (`Send`) inference.
// Browser streams may capture non-Send provider futures.
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) type DriveStream<'a> =
    Pin<Box<dyn Stream<Item = Result<MultiTurnStreamItem, StreamingError>> + Send + 'a>>;

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub(crate) type DriveStream<'a> =
    Pin<Box<dyn Stream<Item = Result<MultiTurnStreamItem, StreamingError>> + 'a>>;

/// Engine output: stream items for forwarding or a canonical terminal response.
pub(crate) enum DriveItem {
    /// Stream event, including the streaming surface's final response item.
    Item(MultiTurnStreamItem),
    /// The run finished; carries the canonical response the blocking fold
    /// returns. The streaming surface has already received the final item as the
    /// preceding `Item` and ignores this.
    Done(PromptResponse),
}

/// Medium-specific turn execution, telemetry, and final-item construction.
/// Implementations resolve invalid calls during model ingestion and feed accepted
/// turns or tool results back into the run.
pub(crate) trait TurnSource: WasmCompatSend {
    /// Build this medium's per-turn `chat` span (name + parenting + any
    /// `follows_from` chaining differ between blocking and streaming).
    fn open_chat_span(
        &self,
        runner: &AgentRunner,
        effective_preamble: Option<&str>,
    ) -> tracing::Span;

    /// Run one model turn: issue the provider call, feed the result into the
    /// sans-IO machine, and yield any intermediate items. Returning normally
    /// advances the loop; yielding an `Err` terminates the run.
    fn run_model_turn<'a>(
        &'a mut self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        prepared: PreparedCompletionRequest,
        chat_span: tracing::Span,
        agent_span: &'a tracing::Span,
        prompt: Message,
    ) -> DriveStream<'a>;

    /// Execute a turn's tool calls, feeding the results into the machine and
    /// yielding any intermediate items.
    fn run_tool_calls<'a>(
        &'a self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        calls: Vec<PendingToolCall>,
        tool_snapshot: Arc<ToolCatalog>,
    ) -> DriveStream<'a>;

    /// Record run-level telemetry onto the agent span at `Done`. Gated on
    /// `created_agent_span` so a caller-supplied outer span is never polluted.
    fn record_run_level_telemetry(
        &self,
        agent_span: &tracing::Span,
        response: &PromptResponse,
        created_agent_span: bool,
    );

    /// Build the final stream item surfaced at `Done`, or `None` when the
    /// surface discards it (the blocking fold) so the engine skips the work.
    fn final_item(&self, response: &PromptResponse) -> Option<MultiTurnStreamItem>;
}

/// Convert a [`StreamingError`] back into a [`PromptError`] for the blocking
/// surface ([`AgentRunner::run`]), which folds the shared engine. Lossless:
/// every streaming error originates as one of these.
pub(crate) fn streaming_error_into_prompt(err: StreamingError) -> PromptError {
    match err {
        StreamingError::Completion(err) => PromptError::CompletionError(err),
        StreamingError::Report(report) => PromptError::Report(report),
        StreamingError::Prompt(err) => err,
    }
}

pub(crate) fn store_error_usage(runner: &AgentRunner, run: &AgentRun) {
    if let Some(usage) = &runner.error_usage {
        *usage
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = run.usage();
    }
}

/// Drive run steps, hooks, request preparation, and memory append using `source`.
/// Yields stream items and a terminal response, or settles and yields an error.
/// Only engine-owned agent spans receive run-level telemetry.
pub(crate) fn drive_agent<S>(
    runner: AgentRunner,
    mut source: S,
    mut run: AgentRun,
    agent_span: tracing::Span,
    created_agent_span: bool,
    memory_handle: Option<(MemoryHandle, rig_core::id::ConversationId)>,
    hook_ctx: HookContext,
) -> impl Stream<Item = Result<DriveItem, StreamingError>>
where
    S: TurnSource,
{
    async_stream::stream! {
        // Hooks must see resumed entries from their first invocation.
        hook_ctx.seed_entries(run.entries());
        // Step-boundary flushing includes hook state in serialization; settlement
        // appends occur after the final flush and remain local.
        macro_rules! flush_entries {
            () => {
                for entry in hook_ctx.drain_pending_entries() {
                    run.append_entry(entry);
                }
            };
        }
        // Settle before yielding an error because consumers need not poll again.
        macro_rules! settle_error {
            ($err:expr) => {{
                if runner.config.hooks.observes(StepEventKind::RunSettled) {
                    let reason = $err.to_string();
                    runner
                        .config
                        .hooks
                        .on_run_settled(
                            &hook_ctx,
                            RunSettled {
                                outcome: SettledOutcome::Error(&reason),
                                messages: Some(run.messages()),
                            },
                        )
                        .await;
                }
            }};
        }
        // Set only after a model turn commits successfully and consumed by its
        // immediately following CallTools step. This keeps the sans-IO run state
        // serializable while pinning execution to the definitions sent that turn.
        let mut pending_tool_snapshot: Option<Arc<ToolCatalog>> = None;
        // Restore routing history so resumed hooks see the last issued model.
        let mut previous_model: Option<ModelRef> = run.previous_model().cloned();

        if runner.config.hooks.observes(StepEventKind::RunStart) {
            let action = match run.initial_prompt() {
                Some(prompt) => {
                    runner
                        .config
                        .hooks
                        .on_run_start(
                            &hook_ctx,
                            RunStart {
                                prompt,
                                history: run.input_chat_history(),
                            },
                        )
                        .await
                }
                // A run resumed past its first model call has no pending
                // initial prompt to steer.
                None => RunStartAction::Continue,
            };
            let early_stop = match action {
                RunStartAction::Continue => None,
                RunStartAction::Rewrite(prompt) => run
                    .rewrite_initial_prompt(prompt)
                    .err()
                    .map(StreamingError::Prompt),
                RunStartAction::Stop(reason) => {
                    Some(StreamingError::Prompt(run.cancel_error(reason)))
                }
            };
            if let Some(err) = early_stop {
                store_error_usage(&runner, &run);
                settle_error!(err);
                yield Err(err);
                return;
            }
        }

        // A macro keeps yield and loop termination in the caller's scope;
        // macro hygiene requires passing the loop label explicitly.
        macro_rules! drive_step {
            ($label:lifetime, $step_stream:expr) => {{
                let mut step_stream = $step_stream;
                let mut step_error = None;
                while let Some(item) = step_stream.next().await {
                    match item {
                        Ok(item) => yield Ok(DriveItem::Item(item)),
                        Err(err) => {
                            step_error = Some(err);
                            break;
                        }
                    }
                }
                drop(step_stream);
                if let Some(err) = step_error {
                    store_error_usage(&runner, &run);
                    settle_error!(err);
                    yield Err(err);
                    break $label;
                }
            }};
        }

        'outer: loop {
            flush_entries!();
            let step = match run.next_step() {
                Ok(step) => step,
                Err(err) => {
                    store_error_usage(&runner, &run);
                    let err: StreamingError = err.into();
                    settle_error!(err);
                    yield Err(err);
                    break 'outer;
                }
            };

            match step {
                AgentRunStep::CallModel { prompt, history, turn } => {
                    drop(pending_tool_snapshot.take());
                    if runner.config.max_turns > 1 {
                        tracing::info!("Current conversation Turns: {}/{}", turn, runner.config.max_turns);
                    }
                    hook_ctx.set_turn(turn);

                    // Selection must see merged request patches and must not run after a stop.
                    let request_patch =
                        match resolve_completion_call(&runner.config.hooks, &hook_ctx, &prompt, &history, turn).await {
                            CompletionCallOutcome::Terminate(reason) => {
                                store_error_usage(&runner, &run);
                                let err = StreamingError::Prompt(run.cancel_error(reason));
                                settle_error!(err);
                                yield Err(err);
                                break 'outer;
                            }
                            CompletionCallOutcome::Proceed(request_patch) => request_patch,
                        };

                    // Preparation and execution must use the same selected model's capabilities.
                    let default_label = runner.config.model_label();
                    let selected_label = match runner.config.hooks.on_model_select(
                        &hook_ctx,
                        ModelSelection {
                            prompt: &prompt,
                            history: &history,
                            request_patch: request_patch.as_ref(),
                            previous_model: previous_model.as_ref(),
                            default_model: &default_label,
                            selected_model: &default_label,
                        },
                    ) {
                        ModelSelectionAction::Continue => default_label.clone(),
                        ModelSelectionAction::Select(model) => model,
                        ModelSelectionAction::Stop(reason) => {
                            store_error_usage(&runner, &run);
                            let err = StreamingError::Prompt(run.cancel_error(reason));
                            settle_error!(err);
                            yield Err(err);
                            break 'outer;
                        }
                    };
                    // Bind the typed view now: an unregistered label is a
                    // wiring error, surfaced before any request is built.
                    let selected_model = if selected_label == default_label {
                        runner.config.model_handle()
                    } else {
                        runner.config.model_by_ref(&selected_label)
                    };
                    let selected_model: ModelHandle = match selected_model {
                        Ok(model) => model,
                        Err(report) => {
                            store_error_usage(&runner, &run);
                            let err = StreamingError::Report(report);
                            settle_error!(err);
                            yield Err(err);
                            break 'outer;
                        }
                    };

                    // Telemetry uses the effective preamble before output-mode augmentation.
                    let effective_preamble = request_patch
                        .as_ref()
                        .and_then(|o| o.preamble.as_deref())
                        .or(runner.config.preamble.as_deref());

                    let chat_span = source.open_chat_span(&runner, effective_preamble);

                    // Pin output mode across registry changes between turns.
                    let committed_output_tool = run.output_tool_name().map(str::to_owned);
                    let mut prepared = match build_prepared_completion_request(
                        &runner,
                        &hook_ctx,
                        &selected_model,
                        prompt.clone(),
                        &history,
                        committed_output_tool.as_deref(),
                        request_patch.as_ref(),
                    )
                    .await
                    {
                        Ok(prepared) => prepared,
                        Err(err) => {
                            store_error_usage(&runner, &run);
                            let err: StreamingError = err.into();
                            settle_error!(err);
                            yield Err(err);
                            break 'outer;
                        }
                    };
                    if let Some(name) = &prepared.output_tool_name {
                        // Refused after the first turn by design: the name is pinned.
                        let _ = run.commit_output_tool_name(name.clone());
                    }
                    let turn_tool_snapshot = prepared.tool_snapshot.clone();
                    // What this request advertises becomes run data, so a
                    // resumed run or another driver can re-pair the calls
                    // that come back with the tools that were offered.
                    run.advertise_tools(turn, std::mem::take(&mut prepared.advertised_tools));
                    if runner.config.record_telemetry_content {
                        let input_messages = std::mem::take(&mut prepared.telemetry_messages);
                        rig_core::telemetry::record_model_input(&chat_span, &input_messages, true);
                    }

                    // Only issued attempts advance routing history, including provider errors.
                    run.set_previous_model(selected_label.clone());
                    previous_model = Some(selected_label);

                    drive_step!('outer, source.run_model_turn(
                        &runner,
                        &hook_ctx,
                        &mut run,
                        prepared,
                        chat_span,
                        &agent_span,
                        prompt,
                    ));
                    pending_tool_snapshot = Some(turn_tool_snapshot);
                }
                AgentRunStep::CallTools { calls } => {
                    // Resume cannot restore registration leases; bind advertised names
                    // to this process's current implementations.
                    if pending_tool_snapshot.is_none()
                        && let Some(advertised) = run.advertised_tools()
                    {
                        let names: Vec<String> = advertised
                            .definitions
                            .iter()
                            .map(|definition| definition.name.clone())
                            .collect();
                        pending_tool_snapshot = Some(Arc::new(
                            runner.tool_server_handle.snapshot_with_dynamic(&names),
                        ));
                    }
                    let Some(tool_snapshot) = pending_tool_snapshot.take() else {
                        store_error_usage(&runner, &run);
                        let err = StreamingError::Completion(ProviderError::Response(
                            "agent requested tool execution without a prepared registry snapshot"
                                .to_string(),
                        ));
                        settle_error!(err);
                        yield Err(err);
                        break 'outer;
                    };
                    drive_step!('outer, source.run_tool_calls(
                        &runner,
                        &hook_ctx,
                        &mut run,
                        calls,
                        tool_snapshot,
                    ));
                }
                AgentRunStep::Done(response) => {
                    flush_entries!();
                    tracing::info!(
                        turn = run.turn(),
                        max_turns = runner.config.max_turns,
                        "Agent run finished"
                    );
                    source.record_run_level_telemetry(&agent_span, &response, created_agent_span);
                    // Append failure does not discard the answer; expose acknowledgement
                    // separately without assuming a failed append wrote nothing.
                    let memory_append = append_run_messages(
                        &runner,
                        &hook_ctx,
                        memory_handle.as_ref(),
                        response.messages.as_deref().unwrap_or_default(),
                    )
                    .await;
                    let response = response.with_memory_append(memory_append);
                    if runner.config.hooks.observes(StepEventKind::RunSettled) {
                        runner
                            .config
                            .hooks
                            .on_run_settled(
                                &hook_ctx,
                                RunSettled {
                                    outcome: SettledOutcome::Response(&response),
                                    messages: Some(run.messages()),
                                },
                            )
                            .await;
                    }
                    // Build the final item only when the surface forwards it
                    // (streaming). The blocking fold discards it, so its source
                    // returns `None` and the extra full-response clone is skipped.
                    if let Some(final_item) = source.final_item(&response) {
                        yield Ok(DriveItem::Item(final_item));
                    }
                    yield Ok(DriveItem::Done(response));
                    break 'outer;
                }
            }
        }

    }
}

/// Execute a turn's tool calls **atomically per batch**, shared by both surfaces.
///
/// The batch commits and surfaces all-or-nothing:
///
/// - The model tool-call events ([`MultiTurnStreamItem::ToolCall`]) are
///   emitted up front, reporting what the model emitted at turn commit.
/// - Every tool then runs (sequentially at `tool_concurrency <= 1`, else
///   concurrently bounded by it), with outcomes **collected, not surfaced**.
/// - On the first hook termination / fail-closed error the batch fails fast: no
///   new tool starts, not-yet-started concurrent siblings are dropped,
///   already-started ones are drained, and the deterministic lowest call-index
///   error is surfaced with **no** successful [`ToolExecutionCommitted`] /
///   [`StreamUserItem`](MultiTurnStreamItem::StreamUserItem) items and **no**
///   history commit.
/// - Only if the whole batch settles successfully are the per-tool
///   [`ToolExecutionCommitted`](MultiTurnStreamItem::ToolExecutionCommitted) + result
///   items surfaced (in call order, only for tools whose body actually ran) and
///   the results committed to run history.
///
/// When `forward_items` is `false` (the blocking fold) no stream items are built,
/// but the collect/commit and fail-fast behavior is identical, so `run()` and
/// `stream()` return the same terminal reason. `chain_tool_span` lets the
/// blocking surface chain spans into its linear `follows_from` sequence.
pub(crate) fn drive_tool_calls<'a, F>(
    runner: &'a AgentRunner,
    hook_ctx: &'a HookContext,
    run: &'a mut AgentRun,
    calls: Vec<PendingToolCall>,
    tool_snapshot: Arc<ToolCatalog>,
    chain_tool_span: F,
    forward_items: bool,
) -> DriveStream<'a>
where
    F: Fn(tracing::Span) -> tracing::Span + WasmCompatSend + 'a,
{
    // Per-call working state: the execute span, paired with the model's
    // tool call. `span` is `Span::none()` for a
    // preresolved (invalid-recovery) call, which never executes.
    struct PreparedToolCall {
        tool_call: rig_core::message::ToolCall,
        preresolved_result: Option<UserContent>,
        span: tracing::Span,
    }
    // How a settled tool call is surfaced on the stream once the batch succeeds:
    //   - `Executed`: `ToolExecutionCommitted` (with the effective, hook-rewritten
    //     call) + the `ToolResult`.
    //   - `Skipped`: the `ToolResult` only (a `ToolCall` hook returned `Skip`, so
    //     nothing ran and no execution commit is surfaced, but the model still
    //     sees the result).
    //   - `Preresolved`: neither (an invalid-recovery result, already surfaced
    //     during the model turn); committed to history only.
    enum ToolSurface {
        Executed(rig_core::message::ToolCall),
        Skipped,
        Preresolved,
    }
    // A collected tool outcome, held (not surfaced or committed) until the whole
    // batch settles.
    struct CollectedToolResult {
        content: UserContent,
        surface: ToolSurface,
    }

    Box::pin(async_stream::stream! {
        let full_history_for_errors = run.full_history();
        let call_count = calls.len();

        // Assign each call that will actually execute an execute span. Emit the MODEL tool-call events now,
        // right after the turn committed: these report what the model emitted and
        // are *not* execution-lifecycle events. A preresolved call emits no model
        // tool-call event (its synthetic result was already surfaced during the
        // model turn) and gets no execute span.
        let mut prepared: Vec<PreparedToolCall> = Vec::with_capacity(call_count);
        for pending in calls {
            let (span, preresolved_result) = match pending.preresolved_result {
                Some(result) => (tracing::Span::none(), Some(result)),
                None => {
                    if forward_items {
                        yield Ok(MultiTurnStreamItem::ToolCall {
                            tool_call: pending.tool_call.clone(),
                        });
                    }
                    (chain_tool_span(new_execute_tool_span()), None)
                }
            };
            prepared.push(PreparedToolCall {
                tool_call: pending.tool_call,
                preresolved_result,
                span,
            });
        }

        // Outcomes are collected in call order and nothing is surfaced or
        // committed until the whole batch settles. After the first termination or
        // fail-closed error no new tool starts, started ones are drained, and the
        // lowest call-index error wins.
        let mut collected: Vec<Option<CollectedToolResult>> =
            (0..call_count).map(|_| None).collect();
        let mut first_error: Option<(usize, PromptError)> = None;

        {
            // Bounded by `tool_concurrency` (`0`/`1` poll strictly in call
            // order, giving sequential fail-fast). A shared `terminating`
            // flag makes a not-yet-started sibling skip (its side effect never
            // runs) once any sibling terminates, while in-flight siblings are
            // drained so the lowest call-index terminator wins and no task is left
            // detached.
            let terminating = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let unordered = stream::iter(prepared.into_iter().enumerate())
                .map(|(index, call)| {
                    let PreparedToolCall { tool_call, preresolved_result, span } = call;
                    let tool_snapshot = &tool_snapshot;
                    let full_history_for_errors = &full_history_for_errors;
                    let terminating = terminating.clone();
                    async move {
                        if let Some(result) = preresolved_result {
                            return (
                                index,
                                Some(Ok(CollectedToolResult {
                                    content: result,
                                    surface: ToolSurface::Preresolved,
                                })),
                            );
                        }
                        // `None` marks a dropped (never-started) sibling.
                        if terminating.load(std::sync::atomic::Ordering::SeqCst) {
                            return (index, None);
                        }
                        let outcome = run_single_tool(
                            runner,
                            hook_ctx,
                            tool_snapshot,
                            &tool_call,
                            full_history_for_errors,
                        )
                        .await;
                        let mapped = outcome.map(|o| {
                            let surface = match o.execution {
                                ToolExecution::Executed(effective) => {
                                    ToolSurface::Executed(effective)
                                }
                                ToolExecution::Skipped => ToolSurface::Skipped,
                            };
                            CollectedToolResult {
                                content: o.content,
                                surface,
                            }
                        });
                        (index, Some(mapped))
                    }
                    .instrument(span)
                })
                .buffer_unordered(runner.concurrency.max(1));
            futures::pin_mut!(unordered);

            while let Some((index, outcome)) = unordered.next().await {
                // A dropped sibling records nothing.
                let Some(result) = outcome else { continue };
                match result {
                    Ok(collected_result) => {
                        if let Some(slot) = collected.get_mut(index) {
                            *slot = Some(collected_result);
                        }
                    }
                    Err(err) => {
                        // Fail-fast: stop starting new siblings; keep draining
                        // in-flight ones so the lowest call-index terminator wins.
                        terminating.store(true, std::sync::atomic::Ordering::SeqCst);
                        if first_error.as_ref().is_none_or(|(i, _)| index < *i) {
                            first_error = Some((index, err));
                        }
                    }
                }
            }
        }

        // On termination surface only the deterministic error: no execution
        // commit, no result, and no history commit.
        if let Some((_, err)) = first_error {
            yield Err(StreamingError::Prompt(err));
            return;
        }

        // Success: prepare each call's stream items and results in call order,
        // commit the results, then surface the buffered items. An executed call
        // surfaces `ToolExecutionCommitted`
        // (with the effective, hook-rewritten call) then its `ToolResult`; a
        // hook-skipped call surfaces its `ToolResult` only (nothing ran); a
        // preresolved call surfaces nothing (already surfaced during the model
        // turn) but is still committed. Every non-dropped slot is filled; a
        // dropped slot only occurs after a termination, handled above.
        let mut committed: Vec<UserContent> = Vec::with_capacity(call_count);
        let mut surface_items: Vec<MultiTurnStreamItem> =
            Vec::with_capacity(call_count.saturating_mul(2));
        for slot in collected {
            let Some(CollectedToolResult { content, surface }) = slot else {
                yield Err(StreamingError::Prompt(PromptError::CompletionError(
                    ProviderError::Response(
                        "tool execution finished without producing every result".to_string(),
                    ),
                )));
                return;
            };
            if forward_items {
                // An executed call also surfaces its execution commit; a skipped
                // call surfaces only its result; a preresolved call surfaces
                // nothing here.
                let surface_result = match surface {
                    ToolSurface::Executed(tool_call) => {
                        surface_items.push(MultiTurnStreamItem::ToolExecutionCommitted {
                            tool_call,
                        });
                        true
                    }
                    ToolSurface::Skipped => true,
                    ToolSurface::Preresolved => false,
                };
                if surface_result
                    && let UserContent::ToolResult(tool_result) = &content
                {
                    surface_items.push(MultiTurnStreamItem::StreamUserItem(
                        StreamedUserContent::ToolResult {
                            tool_result: tool_result.clone(),
                        },
                    ));
                }
            }
            committed.push(content);
        }

        if let Err(err) = run.tool_results(committed) {
            yield Err(err.into());
            return;
        }

        for item in surface_items {
            yield Ok(item);
        }
    })
}

/// [`TurnSource`] for the streaming surface: each turn opens a provider stream,
/// drives a [`StreamedTurnAssembler`], and yields assistant/tool deltas.
pub(crate) struct StreamingTurnSource {
    /// The raw provider choice of the most recent turn; the final response
    /// surfaces it as-is, even when canonical reordering was recorded in history.
    last_final_choice: Vec<AssistantContent>,
    last_message_id: Option<String>,
    /// Resolved agent name, kept only for the empty-turn diagnostic warning.
    agent_name: String,
    /// Whether we created the agent span (vs. adopting a caller's ambient span);
    /// gates recording `gen_ai.completion` onto it, matching the blocking source
    /// so neither surface pollutes a caller-supplied span.
    created_agent_span: bool,
    /// Whether sensitive run-level prompt and completion content may be recorded.
    record_telemetry_content: bool,
    /// Hot-path interest gates, computed once: skip building/dispatching the
    /// high-frequency delta events when no hook observes them.
    observes_text_delta: bool,
    observes_reasoning_delta: bool,
    observes_tool_call_delta: bool,
    /// Whether any hook is present. Gates building the history-cloning
    /// invalid-tool diagnostic context.
    has_hooks: bool,
}

impl StreamingTurnSource {
    pub(crate) fn new(
        hooks: &HookStack,
        agent_name: String,
        created_agent_span: bool,
        record_telemetry_content: bool,
    ) -> Self {
        Self {
            // Nothing has streamed yet, so the last final choice is nothing.
            last_final_choice: Vec::new(),
            last_message_id: None,
            agent_name,
            created_agent_span,
            record_telemetry_content,
            observes_text_delta: hooks.observes(StepEventKind::TextDelta),
            observes_reasoning_delta: hooks.observes(StepEventKind::ReasoningDelta),
            observes_tool_call_delta: hooks.observes(StepEventKind::ToolCallDelta),
            has_hooks: !hooks.is_empty(),
        }
    }

    /// Record a completed model turn's canonical output onto the agent and
    /// chat spans. Only self-created agent spans receive `gen_ai.completion`,
    /// so neither surface pollutes a caller-supplied span.
    fn record_turn_telemetry(
        &self,
        agent_span: &tracing::Span,
        chat_span: &tracing::Span,
        choice: &[AssistantContent],
        record_content: bool,
    ) {
        if self.created_agent_span && self.record_telemetry_content {
            agent_span.record("gen_ai.completion", assistant_text_from_choice(choice));
        }
        rig_core::telemetry::record_model_output(chat_span, choice, record_content);
    }
}

impl TurnSource for StreamingTurnSource {
    fn open_chat_span(
        &self,
        runner: &AgentRunner,
        effective_preamble: Option<&str>,
    ) -> tracing::Span {
        build_chat_span!(runner, effective_preamble, "chat_streaming", "chat")
    }

    fn run_model_turn<'a>(
        &'a mut self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        prepared: PreparedCompletionRequest,
        chat_span: tracing::Span,
        agent_span: &'a tracing::Span,
        _current_prompt: Message,
    ) -> DriveStream<'a> {
        Box::pin(async_stream::stream! {
            // Bound before the builder is consumed: the cap this attempt was
            // prepared with, completion-call patches included.
            let attempt_max_tokens = prepared.max_tokens;

            let request = prepared.request;
            let model = prepared.model;
            let (dispatch_id, dispatched_kind, mut stream) = match dispatch_completion(runner, hook_ctx, &model, request, true)
                .instrument(chat_span.clone())
                .await
            {
                Ok(CompletionDispatch::Stream { id, kind, stream }) => (id, kind, stream),
                Ok(CompletionDispatch::Response { .. }) => {
                    yield Err(StreamingError::Report(
                        ErrorReport::new(
                            ErrorKind::Internal,
                            "a streaming completion dispatch answered unary",
                        ),
                    ));
                    return;
                }
                Err(CompletionDispatchError::Cancelled(reason)) => {
                    yield Err(StreamingError::Prompt(run.cancel_error(reason)));
                    return;
                }
                Err(CompletionDispatchError::Failed(report)) => {
                    yield Err(StreamingError::Report(report));
                    return;
                }
            };
            let mut assembler = StreamedTurnAssembler::new(
                prepared.executable_tool_names.clone(),
                prepared.allowed_tool_names.clone(),
            );
            // A turn whose invalid tool call was repaired is a recovered turn:
            // neither the response hook nor `ModelTurnFinished` fires for it.
            let mut turn_recovered = false;
            // A tool call's start and arguments, held until its end validates
            // the call.
            let mut held: Vec<StreamEvent> = Vec::new();

            'turn: while let Some(item) = stream.next().await {
                // A stream error ends the reply. Unparsable tool-call input
                // still takes the same recovery seam as an unknown tool name.
                // At most one event per item forwards the item itself, so moving
                // it out of the slot avoids cloning every streamed fragment.
                let (mut item_slot, mut events, ended): (
                    Option<Item<StreamEvent>>,
                    VecDeque<StreamedTurnEvent>,
                    bool,
                ) = match item {
                    Ok(item) => match assembler.ingest(&item) {
                        Ok(events) => (Some(item), events.into(), false),
                        Err(err) => {
                            yield Err(err.into());
                            return;
                        }
                    },
                    Err(err) => match ErrorReport::from(&err).detail {
                        Some(rig_core::error::ErrorDetail::MalformedToolInput(detail)) => {
                            (None, assembler.surface_malformed_input(&detail).into(), true)
                        }
                        _ => {
                            yield Err(err.into());
                            return;
                        }
                    },
                };
                while let Some(event) = events.pop_front() {
                    match event {
                        StreamedTurnEvent::EmitIngested => {
                            if self.observes_text_delta
                                && let Some(Item::Event(StreamEvent::Text { text, .. })) =
                                    item_slot.as_ref()
                                && let Some(reason) = observe_action(
                                    runner
                                        .config.hooks
                                        .on_text_delta(
                                            hook_ctx,
                                            TextDelta {
                                                delta: text,
                                                aggregated: assembler.aggregated_text(),
                                            },
                                        )
                                        .await,
                                )
                            {
                                // The stop is the run's: the dispatch in flight is
                                // cancelled here, before the error surfaces, so the
                                // record is the same cancel on every transport.
                                drop(stream);
                                yield Err(StreamingError::Prompt(
                                    run.cancel_error(reason),
                                ));
                                return;
                            }
                            if self.observes_reasoning_delta
                                && let Some(Item::Event(StreamEvent::Reasoning {
                                    part,
                                    text: reasoning,
                                })) = item_slot.as_ref()
                                && let Some(reason) = observe_action(
                                    runner
                                        .config.hooks
                                        .on_reasoning_delta(
                                            hook_ctx,
                                            ReasoningDelta {
                                                part: *part,
                                                delta: reasoning,
                                                aggregated: assembler
                                                    .aggregated_reasoning(part.index())
                                                    .unwrap_or_default(),
                                            },
                                        )
                                        .await,
                                )
                            {
                                // The stop is the run's: the dispatch in flight is
                                // cancelled here, before the error surfaces, so the
                                // record is the same cancel on every transport.
                                drop(stream);
                                yield Err(StreamingError::Prompt(
                                    run.cancel_error(reason),
                                ));
                                return;
                            }
                            if let Some(item) = item_slot.take() {
                                yield Ok(MultiTurnStreamItem::stream_item(item));
                            }
                        }
                        StreamedTurnEvent::HoldToolCall => {
                            if let Some(Item::Event(event)) = item_slot.take() {
                                held.push(event);
                            }
                        }
                        StreamedTurnEvent::EmitToolCall { call } => {
                            // The call's end is the ingested item; a repaired
                            // call's end carries the repaired name.
                            let end = match item_slot.take() {
                                Some(Item::Event(StreamEvent::End { part, .. })) => Some(part),
                                _ => None,
                            };
                            for event in std::mem::take(&mut held) {
                                if self.observes_tool_call_delta
                                    && let StreamEvent::Arguments { part, json } = &event
                                    && let Some(reason) = observe_action(
                                        runner
                                            .config.hooks
                                            .on_tool_call_delta(
                                                hook_ctx,
                                                ToolCallDelta {
                                                    part: *part,
                                                    call_id: &call.id,
                                                    tool_name: call.function.name.as_str(),
                                                    delta: json,
                                                },
                                            )
                                            .await,
                                    )
                                {
                                    // The stop is the run's: the dispatch in flight is
                                    // cancelled here, before the error surfaces, so the
                                    // record is the same cancel on every transport.
                                    drop(stream);
                                    yield Err(StreamingError::Prompt(
                                        run.cancel_error(reason),
                                    ));
                                    return;
                                }
                                yield Ok(MultiTurnStreamItem::stream_item(Item::Event(event)));
                            }
                            if let Some(part) = end {
                                yield Ok(MultiTurnStreamItem::stream_item(Item::Event(
                                    StreamEvent::End {
                                        part,
                                        content: AssistantContent::ToolCall(call),
                                    },
                                )));
                            }
                        }
                        StreamedTurnEvent::InvalidToolCall(invalid) => {
                            // The rejected call's items are not forwarded.
                            held.clear();
                            let partial = assembler.partial_turn(
                                stream.message_id(),
                                &stream.partial().choice,
                            );
                            eprintln!("PARTIAL {:?}", stream.partial().choice);
                            // Gated on `has_hooks`: building the diagnostic context
                            // clones the chat history, so an empty stack skips it and
                            // fails fast.
                            let hook_action = if self.has_hooks {
                                let context =
                                    run.streamed_invalid_tool_call_context(&partial, &invalid);
                                runner
                                    .config.hooks
                                    .on_invalid_tool_call(hook_ctx, &context)
                                    .await
                            } else {
                                None
                            };
                            // No hook resolved it: the runner's policy, as the
                            // unary surface applies it (`Ignore` drops the call
                            // and goes on; `Fail` fails the run).
                            let resolved = match hook_action {
                                Some(action) => {
                                    run.resolve_streamed_invalid_tool_call(&partial, &invalid, action)
                                }
                                None => match runner.unhandled_invalid_tool_call {
                                    UnhandledInvalidToolCall::Fail => run
                                        .resolve_streamed_invalid_tool_call(
                                            &partial,
                                            &invalid,
                                            InvalidToolCallAction::fail(),
                                        ),
                                    UnhandledInvalidToolCall::Ignore => {
                                        run.ignore_streamed_invalid_tool_call()
                                    }
                                },
                            };
                            let resolution = match resolved {
                                Ok(resolution) => resolution,
                                Err(err) => {
                                    yield Err(err.into());
                                    return;
                                }
                            };

                            match resolution {
                                StreamedResolution::Ignored => {
                                    assembler.resolve_pending_invalid(&resolution);
                                    item_slot = None;
                                }
                                StreamedResolution::Repaired { .. } => {
                                    // The repaired call flows through the same event
                                    // handling above; the turn is now recovered.
                                    turn_recovered = true;
                                    events.extend(assembler.resolve_pending_invalid(&resolution));
                                }
                                StreamedResolution::TurnAbandoned {
                                    ref skipped_tool_result,
                                } => {
                                    let skipped_tool_result = skipped_tool_result.clone();
                                    assembler.resolve_pending_invalid(&resolution);
                                    // The abandoned reply still reports its usage
                                    // when it ends; one that already ended with the
                                    // rejected call's error has none to record.
                                    if !ended {
                                        let response = match stream.finish().await {
                                            Ok(response) => response,
                                            Err(err) => {
                                                yield Err(err.into());
                                                return;
                                            }
                                        };
                                        chat_span.record_token_usage(&response.usage);
                                        match run.record_streamed_completion_call(
                                            response.usage,
                                            response.identity(),
                                            response.finish_reason(),
                                            response.raw.clone(),
                                        ) {
                                            Ok(call) => {
                                                yield Ok(MultiTurnStreamItem::CompletionCall(call));
                                            }
                                            Err(err) => {
                                                yield Err(err.into());
                                                return;
                                            }
                                        }
                                    }
                                    if let Some(tool_result) = skipped_tool_result {
                                        yield Ok(MultiTurnStreamItem::StreamUserItem(
                                            StreamedUserContent::ToolResult { tool_result },
                                        ));
                                    }
                                    return;
                                }
                            }
                        }
                    }
                }
                if ended {
                    break 'turn;
                }
            }

            // The reply's end: the response `call` would have returned for it.
            // A reply the provider did not end is truncated, and never a
            // successful zero-usage completion.
            let response = match stream.finish().await {
                Ok(response) => response,
                Err(err) => {
                    yield Err(err.into());
                    return;
                }
            };
            chat_span.record_token_usage(&response.usage);
            match run.record_streamed_completion_call(
                response.usage,
                response.identity(),
                response.finish_reason(),
                response.raw.clone(),
            ) {
                Ok(call) => yield Ok(MultiTurnStreamItem::CompletionCall(call)),
                Err(err) => {
                    yield Err(err.into());
                    return;
                }
            }

            let mut final_turn_content = response.choice.clone();
            let streamed_turn = assembler.finish(response.message_id.clone(), &response);
            let identity = response.identity();
            self.last_message_id.clone_from(&streamed_turn.message_id);
            // The hooks and run history see the assembled turn: the
            // response's choice without ignored calls, with repaired names.
            let canonical_choice = streamed_turn.choice.clone();
            // `streamed_turn` is moved into run state on the next line and the
            // hooks fire after that. `FinishReason::Other` carries a `String`,
            // so this is a clone rather than a copy.
            let attempt_finish_reason = streamed_turn.finish_reason.clone();
            if let Err(err) = run.streamed_turn(streamed_turn) {
                yield Err(err.into());
                return;
            }
            if !turn_recovered {
                let settlement = settle_model_turn(
                    &runner.config.hooks,
                    hook_ctx,
                    run,
                    AssembledTurn {
                        dispatch_id,
                        dispatch_kind: &dispatched_kind,
                        provider: &response.provider,
                        content: &canonical_choice,
                        usage: response.usage,
                        identity: &identity,
                        finish_reason: attempt_finish_reason.as_ref(),
                        max_tokens: attempt_max_tokens,
                        raw: &response.raw,
                    },
                )
                .await;
                match settlement {
                    Ok(ModelTurnDecision::Advance { replaced }) => {
                        // The run keeps the replacement, and so does the final
                        // item the consumer receives: the fragments it saw were
                        // the provider's, the answer is the hook's.
                        if let Some(choice) = replaced {
                            final_turn_content = choice;
                        }
                    }
                    Ok(ModelTurnDecision::Retried) => {
                        yield Ok(MultiTurnStreamItem::ModelTurnRetried {
                            turn: hook_ctx.turn(),
                        });
                        return;
                    }
                    Ok(ModelTurnDecision::Terminate(reason)) => {
                        // A stop observes an already completed provider turn:
                        // its content telemetry stays visible before the
                        // cancellation.
                        self.record_turn_telemetry(
                            agent_span,
                            &chat_span,
                            &canonical_choice,
                            runner.config.record_telemetry_content,
                        );
                        yield Err(StreamingError::Prompt(run.cancel_error(reason)));
                        return;
                    }
                    Err(err) => {
                        yield Err(StreamingError::Prompt(err));
                        return;
                    }
                }
            }

            // Only hook-accepted canonical output belongs in content telemetry.
            self.record_turn_telemetry(
                agent_span,
                &chat_span,
                &canonical_choice,
                runner.config.record_telemetry_content,
            );

            self.last_final_choice = final_turn_content;
        })
    }

    fn run_tool_calls<'a>(
        &'a self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        calls: Vec<PendingToolCall>,
        tool_snapshot: Arc<ToolCatalog>,
    ) -> DriveStream<'a> {
        // The streaming surface chains nothing onto its tool spans, and forwards
        // the ToolCall/ToolResult items to the consumer.
        drive_tool_calls(
            runner,
            hook_ctx,
            run,
            calls,
            tool_snapshot,
            |span| span,
            true,
        )
    }

    fn record_run_level_telemetry(
        &self,
        agent_span: &tracing::Span,
        response: &PromptResponse,
        created_agent_span: bool,
    ) {
        if created_agent_span {
            agent_span.record_token_usage(&response.usage);
        }
    }

    fn final_item(&self, response: &PromptResponse) -> Option<MultiTurnStreamItem> {
        // In tool output mode, when the finishing turn made the output-tool call,
        // surface the run's structured output as the final content.
        let final_choice = finalize_streamed_choice(&self.last_final_choice, &response.output)
            .unwrap_or_else(|| {
                if is_empty_assistant_turn(&self.last_final_choice) {
                    tracing::warn!(
                        agent_name = self.agent_name.as_str(),
                        message_id = ?self.last_message_id,
                        "Streaming turn completed without assistant text; final response will be empty"
                    );
                }
                self.last_final_choice.clone()
            });
        // Always surface the accumulated messages, regardless of whether the
        // caller supplied input history.
        let final_messages: Option<Vec<Message>> =
            Some(response.messages.clone().unwrap_or_default());
        Some(
            MultiTurnStreamItem::final_response_with_completion_calls(
                final_choice,
                response.usage,
                response.completion_calls.clone(),
                final_messages,
            )
            .with_memory_append(response.memory_append.clone()),
        )
    }
}

/// Convert an observe-only action into an optional stop reason.
pub(crate) fn observe_action(action: ObservationAction) -> Option<String> {
    match action {
        ObservationAction::Continue => None,
        ObservationAction::Stop(reason) => Some(reason),
    }
}

/// Resolved outcome of the shared, medium-neutral model-turn hook.
pub(crate) enum ModelTurnDecision {
    /// Accept the turn and advance normally. Carries the content a hook
    /// replaced the turn with, when one did. The streaming surface's final item
    /// follows it.
    Advance {
        replaced: Option<Vec<AssistantContent>>,
    },
    /// The turn was rejected and the run is ready to issue another model call.
    Retried,
    /// Stop the run with the supplied reason.
    Terminate(String),
}

/// One attempt's assembled response, as both drivers hand it to
/// [`settle_model_turn`]: the unary response under `run()`, the finished
/// stream under `stream()`. Every field belongs to this attempt, and a retry
/// re-enters with a fresh response, so a stale attempt's ids or payload can
/// never be attributed here.
pub(crate) struct AssembledTurn<'a> {
    /// The completion dispatch this attempt answers: the outcome hook's
    /// correlation id and the effect that was dispatched.
    pub(crate) dispatch_id: EffectId,
    pub(crate) dispatch_kind: &'a EffectKind,
    /// The provider that answered, as the response names it.
    pub(crate) provider: &'a str,
    pub(crate) content: &'a Vec<AssistantContent>,
    pub(crate) usage: Usage,
    pub(crate) identity: &'a ResponseIdentity,
    pub(crate) finish_reason: Option<&'a FinishReason>,
    /// The cap this attempt was prepared with, completion-call patches
    /// included; read off the prepared request, never the agent config.
    pub(crate) max_tokens: Option<u64>,
    pub(crate) raw: &'a serde_json::Value,
}

/// Settle a parked model turn: fire [`AgentHook::on_outcome`] for the
/// completion dispatch (a replacement lands on the parked turn, a
/// `Cancelled` replacement terminates), then
/// [`AgentHook::on_model_turn_finished`] and apply its action to the sans-IO
/// run. The outcome hook fires here rather than at the dispatch so that both
/// media fire it in one slot, after the run validated the answer's tool calls
/// (a recovered turn fires neither hook, on either medium) and while the turn
/// can still be replaced. Both drivers call this once per accepted attempt, so retry history,
/// tool-turn rejection, and state transitions cannot diverge by medium. The
/// callers own what happens next: the blocking driver records the accepted
/// turn's telemetry; the streaming driver additionally surfaces or discards
/// the buffered provisional `Final`.
pub(crate) async fn settle_model_turn(
    hooks: &HookStack,
    hook_ctx: &HookContext,
    run: &mut AgentRun,
    turn: AssembledTurn<'_>,
) -> Result<ModelTurnDecision, PromptError> {
    let mut folded = rig_core::completion::CompletionResponse::new(
        turn.content.clone(),
        turn.usage,
        turn.provider,
        turn.raw.clone(),
    )
    .with_optional_finish_reason(turn.finish_reason.cloned());
    folded.message_id = turn.identity.message_id.clone();
    folded.response_id = turn.identity.response_id.clone();
    folded.provider_request_id = turn.identity.provider_request_id.clone();
    let outcome: Result<Outcome, ErrorReport> = Ok(Outcome::Completion(folded));
    let mut replaced: Option<Vec<AssistantContent>> = None;
    match hooks
        .on_outcome(
            hook_ctx,
            OutcomeEvent {
                id: turn.dispatch_id,
                kind: turn.dispatch_kind,
                outcome: &outcome,
                turn: hook_ctx.turn(),
                call_id: None,
                context: None,
            },
        )
        .await
    {
        OutcomeAction::Proceed => {}
        OutcomeAction::Replace(Ok(Outcome::Completion(replacement))) => {
            run.replace_accepted_turn_choice(replacement.choice.clone())?;
            replaced = Some(replacement.choice);
        }
        OutcomeAction::Replace(Ok(other)) => {
            return Err(PromptError::Report(wrong_outcome("a completion", &other)));
        }
        OutcomeAction::Replace(Err(report)) => {
            if report.kind == ErrorKind::Cancelled {
                return Ok(ModelTurnDecision::Terminate(report.message));
            }
            return Err(PromptError::Report(report));
        }
    }
    let content = replaced.as_ref().unwrap_or(turn.content);
    let action = hooks
        .on_model_turn_finished(
            hook_ctx,
            ModelTurnFinished {
                turn: hook_ctx.turn(),
                content,
                usage: turn.usage,
                identity: turn.identity,
                finish_reason: turn.finish_reason,
                max_tokens: turn.max_tokens,
                raw: turn.raw,
            },
        )
        .await;
    match action {
        ModelTurnAction::Continue => Ok(ModelTurnDecision::Advance { replaced }),
        ModelTurnAction::Retry(request) => {
            run.retry_model_turn(request)?;
            Ok(ModelTurnDecision::Retried)
        }
        ModelTurnAction::Stop(reason) => Ok(ModelTurnDecision::Terminate(reason)),
    }
}

/// Outcome of firing the `CompletionCallEvent` hook for a turn.
pub(crate) enum CompletionCallOutcome {
    /// Proceed, optionally applying a per-turn request patch (the merged patch
    /// from every hook that contributed one).
    Proceed(Option<RequestPatch>),
    /// Terminate the run with this reason.
    Terminate(String),
}

/// Fire the event-specific completion-call hook for a turn.
pub(crate) async fn resolve_completion_call(
    hooks: &HookStack,
    ctx: &HookContext,
    prompt: &Message,
    history: &[Message],
    turn: usize,
) -> CompletionCallOutcome {
    match hooks
        .on_completion_call(
            ctx,
            CompletionCallEvent {
                prompt,
                history,
                turn,
            },
        )
        .await
    {
        CompletionCallAction::Stop(reason) => CompletionCallOutcome::Terminate(reason),
        CompletionCallAction::Patch(patch) => CompletionCallOutcome::Proceed(Some(patch)),
        CompletionCallAction::Continue => CompletionCallOutcome::Proceed(None),
    }
}

/// Append a finished run's messages to conversation memory, logging and
/// proceeding on failure. Shared `Done`-arm behavior for both drivers. The
/// append is a `Memory` dispatch at the boundary: observe-only for hooks
/// unless one opts into `MemoryDispatch`. Returns how the append settled
/// for the response, `None` when the run has no memory to append to.
pub(crate) async fn append_run_messages(
    runner: &AgentRunner,
    ctx: &HookContext,
    memory_handle: Option<&(MemoryHandle, rig_core::id::ConversationId)>,
    messages: &[Message],
) -> Option<MemoryAppend> {
    // Clone into an owned vec only when there is a backend to append to, so the
    // common no-memory path pays nothing.
    let (memory, id) = memory_handle?;
    let appended = dispatch_effect(
        &runner.config.hooks,
        ctx,
        runner.config.bus.dispatcher(),
        memory.key(),
        EffectKind::Memory {
            op: rig_core::effect::MemoryOp::Append {
                conversation: id.clone(),
                messages: messages.to_vec(),
            },
        },
    )
    .await
    .and_then(|outcome| match outcome {
        Outcome::Memory(rig_core::effect::MemoryOutcome::Appended) => Ok(()),
        other => Err(wrong_outcome("appended memory", &other)),
    });
    Some(match appended {
        Ok(()) => MemoryAppend::Acknowledged,
        Err(report) => {
            tracing::warn!(
                error = %report,
                conversation_id = %id,
                "conversation memory append failed; surfacing final response anyway"
            );
            MemoryAppend::Failed { report }
        }
    })
}

/// Dispatch any effect through the agent's bus at the dispatch boundary:
/// `on_dispatch` before (a same-family patch or a denial), the bus, then
/// `on_outcome` after (a replacement). The engine's memory and retrieval
/// effects go through here; completions and tool calls have their own
/// entry points because their denials have run-level meaning.
pub(crate) async fn dispatch_effect(
    hooks: &HookStack,
    ctx: &HookContext,
    dispatcher: &crate::bus::Dispatcher,
    key: &rig_core::effect::HandlerKey,
    kind: EffectKind,
) -> Result<Outcome, ErrorReport> {
    let id = dispatcher.mint_id();
    let family = kind.family();
    let kind = match hooks
        .on_dispatch(
            ctx,
            DispatchEvent {
                id,
                kind: &kind,
                turn: ctx.turn(),
                call_id: None,
                context: None,
            },
        )
        .await
    {
        DispatchAction::Proceed => kind,
        DispatchAction::Patch(patched) if patched.family() == family => patched,
        DispatchAction::Patch(other) => return Err(wrong_family_patch(kind.name(), &other)),
        DispatchAction::Deny(report) => return Err(report),
    };
    let outcome = dispatcher
        .dispatch_with(key, kind.clone(), DispatchOptions::default().with_id(id))
        .await;
    match hooks
        .on_outcome(
            ctx,
            OutcomeEvent {
                id,
                kind: &kind,
                outcome: &outcome,
                turn: ctx.turn(),
                call_id: None,
                context: None,
            },
        )
        .await
    {
        OutcomeAction::Proceed => outcome,
        OutcomeAction::Replace(replaced) => replaced,
    }
}

pub(crate) fn wrong_outcome(expected: &str, outcome: &Outcome) -> ErrorReport {
    ErrorReport::new(
        ErrorKind::Internal,
        format!(
            "expected {expected}, the handler answered with a {} outcome",
            outcome.family()
        ),
    )
}

/// Whether (and how) a tool call executed, for [`run_single_tool`].
pub(crate) enum ToolExecution {
    /// The tool's body ran. Carries the effective tool call, meaning the model's
    /// call with any [`DispatchAction::Patch`] hook rewrite applied, so the
    /// driver can surface it in the
    /// [`ToolExecutionCommitted`](crate::agent::streaming::MultiTurnStreamItem::ToolExecutionCommitted)
    /// event (what actually ran, not the model's original arguments).
    Executed(ToolCall),
    /// A dispatch hook denied the call ([`DispatchAction::skip`]): the
    /// body did not run, so no execution-commit is surfaced, but the skip result
    /// still reaches the model and is surfaced as a `ToolResult`.
    Skipped,
}

/// Outcome of [`run_single_tool`]: the tool-result content plus whether the
/// tool's body ran (and the effective call) or a hook skipped it.
pub(crate) struct ToolCallOutcome {
    /// The tool result delivered to the model (a real output, a redacted
    /// replacement, or a hook skip reason).
    pub content: UserContent,
    /// How the call resolved: executed (with the effective tool call) or skipped.
    pub execution: ToolExecution,
}

/// Execute a single tool call through the dispatch boundary and shape the
/// result. **Shared by the blocking and streaming drivers** so a tool call
/// behaves identically in both: same hook events (`on_dispatch` before,
/// `on_outcome` after), same fail-closed skip/terminate handling, and the
/// same result shaping. A hook's skip becomes [`ToolResult::skipped`], and
/// every result is converted directly into typed message content through
/// [`tool_result_output`] without reparsing text. Records `gen_ai.tool.*` on
/// the current span; `error_history` builds a cancellation error if a hook
/// terminates the run. Returns whether the tool body executed via
/// [`ToolCallOutcome::execution`].
pub(crate) async fn run_single_tool(
    runner: &AgentRunner,
    ctx: &HookContext,
    tool_snapshot: &ToolCatalog,
    tool_call: &ToolCall,
    error_history: &[Message],
) -> Result<ToolCallOutcome, PromptError> {
    let tool_context = &runner.tool_context;
    let record_content = runner.config.record_telemetry_content;
    let tool_name = tool_call.function.name.as_str();
    let args = json_utils::serialize_json_value(&tool_call.function.arguments);

    let tool_span = tracing::Span::current();
    tool_span.record("gen_ai.tool.name", tool_name);
    tool_span.record(
        "gen_ai.tool.call.id",
        tracing::field::display(&tool_call.id),
    );
    if record_content {
        tool_span.record("gen_ai.tool.call.arguments", &args);
    }

    let ToolCallDispatch {
        result: exec,
        executed,
        context: _dispatch_context,
        args: effective_args,
    } = match dispatch_tool_call(
        runner,
        ctx,
        tool_snapshot,
        tool_name,
        args.clone(),
        &tool_call.id,
        tool_context,
    )
    .await
    {
        Ok(dispatch) => dispatch,
        Err(ToolDispatchAbort::Cancelled(reason)) => {
            return Err(PromptError::prompt_cancelled(
                error_history.to_vec(),
                reason,
            ));
        }
        Err(ToolDispatchAbort::Failed(report)) => return Err(PromptError::Report(report)),
    };

    // A hook patched the arguments: re-record the span so the trace reflects
    // what the tool actually received rather than what the model emitted.
    if effective_args != args {
        if record_content {
            tool_span.record("gen_ai.tool.call.arguments", &effective_args);
        }
        tracing::debug!(
            tool_name = tool_name,
            "tool-call arguments rewritten by a hook"
        );
    }

    // A skip runs nothing and surfaces no execution commit; a real execution
    // carries the effective tool call (the model's call with any patch
    // applied) so a redaction rewrite does not leak.
    let execution = if !executed {
        ToolExecution::Skipped
    } else {
        let mut effective_tool_call = tool_call.clone();
        effective_tool_call.function.arguments = serde_json::from_str(&effective_args)
            .unwrap_or_else(|_| serde_json::Value::String(effective_args.clone()));
        ToolExecution::Executed(effective_tool_call)
    };
    // Outcome metadata describes the execution itself, while result content
    // follows the same presentation policy as the model: what the outcome
    // hook let through is what telemetry records.
    record_tool_result(&tool_span, &exec);
    if record_content {
        tool_span.record("gen_ai.tool.call.result", exec.output().render());
    }
    let content = tool_result_output(
        tool_call.id.clone(),
        tool_call.function.name.clone(),
        exec.output().clone(),
    );
    Ok(ToolCallOutcome { content, execution })
}

fn record_tool_result(span: &tracing::Span, result: &ToolResult) {
    span.record("gen_ai.tool.call.outcome", result.status_name());
    if let Some(error) = result.error() {
        span.record("gen_ai.tool.error.type", error.kind().as_str());
    }
}

/// [`TurnSource`] for the blocking surface: each turn issues a unary
/// `model.completion()` request and feeds the whole response into the machine.
/// Emits no intermediate items (the blocking surface folds the engine to its
/// final response), but keeps the blocking driver's linear `follows_from` span
/// chain across chat and tool spans.
pub(crate) struct UnaryTurnSource {
    /// Sequences chat and tool spans into a linear `follows_from` chain (the
    /// streaming surface parents the same tree but does not chain).
    ///
    /// Atomic rather than `Cell` despite being driven by a single sequential
    /// task: `run_tool_calls` passes `chain_span` as a closure into
    /// `drive_tool_calls`, whose returned `DriveStream` is `Send`. That makes the
    /// closure capture `&self`, so `&UnaryTurnSource` must be `Send`, i.e.
    /// `UnaryTurnSource: Sync`, which `AtomicU64` provides and `Cell` does not.
    current_span_id: AtomicU64,
    record_telemetry_content: bool,
}

impl UnaryTurnSource {
    pub(crate) fn new(record_telemetry_content: bool) -> Self {
        Self {
            current_span_id: AtomicU64::new(0),
            record_telemetry_content,
        }
    }

    /// Chain `span` onto the previous step's span and record it as the new chain
    /// head, preserving the blocking driver's linear causal trace.
    fn chain_span(&self, span: tracing::Span) -> tracing::Span {
        let span = match self.current_span_id.load(Ordering::Relaxed) {
            0 => span,
            id => {
                span.follows_from(Id::from_u64(id));
                span
            }
        };
        if let Some(id) = span.id() {
            self.current_span_id.store(id.into_u64(), Ordering::Relaxed);
        }
        span
    }
}

impl TurnSource for UnaryTurnSource {
    fn open_chat_span(
        &self,
        runner: &AgentRunner,
        effective_preamble: Option<&str>,
    ) -> tracing::Span {
        let chat_span = build_chat_span!(runner, effective_preamble, "chat", "chat");
        self.chain_span(chat_span)
    }

    fn run_model_turn<'a>(
        &'a mut self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        prepared: PreparedCompletionRequest,
        chat_span: tracing::Span,
        _agent_span: &'a tracing::Span,
        _current_prompt: Message,
    ) -> DriveStream<'a> {
        Box::pin(async_stream::stream! {
            // Content telemetry for the accepted provider turn. Called at each
            // terminal site (stop, terminate, accept) rather than hoisted: a
            // retried turn must not record output for the discarded attempt.
            let record_accepted_turn = |run: &AgentRun| {
                if runner.config.record_telemetry_content
                    && let Some(choice) = run.accepted_turn_choice()
                {
                    rig_core::telemetry::record_model_output(&chat_span, &choice, true);
                }
            };

            // Bound before the builder is consumed: this is the cap this exact
            // attempt was prepared with, patches included, and it is what the
            // per-turn hook reports. Reading it later off the agent config would
            // silently drop a completion-call hook's patch.
            let attempt_max_tokens = prepared.max_tokens;

            let request = prepared.request;
            let model = prepared.model;
            let (dispatch_id, dispatched_kind, resp) = match dispatch_completion(runner, hook_ctx, &model, request, false)
                .instrument(chat_span.clone())
                .await
            {
                Ok(CompletionDispatch::Response { id, kind, response }) => (id, kind, response),
                Ok(CompletionDispatch::Stream { .. }) => {
                    yield Err(StreamingError::Report(
                        ErrorReport::new(
                            ErrorKind::Internal,
                            "a unary completion dispatch answered with a stream",
                        ),
                    ));
                    return;
                }
                Err(CompletionDispatchError::Cancelled(reason)) => {
                    yield Err(StreamingError::Prompt(run.cancel_error(reason)));
                    return;
                }
                Err(CompletionDispatchError::Failed(err)) => {
                    yield Err(StreamingError::from(err));
                    return;
                }
            };

            // Normalized once, then shared by run state and the per-turn hook, so
            // the two cannot report different reasons for one attempt.
            let attempt_finish_reason = resp.finish_reason();

            let mut outcome = match run.model_response(ModelTurn::from_response_parts(
                &resp,
                prepared.executable_tool_names,
                prepared.allowed_tool_names,
            )) {
                Ok(outcome) => outcome,
                Err(err) => {
                    yield Err(err.into());
                    return;
                }
            };

            loop {
                match outcome {
                    ModelTurnOutcome::NeedsResolution(context) => {
                        let action = runner
                            .config.hooks
                            .on_invalid_tool_call(hook_ctx, &context)
                            .await;
                        let resolution = match action {
                            Some(action) => run.resolve_invalid_tool_call(action),
                            None => run.resolve_unhandled_invalid_tool_call(),
                        };
                        outcome = match resolution {
                            Ok(outcome) => outcome,
                            Err(err) => {
                                yield Err(err.into());
                                return;
                            }
                        };
                    }
                    ModelTurnOutcome::TurnRetried => break,
                    ModelTurnOutcome::Continue {
                        response_hook_suppressed,
                    } => {
                        if !response_hook_suppressed {
                            let identity = resp.identity();
                            let settlement = settle_model_turn(
                                &runner.config.hooks,
                                hook_ctx,
                                run,
                                AssembledTurn {
                                    dispatch_id,
                                    dispatch_kind: &dispatched_kind,
                                    provider: &resp.provider,
                                    content: &resp.choice,
                                    usage: resp.usage,
                                    identity: &identity,
                                    finish_reason: attempt_finish_reason.as_ref(),
                                    max_tokens: attempt_max_tokens,
                                    raw: &resp.raw,
                                },
                            )
                            .await;
                            match settlement {
                                Ok(ModelTurnDecision::Advance { .. }) => {}
                                Ok(ModelTurnDecision::Retried) => break,
                                Ok(ModelTurnDecision::Terminate(reason)) => {
                                    record_accepted_turn(run);
                                    yield Err(StreamingError::Prompt(
                                        run.cancel_error(reason),
                                    ));
                                    return;
                                }
                                Err(err) => {
                                    yield Err(StreamingError::Prompt(err));
                                    return;
                                }
                            }
                        }

                        record_accepted_turn(run);
                        break;
                    }
                }
            }
        })
    }

    fn run_tool_calls<'a>(
        &'a self,
        runner: &'a AgentRunner,
        hook_ctx: &'a HookContext,
        run: &'a mut AgentRun,
        calls: Vec<PendingToolCall>,
        tool_snapshot: Arc<ToolCatalog>,
    ) -> DriveStream<'a> {
        // The blocking surface chains tool spans into its linear `follows_from`
        // sequence (chat -> tool -> chat), and discards the yielded items, so it
        // skips building them.
        drive_tool_calls(
            runner,
            hook_ctx,
            run,
            calls,
            tool_snapshot,
            |span| self.chain_span(span),
            false,
        )
    }

    fn record_run_level_telemetry(
        &self,
        agent_span: &tracing::Span,
        response: &PromptResponse,
        created_agent_span: bool,
    ) {
        // Record completion and usage onto the agent span only when this run
        // created it, never onto a caller-supplied outer span. The blocking
        // surface additionally records the final completion text.
        if created_agent_span {
            if self.record_telemetry_content {
                agent_span.record("gen_ai.completion", &response.output);
            }
            agent_span.record_token_usage(&response.usage);
        }
    }

    fn final_item(&self, _response: &PromptResponse) -> Option<MultiTurnStreamItem> {
        // The blocking surface folds the engine and discards the final item, so
        // building it (an extra full-response clone) is skipped entirely.
        None
    }
}

#[cfg(test)]
#[allow(irrefutable_let_patterns, unreachable_patterns)]
mod tests;

/// What a completion dispatch answered.
pub(crate) enum CompletionDispatch {
    /// A unary dispatch's answer. The outcome hook fires when the turn is
    /// settled (after the run validated the answer's tool calls), so the id
    /// and the dispatched effect travel with the response.
    Response {
        id: EffectId,
        kind: EffectKind,
        response: rig_core::completion::CompletionResponse,
    },
    /// A streaming dispatch: the outcome hook fires on its folded terminal,
    /// which is why the id and the dispatched effect travel with the stream.
    Stream {
        id: EffectId,
        kind: EffectKind,
        stream: rig_core::streaming::CompletionStream,
    },
}

/// Why a completion dispatch did not answer.
pub(crate) enum CompletionDispatchError {
    /// A hook denied it with a `Cancelled` report: the run is cancelled.
    Cancelled(String),
    /// The dispatch failed (a denial with any other kind, a bus or handler
    /// failure, a wrong-family patch).
    Failed(ErrorReport),
}

fn wrong_family_patch(expected: &str, kind: &EffectKind) -> ErrorReport {
    ErrorReport::new(
        ErrorKind::Internal,
        format!(
            "a hook patched a {expected} dispatch into a `{}` effect",
            kind.name()
        ),
    )
}

/// Dispatch a completion through the agent's bus at the dispatch boundary:
/// `on_dispatch` before (patch or deny), then the bus. The outcome hook is
/// not fired here: on either medium it fires in [`settle_model_turn`], once
/// the run has validated the answer's tool calls and parked the turn. That is
/// the slot where a hook can still replace what history keeps, on both media.
pub(crate) async fn dispatch_completion(
    runner: &AgentRunner,
    ctx: &HookContext,
    model: &ModelHandle,
    request: rig_core::completion::CompletionRequest,
    stream: bool,
) -> Result<CompletionDispatch, CompletionDispatchError> {
    let hooks = &runner.config.hooks;
    let dispatcher = runner.config.bus.dispatcher();
    let id = dispatcher.mint_id();
    let kind = EffectKind::Completion { request, stream };
    let kind = match hooks
        .on_dispatch(
            ctx,
            DispatchEvent {
                id,
                kind: &kind,
                turn: ctx.turn(),
                call_id: None,
                context: None,
            },
        )
        .await
    {
        DispatchAction::Proceed => kind,
        DispatchAction::Patch(patched) => match patched {
            EffectKind::Completion { request, .. } => EffectKind::Completion { request, stream },
            other => {
                return Err(CompletionDispatchError::Failed(wrong_family_patch(
                    "completion",
                    &other,
                )));
            }
        },
        DispatchAction::Deny(report) => {
            return Err(if report.kind == ErrorKind::Cancelled {
                CompletionDispatchError::Cancelled(report.message)
            } else {
                CompletionDispatchError::Failed(report)
            });
        }
    };
    if stream {
        let provider = model.label().to_string();
        let events = dispatcher.dispatch_stream_with(
            model.key(),
            kind.clone(),
            DispatchOptions::default().with_id(id),
        );
        return Ok(CompletionDispatch::Stream {
            id,
            kind,
            stream: crate::bus::wrap_stream(provider, events),
        });
    }
    let outcome = dispatcher
        .dispatch_with(
            model.key(),
            kind.clone(),
            DispatchOptions::default().with_id(id),
        )
        .await;
    match outcome {
        Ok(Outcome::Completion(response)) => {
            Ok(CompletionDispatch::Response { id, kind, response })
        }
        Ok(other) => Err(CompletionDispatchError::Failed(ErrorReport::new(
            ErrorKind::Internal,
            format!(
                "the completion handler answered with a {} outcome",
                other.family()
            ),
        ))),
        Err(report) => Err(CompletionDispatchError::Failed(report)),
    }
}

/// A tool call answered at the dispatch boundary: the result, the context
/// the tool answered with, and the arguments it actually ran with (after
/// any hook's patch).
pub(crate) struct ToolCallDispatch {
    pub(crate) result: ToolResult,
    /// Disposition at the dispatch boundary, before outcome presentation hooks.
    pub(crate) executed: bool,
    pub(crate) context: crate::tool::ToolContext,
    pub(crate) args: String,
}

/// Dispatch a tool call through the agent's bus at the dispatch boundary:
/// `on_dispatch` before (patch the arguments, skip with a reason, or stop),
/// the bus, `on_outcome` after (replace what the run sees, or stop).
/// `Err(reason)` cancels the run; every other failure is the tool result
/// the model sees.
/// Why a tool dispatch produced no result for the model: a hook cancelled
/// the run, or the bus could not serve the call (closed, or the tool's
/// handler gone). This is a failure of the run, not of the tool.
pub(crate) enum ToolDispatchAbort {
    Cancelled(String),
    Failed(ErrorReport),
}

pub(crate) async fn dispatch_tool_call(
    runner: &AgentRunner,
    ctx: &HookContext,
    tool_snapshot: &ToolCatalog,
    tool_name: &str,
    args: String,
    call_id: &rig_core::message::CallId,
    tool_context: &crate::tool::ToolContext,
) -> Result<ToolCallDispatch, ToolDispatchAbort> {
    let hooks = &runner.config.hooks;
    let dispatcher = runner.config.bus.dispatcher();
    let id = dispatcher.mint_id();
    let kind = EffectKind::ToolCall {
        name: tool_name.to_owned(),
        args,
    };
    // The context the tool runs with travels beside the effect, never in it
    // (format 5): the hooks see it on the event, the bus carries it to the
    // tool's sink, and what the tool published comes back the same way.
    let inbound = tool_context.for_dispatch();
    let (kind, denied) = match hooks
        .on_dispatch(
            ctx,
            DispatchEvent {
                id,
                kind: &kind,
                turn: ctx.turn(),
                call_id: Some(call_id),
                context: Some(&inbound),
            },
        )
        .await
    {
        DispatchAction::Proceed => (kind, None),
        DispatchAction::Patch(patched) => {
            match super::hook::validate_dispatch_patch(&kind, &patched) {
                Ok(()) => (patched, None),
                Err(report) => (kind, Some(report)),
            }
        }
        DispatchAction::Deny(report) => {
            if report.kind == ErrorKind::Cancelled {
                return Err(ToolDispatchAbort::Cancelled(report.message));
            }
            tracing::info!(tool_name = tool_name, reason = %report.message, "Tool call rejected");
            // A patch an earlier hook made before the denial is what the
            // skipped result reports.
            let salvaged = ctx.take_salvaged_patch(id);
            let kind = salvaged
                .filter(|patched| super::hook::validate_dispatch_patch(&kind, patched).is_ok())
                .unwrap_or(kind);
            (kind, Some(report))
        }
    };
    let effective_args = match &kind {
        EffectKind::ToolCall { args, .. } => args.clone(),
        _ => String::new(),
    };
    let mut published: Option<crate::tool::ToolContext> = None;
    let mut executed = false;
    let outcome: Result<Outcome, ErrorReport> = match denied {
        Some(report) => Ok(Outcome::ToolResult {
            result: ToolResult::skipped(report.message),
        }),
        None => match tool_snapshot.key(tool_name) {
            Some(key) => {
                let pending = dispatcher.dispatch_with(
                    key.raw(),
                    kind.clone(),
                    DispatchOptions::default()
                        .with_id(id)
                        .with_tool_context(inbound.clone()),
                );
                let published_at = pending.published_context();
                let outcome = pending.await;
                executed =
                    matches!(&outcome, Ok(Outcome::ToolResult { result }) if !result.is_skipped());
                published = published_at.and_then(|published| published.take());
                outcome
            }
            None => Ok(Outcome::ToolResult {
                result: ToolResult::failed(
                    crate::tool::ToolExecutionError::not_found(format!(
                        "no tool named `{tool_name}` is registered"
                    ))
                    .with_model_feedback(format!("tool `{tool_name}` not found")),
                ),
            }),
        },
    };
    let context = published.unwrap_or_else(|| tool_context.for_dispatch());
    let outcome = match hooks
        .on_outcome(
            ctx,
            OutcomeEvent {
                id,
                kind: &kind,
                outcome: &outcome,
                turn: ctx.turn(),
                call_id: Some(call_id),
                context: Some(&context),
            },
        )
        .await
    {
        OutcomeAction::Proceed => outcome,
        OutcomeAction::Replace(replaced) => replaced,
    };
    Ok(match outcome {
        Ok(Outcome::ToolResult { result }) => ToolCallDispatch {
            executed,
            result,
            context,
            args: effective_args,
        },
        Ok(other) => ToolCallDispatch {
            executed,
            result: ToolResult::failed(crate::tool::ToolExecutionError::other(format!(
                "the tool handler answered with a {} outcome",
                other.family()
            ))),
            context: tool_context.for_dispatch(),
            args: effective_args,
        },
        // A hook that observed the result stopped the run.
        Err(report) if report.kind == ErrorKind::Cancelled => {
            return Err(ToolDispatchAbort::Cancelled(report.message));
        }
        // A layer on the tool's key denied the call: the model sees the
        // skipped result, as it does for a hook's denial.
        Err(report) if report.kind == ErrorKind::Denied => {
            tracing::info!(tool_name = tool_name, reason = %report.message, "Tool call denied");
            ToolCallDispatch {
                executed,
                result: ToolResult::skipped(report.message),
                context: tool_context.for_dispatch(),
                args: effective_args,
            }
        }
        // The bus could not serve the call, or a replayer refused it as a
        // divergence: the run fails with the report rather than telling the model
        // its tool failed, since a replay continuing on an answer the record never
        // gave would pass with a different trace.
        Err(report)
            if matches!(
                report.kind,
                ErrorKind::BusClosed | ErrorKind::HandlerUnavailable | ErrorKind::Divergence
            ) =>
        {
            return Err(ToolDispatchAbort::Failed(report));
        }
        Err(report) => ToolCallDispatch {
            executed,
            result: ToolResult::failed(
                crate::tool::ToolExecutionError::other(report.message.clone())
                    .with_model_feedback(report.message),
            ),
            context: tool_context.for_dispatch(),
            args: effective_args,
        },
    })
}