appam 0.1.1

High-throughput, traceable, reliable Rust agent framework for long-horizon AI sessions and easy extensibility
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
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
//! Default agent runtime and orchestration.
//!
//! Provides the standard conversation loop for agents: streaming LLM responses,
//! executing tool calls, and managing session state.

use anyhow::{Context, Result};
use futures::stream::{self, StreamExt};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use tracing::{debug, info, instrument, warn};
use uuid::Uuid;

use super::consumers::{ConsoleConsumer, TraceConsumer};
use super::errors::{extract_session_failure_kind, SessionFailureError, SessionFailureKind};
use super::history::SessionHistory;
use super::streaming::{MultiConsumer, StreamConsumer, StreamEvent};
use super::{Agent, Session};
use crate::llm::{
    ChatMessage, DynamicLlmClient, LlmClient, LlmProvider, Role, UnifiedMessage, UnifiedRole,
};
use crate::logging::write_session_log;
use crate::tools::{ToolConcurrency, ToolContext};

fn select_usage_model(cfg: &crate::config::AppConfig, provider: &LlmProvider) -> String {
    match provider {
        LlmProvider::Anthropic | LlmProvider::AzureAnthropic { .. } => cfg
            .anthropic
            .pricing_model
            .clone()
            .unwrap_or_else(|| cfg.anthropic.model.clone()),
        LlmProvider::OpenAI | LlmProvider::AzureOpenAI { .. } => cfg
            .openai
            .pricing_model
            .as_deref()
            .map(crate::llm::openai::normalize_openai_model)
            .unwrap_or_else(|| crate::llm::openai::normalize_openai_model(&cfg.openai.model)),
        LlmProvider::OpenAICodex => cfg
            .openai_codex
            .pricing_model
            .as_deref()
            .map(crate::llm::openai::normalize_openai_model)
            .unwrap_or_else(|| crate::llm::openai::normalize_openai_model(&cfg.openai_codex.model)),
        LlmProvider::Vertex => cfg.vertex.model.clone(),
        LlmProvider::OpenRouterCompletions | LlmProvider::OpenRouterResponses => {
            cfg.openrouter.model.clone()
        }
        LlmProvider::Bedrock { model_id, .. } => model_id.clone(),
    }
}

fn latest_provider_response_id(messages: &[ChatMessage]) -> Option<String> {
    messages.iter().rev().find_map(|message| {
        if message.role == Role::Assistant {
            message.provider_response_id.clone()
        } else {
            None
        }
    })
}

fn has_non_thinking_raw_content(blocks: &[crate::llm::UnifiedContentBlock]) -> bool {
    blocks
        .iter()
        .any(|block| !matches!(block, crate::llm::UnifiedContentBlock::Thinking { .. }))
}

fn blank_assistant_turn(
    streamed_text: &str,
    pending_tool_calls: &[crate::llm::ToolCall],
    raw_content_blocks: &[crate::llm::UnifiedContentBlock],
) -> bool {
    streamed_text.is_empty()
        && pending_tool_calls.is_empty()
        && !has_non_thinking_raw_content(raw_content_blocks)
}

/// Persist finalized tool calls for the current assistant turn.
///
/// Some streaming providers emit an additional empty finalized-tool-call batch
/// after the real tool calls have already been reported. Appam must ignore that
/// empty batch so it does not overwrite the assistant history entry with
/// `tool_calls: []`.
fn apply_finalized_tool_calls(
    pending_tool_calls: &mut Vec<crate::llm::ToolCall>,
    assistant_tool_msg: &mut Option<ChatMessage>,
    unified_calls: Vec<crate::llm::unified::UnifiedToolCall>,
) {
    if unified_calls.is_empty() {
        return;
    }

    let tool_calls: Vec<crate::llm::ToolCall> = unified_calls
        .iter()
        .map(|uc| crate::llm::ToolCall {
            id: uc.id.clone(),
            type_field: "function".to_string(),
            function: crate::llm::ToolCallFunction {
                name: uc.name.clone(),
                arguments: uc.raw_input_json.clone().unwrap_or_else(|| {
                    serde_json::to_string(&uc.input).unwrap_or_else(|_| uc.input.to_string())
                }),
            },
        })
        .collect();

    pending_tool_calls.extend(tool_calls.clone());
    *assistant_tool_msg = Some(ChatMessage {
        role: Role::Assistant,
        name: None,
        tool_call_id: None,
        content: None,
        tool_calls: Some(tool_calls),
        reasoning: None,
        raw_content_blocks: None,
        tool_metadata: None,
        timestamp: Some(chrono::Utc::now()),
        id: Some(ChatMessage::generate_id()),
        provider_response_id: None,
        status: Some(crate::llm::MessageStatus::Completed),
    });
}

fn called_required_completion_tool(messages: &[ChatMessage], required_tools: &[String]) -> bool {
    messages.iter().any(|msg| {
        msg.tool_calls.as_ref().is_some_and(|tool_calls| {
            tool_calls
                .iter()
                .any(|tool_call| required_tools.contains(&tool_call.function.name))
        })
    })
}

/// Runtime decision for agents that must call a completion tool before exiting.
///
/// Some agents, such as the init agent, are not allowed to finish with a plain
/// assistant response. They must eventually call a specific tool that persists
/// or finalizes their work. This enum captures the runtime action to take after
/// a turn ends without a successful completion-tool call.
///
/// # Design notes
///
/// The runtime keeps this decision explicit rather than encoding it in booleans
/// so call sites can distinguish between:
/// - a normal terminal state (`None`)
/// - a recoverable state that should inject another user continuation message
/// - an exhausted state that should raise a deterministic session failure
#[derive(Debug, Clone, PartialEq, Eq)]
enum RequiredCompletionContinuationDecision {
    /// Inject another continuation user message and let the session proceed.
    Inject {
        /// Exact continuation message that should be appended to the transcript.
        continuation_message: String,
        /// One-based attempt number for observability.
        continuation_attempt: usize,
        /// Required completion tools that remain outstanding.
        required_tools: Vec<String>,
    },
    /// Stop retrying because the continuation budget has been exhausted.
    Exhausted {
        /// Number of continuation messages already injected.
        continuation_count: usize,
        /// Required completion tools that were never called.
        required_tools: Vec<String>,
    },
    /// No continuation handling is needed.
    None,
}

/// Decide whether the runtime should auto-continue a session that requires a tool.
///
/// The runtime uses this helper after turns that end without tool calls and after
/// blank/reasoning-only turns. In both cases, the recovery strategy is identical:
/// if the agent still owes a required completion tool and continuation budget
/// remains, inject the configured continuation message instead of terminating the
/// session immediately.
///
/// # Parameters
///
/// - `agent`: Agent whose continuation policy should be enforced
/// - `messages`: Transcript accumulated so far, used to detect prior attempts
///
/// # Returns
///
/// A structured decision describing whether the runtime should inject another
/// continuation message, fail due to exhaustion, or do nothing.
///
/// # Edge cases
///
/// - Agents without required completion tools always return `None`
/// - If any required completion tool was already called, the helper returns `None`
/// - Exact-message matching is used intentionally so unrelated user messages do
///   not consume the continuation budget
fn required_completion_continuation_decision<A: Agent + ?Sized>(
    agent: &A,
    messages: &[ChatMessage],
) -> RequiredCompletionContinuationDecision {
    let Some(required_tools) = agent.required_completion_tools() else {
        return RequiredCompletionContinuationDecision::None;
    };

    if called_required_completion_tool(messages, required_tools) {
        return RequiredCompletionContinuationDecision::None;
    }

    let continuation_message = agent
        .continuation_message()
        .unwrap_or(
            "Continue your task. Please call one of the required completion tools to finish this session.",
        )
        .to_string();

    let continuation_count = messages
        .iter()
        .filter(|message| {
            message.role == Role::User
                && message
                    .content
                    .as_ref()
                    .map(|content| content == &continuation_message)
                    .unwrap_or(false)
        })
        .count();

    if continuation_count < agent.max_continuations() {
        RequiredCompletionContinuationDecision::Inject {
            continuation_message,
            continuation_attempt: continuation_count + 1,
            required_tools: required_tools.clone(),
        }
    } else {
        RequiredCompletionContinuationDecision::Exhausted {
            continuation_count,
            required_tools: required_tools.clone(),
        }
    }
}

/// Apply required-completion continuation handling for recoverable terminal turns.
///
/// This helper centralizes the runtime behavior for turns that ended before the
/// model called one of the required completion tools. That includes both:
/// - visible assistant turns that simply stopped without tool calls
/// - blank/reasoning-only turns where the provider produced no usable content
///
/// # Parameters
///
/// - `agent`: Agent whose completion policy is being enforced
/// - `messages`: Mutable transcript that may receive a continuation message
/// - `consumer`: Stream consumer used to emit structured error events on failure
/// - `client`: LLM client used to attach provider diagnostics to failures
/// - `completion_reason`: Short human-readable reason for logs
///
/// # Returns
///
/// - `Ok(true)` when a continuation message was appended and the caller should
///   immediately continue the main runtime loop
/// - `Ok(false)` when no continuation handling is required
/// - `Err(...)` when continuation attempts are exhausted and the session should fail
///
/// # Security considerations
///
/// The helper only injects the runtime-owned continuation message. It does not
/// reinterpret arbitrary model output as operator intent, which avoids accidental
/// privilege escalation through prompt-manipulated user messages.
fn handle_required_completion_gap<A: Agent + ?Sized>(
    agent: &A,
    messages: &mut Vec<ChatMessage>,
    consumer: &MultiConsumer,
    client: &DynamicLlmClient,
    completion_reason: &str,
) -> Result<bool> {
    match required_completion_continuation_decision(agent, messages) {
        RequiredCompletionContinuationDecision::Inject {
            continuation_message,
            continuation_attempt,
            required_tools,
        } => {
            info!(
                continuation_attempt = continuation_attempt,
                max_continuations = agent.max_continuations(),
                required_tools = ?required_tools,
                completion_reason = completion_reason,
                "Session continuation: injecting continuation message"
            );

            messages.push(ChatMessage {
                role: Role::User,
                name: None,
                tool_call_id: None,
                content: Some(continuation_message),
                tool_calls: None,
                reasoning: None,
                raw_content_blocks: None,
                tool_metadata: None,
                timestamp: Some(chrono::Utc::now()),
                id: None,
                provider_response_id: None,
                status: None,
            });
            Ok(true)
        }
        RequiredCompletionContinuationDecision::Exhausted {
            continuation_count,
            required_tools,
        } => {
            let error = anyhow::Error::new(SessionFailureError::new(
                SessionFailureKind::RequiredCompletionToolMissing,
                format!(
                    "Agent '{}' exhausted {} continuation attempts without calling required completion tools: {}",
                    agent.name(),
                    continuation_count,
                    required_tools.join(", ")
                ),
            ));
            emit_stream_error_event(consumer, client, &error);
            Err(error)
        }
        RequiredCompletionContinuationDecision::None => Ok(false),
    }
}

fn emit_stream_error_event(
    consumer: &MultiConsumer,
    client: &DynamicLlmClient,
    error: &anyhow::Error,
) {
    let provider_failure = client.take_last_failed_exchange();
    let event = StreamEvent::Error {
        message: error.to_string(),
        failure_kind: extract_session_failure_kind(error),
        provider: provider_failure
            .as_ref()
            .map(|capture| capture.provider.clone())
            .or_else(|| Some(client.provider_name().to_string())),
        model: provider_failure
            .as_ref()
            .map(|capture| capture.model.clone()),
        http_status: provider_failure
            .as_ref()
            .and_then(|capture| capture.http_status),
        request_payload: provider_failure
            .as_ref()
            .map(|capture| capture.request_payload.clone()),
        response_payload: provider_failure
            .as_ref()
            .map(|capture| capture.response_payload.clone()),
        provider_response_id: provider_failure
            .as_ref()
            .and_then(|capture| capture.provider_response_id.clone()),
    };

    if let Err(consumer_error) = consumer.on_event(&event) {
        warn!(
            error = %consumer_error,
            original_error = %error,
            "Failed to emit stream error event"
        );
    }
}

/// Apply per-agent parallel tool-call defaults to provider configuration.
///
/// Appam intentionally keeps provider-side tool batching disabled unless the
/// active agent explicitly enables it. Anthropic requires a slightly different
/// mapping because the parallel control lives inside `tool_choice`.
fn apply_parallel_tool_call_defaults<A: Agent + ?Sized>(
    agent: &A,
    cfg: &mut crate::config::AppConfig,
) {
    let parallel_tool_calls = agent.provider_parallel_tool_calls();
    cfg.openai.parallel_tool_calls = Some(parallel_tool_calls);
    cfg.openrouter.parallel_tool_calls = Some(parallel_tool_calls);
    cfg.openai_codex.parallel_tool_calls = Some(parallel_tool_calls);

    if cfg.anthropic.tool_choice.is_none() {
        cfg.anthropic.tool_choice = Some(crate::llm::anthropic::ToolChoiceConfig::Auto {
            disable_parallel_tool_use: !parallel_tool_calls,
        });
    }
}

#[derive(Debug)]
struct PreparedToolCall {
    call: crate::llm::ToolCall,
    args: serde_json::Value,
}

#[derive(Debug)]
struct ToolExecutionOutcome {
    call: crate::llm::ToolCall,
    result_json: serde_json::Value,
    success: bool,
    duration_ms: f64,
}

fn prepare_tool_calls(
    pending_tool_calls: &[crate::llm::ToolCall],
    multi_consumer: &MultiConsumer,
    emitted_tool_calls: &Arc<Mutex<HashSet<String>>>,
) -> Result<Vec<PreparedToolCall>> {
    let mut prepared = Vec::with_capacity(pending_tool_calls.len());

    for call in pending_tool_calls {
        info!(tool = %call.function.name, "Executing tool");

        let mut should_emit_start = false;
        let args_snapshot = call.function.arguments.clone();

        if !args_snapshot.trim().is_empty() {
            let mut seen = emitted_tool_calls
                .lock()
                .expect("tool call tracker poisoned");
            should_emit_start = seen.insert(call.id.clone());
        }

        if should_emit_start {
            multi_consumer.on_event(&StreamEvent::ToolCallStarted {
                tool_name: call.function.name.clone(),
                arguments: args_snapshot.clone(),
            })?;
        }

        debug!(
            tool = %call.function.name,
            args_len = call.function.arguments.len(),
            "Parsing tool arguments"
        );
        let args = serde_json::from_str(&call.function.arguments).with_context(|| {
            format!(
                "Failed to parse arguments for tool {} ({} bytes)",
                call.function.name,
                call.function.arguments.len()
            )
        })?;

        prepared.push(PreparedToolCall {
            call: call.clone(),
            args,
        });
    }

    Ok(prepared)
}

async fn run_tool_call<A: Agent + ?Sized>(
    agent: &A,
    session_id: &str,
    prepared: PreparedToolCall,
) -> ToolExecutionOutcome {
    let start_time = std::time::Instant::now();
    let ctx = ToolContext::new(
        session_id.to_string(),
        agent.name().to_string(),
        prepared.call.id.clone(),
    );
    let result = agent
        .execute_tool_with_context(&prepared.call.function.name, ctx, prepared.args)
        .await;
    let elapsed = start_time.elapsed();
    let duration_ms = elapsed.as_secs_f64() * 1000.0;

    match result {
        Ok(value) => ToolExecutionOutcome {
            call: prepared.call,
            result_json: value,
            success: true,
            duration_ms,
        },
        Err(error) => ToolExecutionOutcome {
            call: prepared.call,
            result_json: serde_json::json!({
                "success": false,
                "error": error.to_string()
            }),
            success: false,
            duration_ms,
        },
    }
}

async fn execute_pending_tool_calls<A: Agent + ?Sized>(
    agent: &A,
    session_id: &str,
    pending_tool_calls: &[crate::llm::ToolCall],
    messages: &mut Vec<ChatMessage>,
    multi_consumer: &MultiConsumer,
    emitted_tool_calls: &Arc<Mutex<HashSet<String>>>,
) -> Result<bool> {
    let required_completion_tools = agent.required_completion_tools().cloned();
    let prepared_calls =
        prepare_tool_calls(pending_tool_calls, multi_consumer, emitted_tool_calls)?;

    let should_run_parallel = agent.provider_parallel_tool_calls()
        && agent.max_concurrent_tool_executions() > 1
        && prepared_calls.len() > 1
        && prepared_calls.iter().all(|prepared| {
            agent.tool_concurrency(&prepared.call.function.name) == ToolConcurrency::ParallelSafe
        });

    let outcomes = if should_run_parallel {
        let max_concurrency = agent.max_concurrent_tool_executions();
        let mut indexed: Vec<(usize, ToolExecutionOutcome)> =
            stream::iter(prepared_calls.into_iter().enumerate().map(
                |(index, prepared)| async move {
                    (index, run_tool_call(agent, session_id, prepared).await)
                },
            ))
            .buffer_unordered(max_concurrency)
            .collect()
            .await;
        indexed.sort_by_key(|(index, _)| *index);
        indexed.into_iter().map(|(_, outcome)| outcome).collect()
    } else {
        let mut outcomes = Vec::with_capacity(prepared_calls.len());
        for prepared in prepared_calls {
            outcomes.push(run_tool_call(agent, session_id, prepared).await);
        }
        outcomes
    };

    let mut completed_via_required_tool = false;

    for outcome in outcomes {
        if outcome.success {
            info!(tool = %outcome.call.function.name, "Tool succeeded");
            multi_consumer.on_event(&StreamEvent::ToolCallCompleted {
                tool_name: outcome.call.function.name.clone(),
                result: outcome.result_json.clone(),
                success: true,
                duration_ms: outcome.duration_ms,
            })?;
        } else {
            let error_message = outcome.result_json["error"]
                .as_str()
                .unwrap_or("Tool execution failed")
                .to_string();
            info!(
                tool = %outcome.call.function.name,
                error = %error_message,
                "Tool failed"
            );
            multi_consumer.on_event(&StreamEvent::ToolCallFailed {
                tool_name: outcome.call.function.name.clone(),
                error: error_message,
            })?;
        }

        if outcome.success
            && required_completion_tools
                .as_ref()
                .is_some_and(|tools| tools.contains(&outcome.call.function.name))
        {
            completed_via_required_tool = true;
        }

        let content_str = match &outcome.result_json {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        messages.push(ChatMessage {
            role: Role::Tool,
            name: Some(outcome.call.function.name.clone()),
            tool_call_id: Some(outcome.call.id.clone()),
            content: Some(content_str),
            tool_calls: None,
            reasoning: None,
            raw_content_blocks: None,
            tool_metadata: Some(crate::llm::ToolExecutionMetadata {
                success: outcome.success,
                duration_ms: outcome.duration_ms,
                tool_name: outcome.call.function.name.clone(),
                arguments: outcome.call.function.arguments.clone(),
            }),
            timestamp: Some(chrono::Utc::now()),
            id: None,
            provider_response_id: None,
            status: None,
        });
    }

    Ok(completed_via_required_tool)
}

/// Default agent run implementation with console output.
///
/// Orchestrates a multi-turn conversation with tool calling and streams output
/// to the console with default formatting.
///
/// This is a convenience wrapper around `default_run_streaming()` that uses
/// `ConsoleConsumer` with default settings.
///
/// # Errors
///
/// Returns an error if:
/// - Configuration loading fails
/// - LLM request fails
/// - Tool execution fails
/// - Session logging fails
#[instrument(skip(agent), fields(agent = agent.name()))]
pub async fn default_run<A: Agent + ?Sized>(agent: &A, user_prompt: &str) -> Result<Session> {
    let consumer = ConsoleConsumer::default();
    default_run_streaming(agent, user_prompt, Box::new(consumer)).await
}

/// Default agent run implementation with custom streaming.
///
/// Orchestrates a multi-turn conversation with tool calling:
/// 1. Loads global configuration and initializes logging
/// 2. Creates a session and builds initial messages
/// 3. Streams LLM response with tool support via consumer
/// 4. Executes requested tools and appends results
/// 5. Repeats until LLM stops requesting tools
/// 6. Persists session transcript
///
/// # Tool Calling Loop
///
/// The agent continues streaming and executing tools until the LLM emits a
/// finish_reason other than "tool_calls". This enables multi-step reasoning
/// where the agent can call multiple tools sequentially.
///
/// # Parameters
///
/// - `agent`: The agent to run
/// - `user_prompt`: User's input message
/// - `consumer`: Stream consumer that receives events
///
/// # Errors
///
/// Returns an error if:
/// - Configuration loading fails
/// - LLM request fails
/// - Tool execution fails
/// - Consumer returns an error
/// - Session logging fails
#[instrument(skip(agent, consumer), fields(agent = agent.name()))]
pub async fn default_run_streaming<A: Agent + ?Sized>(
    agent: &A,
    user_prompt: &str,
    consumer: Box<dyn StreamConsumer>,
) -> Result<Session> {
    info!("Starting agent session");

    // Load configuration from defaults and environment variables only
    // (does NOT load appam.toml automatically - user must load explicitly if needed)
    let mut cfg = crate::config::load_config_from_env()?;

    // Override provider if agent specifies one
    if let Some(provider) = agent.provider() {
        info!(provider = %provider, "Using agent-specific provider override");
        cfg.provider = provider;
    }

    // Apply agent-specific configuration overrides (programmatic config has highest priority)
    agent.apply_config_overrides(&mut cfg);
    apply_parallel_tool_call_defaults(agent, &mut cfg);

    let logs_dir = crate::logging::init_logging(&cfg.logging)?;

    // Initialize session history
    let history = SessionHistory::new(cfg.history.clone()).await?;

    // Create session
    let session_id = Uuid::new_v4().to_string();
    let started_at = chrono::Utc::now();

    // Setup multi-consumer with trace consumer (if enabled)
    let multi_consumer = if cfg.logging.enable_traces {
        let trace_consumer = TraceConsumer::new(&logs_dir, &session_id, cfg.logging.trace_format)?;
        MultiConsumer::new()
            .add(Box::new(trace_consumer))
            .add(consumer)
    } else {
        MultiConsumer::new().add(consumer)
    };

    // Emit session started event
    multi_consumer.on_event(&StreamEvent::SessionStarted {
        session_id: session_id.clone(),
    })?;

    // Build initial messages
    let mut messages = agent.initial_messages(user_prompt)?;
    let tool_specs = agent.available_tools()?;

    debug!(
        session_id = %session_id,
        tools = tool_specs.len(),
        "Session initialized"
    );

    // Create LLM client based on configured provider
    let client = DynamicLlmClient::from_config(&cfg)?;
    client.set_previous_response_id(latest_provider_response_id(&messages));
    info!(provider = %client.provider(), "LLM client initialized");

    // Create usage tracker for this session
    let usage_tracker = crate::llm::usage::UsageTracker::new();
    let provider_variant = client.provider();
    let provider_usage_key = provider_variant.pricing_key().to_string();
    let model_name = select_usage_model(&cfg, &provider_variant);

    let emitted_tool_calls = Arc::new(Mutex::new(HashSet::<String>::new()));

    // Multi-round tool-calling loop
    loop {
        let mut streamed_text = String::new();
        let mut reasoning_text = String::new();
        let mut pending_tool_calls: Vec<crate::llm::ToolCall> = Vec::new();
        let mut assistant_tool_msg: Option<ChatMessage> = None;
        let mut raw_content_blocks: Vec<crate::llm::UnifiedContentBlock> = Vec::new();

        debug!("Starting LLM stream");

        let emitted_tool_calls_for_partial = Arc::clone(&emitted_tool_calls);

        // Convert to unified format for provider-agnostic client
        let unified_messages = chat_messages_to_unified(&messages);
        let unified_tools = tool_specs_to_unified(&tool_specs);

        // Stream response
        if let Err(error) = client
            .chat_with_tools_streaming(
                &unified_messages,
                &unified_tools,
                |chunk| {
                    // Content callback - stream via consumer
                    streamed_text.push_str(chunk);
                    multi_consumer.on_event(&StreamEvent::Content {
                        content: chunk.to_string(),
                    })?;
                    Ok(())
                },
                |unified_calls| {
                    apply_finalized_tool_calls(
                        &mut pending_tool_calls,
                        &mut assistant_tool_msg,
                        unified_calls,
                    );
                    Ok(())
                },
                |reason| {
                    // Reasoning callback - stream via consumer
                    reasoning_text.push_str(reason);
                    multi_consumer.on_event(&StreamEvent::Reasoning {
                        content: reason.to_string(),
                    })?;
                    Ok(())
                },
                |partial_calls| {
                    // Partial tool calls callback - emit tool call started events
                    for uc in partial_calls {
                        if !uc.name.is_empty() {
                            // Check if arguments are complete valid JSON
                            let args_str = uc.raw_input_json.clone().unwrap_or_else(|| {
                                serde_json::to_string(&uc.input)
                                    .unwrap_or_else(|_| uc.input.to_string())
                            });

                            if serde_json::from_str::<serde_json::Value>(&args_str).is_ok() {
                                let should_emit = {
                                    let mut seen = emitted_tool_calls_for_partial
                                        .lock()
                                        .expect("tool call tracker poisoned");
                                    seen.insert(uc.id.clone())
                                };

                                if should_emit {
                                    multi_consumer.on_event(&StreamEvent::ToolCallStarted {
                                        tool_name: uc.name.clone(),
                                        arguments: args_str,
                                    })?;
                                }
                            }
                        }
                    }
                    Ok(())
                },
                |content_block| {
                    // Complete content block callback - preserves thinking signatures
                    raw_content_blocks.push(content_block);
                    Ok(())
                },
                {
                    let tracker = usage_tracker.clone();
                    let provider = provider_usage_key.clone();
                    let model = model_name.clone();
                    let consumer = &multi_consumer;
                    move |usage| {
                        // Usage callback - track tokens and cost
                        tracker.add_usage(&usage, &provider, &model);
                        let snapshot = tracker.get_snapshot();
                        consumer.on_event(&StreamEvent::UsageUpdate { snapshot })?;
                        Ok(())
                    }
                },
            )
            .await
        {
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        let provider_response_id = client.latest_response_id();

        // Derive tool calls from raw content blocks when the streaming API
        // doesn't emit explicit tool call events (e.g., newer Responses formats).
        if pending_tool_calls.is_empty() {
            let derived_tool_calls: Vec<crate::llm::ToolCall> = raw_content_blocks
                .iter()
                .filter_map(|block| {
                    if let crate::llm::UnifiedContentBlock::ToolUse { id, name, input } = block {
                        match serde_json::to_string(input) {
                            Ok(arguments) => Some(crate::llm::ToolCall {
                                id: id.clone(),
                                type_field: "function".to_string(),
                                function: crate::llm::ToolCallFunction {
                                    name: name.clone(),
                                    arguments,
                                },
                            }),
                            Err(e) => {
                                debug!(tool = %name, error = %e, "Failed to serialize tool input");
                                None
                            }
                        }
                    } else {
                        None
                    }
                })
                .collect();

            if !derived_tool_calls.is_empty() {
                for call in &derived_tool_calls {
                    debug!(tool = %call.function.name, call_id = %call.id, "Derived tool call from raw content");
                }
                pending_tool_calls = derived_tool_calls.clone();

                if let Some(msg) = assistant_tool_msg.as_mut() {
                    msg.tool_calls = Some(derived_tool_calls.clone());
                } else {
                    assistant_tool_msg = Some(ChatMessage {
                        role: Role::Assistant,
                        name: None,
                        tool_call_id: None,
                        content: None,
                        tool_calls: Some(derived_tool_calls.clone()),
                        reasoning: None,
                        raw_content_blocks: None,
                        tool_metadata: None,
                        timestamp: Some(chrono::Utc::now()),
                        id: Some(ChatMessage::generate_id()),
                        provider_response_id: None,
                        status: Some(crate::llm::MessageStatus::Completed),
                    });
                }
            }
        }

        let has_tool_calls = !pending_tool_calls.is_empty();
        let has_streamed_text = !streamed_text.is_empty();
        let has_raw_blocks = !raw_content_blocks.is_empty();

        if has_tool_calls {
            // Preserve legacy behaviour: only add a separate assistant text message
            // when the model streamed visible content without raw blocks. When raw
            // blocks are present, they will be attached to the tool call message to
            // avoid duplicate messages.
            if has_streamed_text && !has_raw_blocks {
                messages.push(ChatMessage {
                    role: Role::Assistant,
                    name: None,
                    tool_call_id: None,
                    content: Some(streamed_text.clone()),
                    tool_calls: None,
                    reasoning: if reasoning_text.is_empty() {
                        None
                    } else {
                        Some(reasoning_text.clone())
                    },
                    raw_content_blocks: None,
                    tool_metadata: None,
                    timestamp: Some(chrono::Utc::now()),
                    id: Some(ChatMessage::generate_id()),
                    provider_response_id: provider_response_id.clone(),
                    status: Some(crate::llm::MessageStatus::Completed),
                });
            }
        } else if has_streamed_text || has_raw_blocks {
            // Final assistant turn (no tool calls). Capture whichever payload the
            // model produced: streamed text, raw content blocks, and reasoning.
            messages.push(ChatMessage {
                role: Role::Assistant,
                name: None,
                tool_call_id: None,
                content: if has_streamed_text {
                    Some(streamed_text.clone())
                } else {
                    None
                },
                tool_calls: None,
                reasoning: if reasoning_text.is_empty() {
                    None
                } else {
                    Some(reasoning_text.clone())
                },
                raw_content_blocks: if has_raw_blocks {
                    Some(raw_content_blocks.clone())
                } else {
                    None
                },
                tool_metadata: None,
                timestamp: Some(chrono::Utc::now()),
                id: Some(ChatMessage::generate_id()),
                provider_response_id: provider_response_id.clone(),
                status: Some(crate::llm::MessageStatus::Completed),
            });
        }

        if provider_response_id.is_some() {
            client.set_previous_response_id(provider_response_id.clone());
        }

        if blank_assistant_turn(&streamed_text, &pending_tool_calls, &raw_content_blocks) {
            if pending_tool_calls.is_empty()
                && handle_required_completion_gap(
                    agent,
                    &mut messages,
                    &multi_consumer,
                    &client,
                    "blank assistant turn",
                )?
            {
                continue;
            }

            let error = anyhow::Error::new(SessionFailureError::new(
                SessionFailureKind::BlankAssistantResponse,
                format!(
                    "Agent '{}' completed a turn without assistant text, tool calls, or non-thinking content",
                    agent.name()
                ),
            ));
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        // If no tool calls, check if continuation is needed
        if pending_tool_calls.is_empty() {
            debug!("No tool calls requested, checking completion status");

            if handle_required_completion_gap(
                agent,
                &mut messages,
                &multi_consumer,
                &client,
                "turn ended without tool calls",
            )? {
                continue;
            }

            debug!("Session complete");
            break;
        }

        debug!(
            tool_calls = pending_tool_calls.len(),
            "Executing tool calls"
        );

        // Add tool call message to history with reasoning and raw blocks attached
        if let Some(mut msg) = assistant_tool_msg.take() {
            // Attach any reasoning that was collected during streaming
            if !reasoning_text.is_empty() {
                msg.reasoning = Some(reasoning_text.clone());
            }
            // Attach raw content blocks to the tool call message (preserves thinking signatures)
            if !raw_content_blocks.is_empty() {
                msg.raw_content_blocks = Some(raw_content_blocks.clone());
            }
            msg.provider_response_id = provider_response_id.clone();
            messages.push(msg);
        }

        let completed_via_required_tool = execute_pending_tool_calls(
            agent,
            &session_id,
            &pending_tool_calls,
            &mut messages,
            &multi_consumer,
            &emitted_tool_calls,
        )
        .await?;

        if completed_via_required_tool {
            info!(
                agent = agent.name(),
                "Required completion tool executed successfully; ending session without additional continuation turn"
            );
            break;
        }

        // Loop continues: with tool results, prompt model again
    }

    let ended_at = chrono::Utc::now();

    // Create session object with usage tracking
    let session = Session {
        session_id: session_id.clone(),
        agent_name: agent.name().to_string(),
        model: model_name.clone(),
        messages: messages.clone(),
        started_at: Some(started_at),
        ended_at: Some(ended_at),
        usage: Some(usage_tracker.get_snapshot()),
    };

    // Save to history (if enabled and auto_save is true)
    if cfg.history.enabled && cfg.history.auto_save {
        history.save_session(&session).await?;
        info!(session_id = %session_id, "Session saved to history database");
    }

    // Write session log (legacy JSON format) - only if tracing enabled
    if cfg.logging.enable_traces {
        let log_path = write_session_log(&logs_dir, &session_id, &session)?;
        info!(path = %log_path.display(), "Session log written");
    }

    // Emit done event
    multi_consumer.on_event(&StreamEvent::Done)?;

    Ok(session)
}

/// Default agent run implementation with pre-built messages and custom streaming.
///
/// Like `default_run_streaming()`, but accepts a pre-built message list instead
/// of constructing messages from a user prompt. This is useful for multi-turn
/// conversations where the caller has already built the message history.
///
/// # Parameters
///
/// - `agent`: The agent to run
/// - `messages`: Pre-built message list (typically system + history + new user message)
/// - `consumer`: Stream consumer that receives events
///
/// # Errors
///
/// Returns an error if:
/// - Configuration loading fails
/// - LLM request fails
/// - Tool execution fails
/// - Consumer returns an error
/// - Session logging fails
#[instrument(skip(agent, messages, consumer), fields(agent = agent.name()))]
pub async fn default_run_streaming_with_messages<A: Agent + ?Sized>(
    agent: &A,
    messages: Vec<ChatMessage>,
    consumer: Box<dyn StreamConsumer>,
) -> Result<Session> {
    info!(
        message_count = messages.len(),
        "Starting agent session with pre-built messages"
    );

    // Load configuration from defaults and environment variables only
    let mut cfg = crate::config::load_config_from_env()?;

    // Override provider if agent specifies one
    if let Some(provider) = agent.provider() {
        info!(provider = %provider, "Using agent-specific provider override");
        cfg.provider = provider;
    }

    // Apply agent-specific configuration overrides
    agent.apply_config_overrides(&mut cfg);
    apply_parallel_tool_call_defaults(agent, &mut cfg);

    let logs_dir = crate::logging::init_logging(&cfg.logging)?;

    // Initialize session history
    let history = SessionHistory::new(cfg.history.clone()).await?;

    // Create session
    let session_id = Uuid::new_v4().to_string();
    let started_at = chrono::Utc::now();

    // Setup multi-consumer with trace consumer (if enabled)
    let multi_consumer = if cfg.logging.enable_traces {
        let trace_consumer = TraceConsumer::new(&logs_dir, &session_id, cfg.logging.trace_format)?;
        MultiConsumer::new()
            .add(Box::new(trace_consumer))
            .add(consumer)
    } else {
        MultiConsumer::new().add(consumer)
    };

    // Emit session started event
    multi_consumer.on_event(&StreamEvent::SessionStarted {
        session_id: session_id.clone(),
    })?;

    // Use pre-built messages instead of agent.initial_messages()
    let mut messages = messages;
    let tool_specs = agent.available_tools()?;

    debug!(
        session_id = %session_id,
        messages = messages.len(),
        tools = tool_specs.len(),
        "Session initialized with pre-built messages"
    );

    // Create LLM client based on configured provider
    let client = DynamicLlmClient::from_config(&cfg)?;
    client.set_previous_response_id(latest_provider_response_id(&messages));
    info!(provider = %client.provider(), "LLM client initialized");

    // Create usage tracker for this session
    let usage_tracker = crate::llm::usage::UsageTracker::new();
    let provider_variant = client.provider();
    let provider_usage_key = provider_variant.pricing_key().to_string();
    let model_name = select_usage_model(&cfg, &provider_variant);

    let emitted_tool_calls = Arc::new(Mutex::new(HashSet::<String>::new()));

    // Multi-round tool-calling loop
    loop {
        let mut streamed_text = String::new();
        let mut reasoning_text = String::new();
        let mut pending_tool_calls: Vec<crate::llm::ToolCall> = Vec::new();
        let mut assistant_tool_msg: Option<ChatMessage> = None;
        let mut raw_content_blocks: Vec<crate::llm::UnifiedContentBlock> = Vec::new();

        debug!("Starting LLM stream");

        let emitted_tool_calls_for_partial = Arc::clone(&emitted_tool_calls);

        // Convert to unified format for provider-agnostic client
        let unified_messages = chat_messages_to_unified(&messages);
        let unified_tools = tool_specs_to_unified(&tool_specs);

        // Stream response
        if let Err(error) = client
            .chat_with_tools_streaming(
                &unified_messages,
                &unified_tools,
                |chunk| {
                    streamed_text.push_str(chunk);
                    multi_consumer.on_event(&StreamEvent::Content {
                        content: chunk.to_string(),
                    })?;
                    Ok(())
                },
                |unified_calls| {
                    apply_finalized_tool_calls(
                        &mut pending_tool_calls,
                        &mut assistant_tool_msg,
                        unified_calls,
                    );
                    Ok(())
                },
                |reason| {
                    reasoning_text.push_str(reason);
                    multi_consumer.on_event(&StreamEvent::Reasoning {
                        content: reason.to_string(),
                    })?;
                    Ok(())
                },
                |partial_calls| {
                    for uc in partial_calls {
                        if !uc.name.is_empty() {
                            let args_str = uc.raw_input_json.clone().unwrap_or_else(|| {
                                serde_json::to_string(&uc.input)
                                    .unwrap_or_else(|_| uc.input.to_string())
                            });

                            if serde_json::from_str::<serde_json::Value>(&args_str).is_ok() {
                                let should_emit = {
                                    let mut seen = emitted_tool_calls_for_partial
                                        .lock()
                                        .expect("tool call tracker poisoned");
                                    seen.insert(uc.id.clone())
                                };

                                if should_emit {
                                    multi_consumer.on_event(&StreamEvent::ToolCallStarted {
                                        tool_name: uc.name.clone(),
                                        arguments: args_str,
                                    })?;
                                }
                            }
                        }
                    }
                    Ok(())
                },
                |content_block| {
                    raw_content_blocks.push(content_block);
                    Ok(())
                },
                {
                    let tracker = usage_tracker.clone();
                    let provider = provider_usage_key.clone();
                    let model = model_name.clone();
                    let consumer = &multi_consumer;
                    move |usage| {
                        tracker.add_usage(&usage, &provider, &model);
                        let snapshot = tracker.get_snapshot();
                        consumer.on_event(&StreamEvent::UsageUpdate { snapshot })?;
                        Ok(())
                    }
                },
            )
            .await
        {
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        let provider_response_id = client.latest_response_id();

        // Derive tool calls from raw content blocks when needed
        if pending_tool_calls.is_empty() {
            let derived_tool_calls: Vec<crate::llm::ToolCall> = raw_content_blocks
                .iter()
                .filter_map(|block| {
                    if let crate::llm::UnifiedContentBlock::ToolUse { id, name, input } = block {
                        match serde_json::to_string(input) {
                            Ok(arguments) => Some(crate::llm::ToolCall {
                                id: id.clone(),
                                type_field: "function".to_string(),
                                function: crate::llm::ToolCallFunction {
                                    name: name.clone(),
                                    arguments,
                                },
                            }),
                            Err(e) => {
                                debug!(tool = %name, error = %e, "Failed to serialize tool input");
                                None
                            }
                        }
                    } else {
                        None
                    }
                })
                .collect();

            if !derived_tool_calls.is_empty() {
                for call in &derived_tool_calls {
                    debug!(tool = %call.function.name, call_id = %call.id, "Derived tool call from raw content");
                }
                pending_tool_calls = derived_tool_calls.clone();

                if let Some(msg) = assistant_tool_msg.as_mut() {
                    msg.tool_calls = Some(derived_tool_calls.clone());
                } else {
                    assistant_tool_msg = Some(ChatMessage {
                        role: Role::Assistant,
                        name: None,
                        tool_call_id: None,
                        content: None,
                        tool_calls: Some(derived_tool_calls.clone()),
                        reasoning: None,
                        raw_content_blocks: None,
                        tool_metadata: None,
                        timestamp: Some(chrono::Utc::now()),
                        id: Some(ChatMessage::generate_id()),
                        provider_response_id: None,
                        status: Some(crate::llm::MessageStatus::Completed),
                    });
                }
            }
        }

        let has_tool_calls = !pending_tool_calls.is_empty();
        let has_streamed_text = !streamed_text.is_empty();
        let has_raw_blocks = !raw_content_blocks.is_empty();

        if has_tool_calls {
            if has_streamed_text && !has_raw_blocks {
                messages.push(ChatMessage {
                    role: Role::Assistant,
                    name: None,
                    tool_call_id: None,
                    content: Some(streamed_text.clone()),
                    tool_calls: None,
                    reasoning: if reasoning_text.is_empty() {
                        None
                    } else {
                        Some(reasoning_text.clone())
                    },
                    raw_content_blocks: None,
                    tool_metadata: None,
                    timestamp: Some(chrono::Utc::now()),
                    id: Some(ChatMessage::generate_id()),
                    provider_response_id: provider_response_id.clone(),
                    status: Some(crate::llm::MessageStatus::Completed),
                });
            }
        } else if has_streamed_text || has_raw_blocks {
            messages.push(ChatMessage {
                role: Role::Assistant,
                name: None,
                tool_call_id: None,
                content: if has_streamed_text {
                    Some(streamed_text.clone())
                } else {
                    None
                },
                tool_calls: None,
                reasoning: if reasoning_text.is_empty() {
                    None
                } else {
                    Some(reasoning_text.clone())
                },
                raw_content_blocks: if has_raw_blocks {
                    Some(raw_content_blocks.clone())
                } else {
                    None
                },
                tool_metadata: None,
                timestamp: Some(chrono::Utc::now()),
                id: Some(ChatMessage::generate_id()),
                provider_response_id: provider_response_id.clone(),
                status: Some(crate::llm::MessageStatus::Completed),
            });
        }

        if provider_response_id.is_some() {
            client.set_previous_response_id(provider_response_id.clone());
        }

        if blank_assistant_turn(&streamed_text, &pending_tool_calls, &raw_content_blocks) {
            if pending_tool_calls.is_empty()
                && handle_required_completion_gap(
                    agent,
                    &mut messages,
                    &multi_consumer,
                    &client,
                    "blank assistant turn",
                )?
            {
                continue;
            }

            let error = anyhow::Error::new(SessionFailureError::new(
                SessionFailureKind::BlankAssistantResponse,
                format!(
                    "Agent '{}' completed a turn without assistant text, tool calls, or non-thinking content",
                    agent.name()
                ),
            ));
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        // If no tool calls, check if continuation is needed
        if pending_tool_calls.is_empty() {
            debug!("No tool calls requested, checking completion status");

            if handle_required_completion_gap(
                agent,
                &mut messages,
                &multi_consumer,
                &client,
                "turn ended without tool calls",
            )? {
                continue;
            }

            debug!("Session complete");
            break;
        }

        debug!(
            tool_calls = pending_tool_calls.len(),
            "Executing tool calls"
        );

        // Add tool call message to history with reasoning and raw blocks attached
        if let Some(mut msg) = assistant_tool_msg.take() {
            if !reasoning_text.is_empty() {
                msg.reasoning = Some(reasoning_text.clone());
            }
            if !raw_content_blocks.is_empty() {
                msg.raw_content_blocks = Some(raw_content_blocks.clone());
            }
            msg.provider_response_id = provider_response_id.clone();
            messages.push(msg);
        }

        let completed_via_required_tool = execute_pending_tool_calls(
            agent,
            &session_id,
            &pending_tool_calls,
            &mut messages,
            &multi_consumer,
            &emitted_tool_calls,
        )
        .await?;

        if completed_via_required_tool {
            info!(
                agent = agent.name(),
                "Required completion tool executed successfully; ending session without additional continuation turn"
            );
            break;
        }
    }

    let ended_at = chrono::Utc::now();

    // Create session object with usage tracking
    let session = Session {
        session_id: session_id.clone(),
        agent_name: agent.name().to_string(),
        model: model_name.clone(),
        messages: messages.clone(),
        started_at: Some(started_at),
        ended_at: Some(ended_at),
        usage: Some(usage_tracker.get_snapshot()),
    };

    // Save to history (if enabled and auto_save is true)
    if cfg.history.enabled && cfg.history.auto_save {
        history.save_session(&session).await?;
        info!(session_id = %session_id, "Session saved to history database");
    }

    // Write session log (legacy JSON format) - only if tracing enabled
    if cfg.logging.enable_traces {
        let log_path = write_session_log(&logs_dir, &session_id, &session)?;
        info!(path = %log_path.display(), "Session log written");
    }

    // Emit done event
    multi_consumer.on_event(&StreamEvent::Done)?;

    Ok(session)
}

/// Continue an existing session with a new user prompt.
///
/// Loads the session from history and continues the conversation with
/// the new prompt, preserving all previous messages and context.
///
/// # Parameters
///
/// - `agent`: The agent to run
/// - `session_id`: ID of the session to continue
/// - `user_prompt`: New user input
///
/// # Errors
///
/// Returns an error if:
/// - Session history is not enabled
/// - Session ID does not exist
/// - LLM request fails
/// - Tool execution fails
#[instrument(skip(agent), fields(agent = agent.name(), session_id = %session_id))]
pub async fn continue_session_run<A: Agent + ?Sized>(
    agent: &A,
    session_id: &str,
    user_prompt: &str,
) -> Result<Session> {
    let consumer = ConsoleConsumer::default();
    continue_session_streaming(agent, session_id, user_prompt, Box::new(consumer)).await
}

/// Continue an existing session with custom streaming.
///
/// Like `continue_session_run()`, but with a custom stream consumer.
///
/// # Parameters
///
/// - `agent`: The agent to run
/// - `session_id`: ID of the session to continue
/// - `user_prompt`: New user input
/// - `consumer`: Stream consumer for events
///
/// # Errors
///
/// Returns an error if:
/// - Session history is not enabled
/// - Session ID does not exist
/// - LLM request fails
/// - Tool execution fails
/// - Consumer returns an error
#[instrument(skip(agent, consumer), fields(agent = agent.name(), session_id = %session_id))]
pub async fn continue_session_streaming<A: Agent + ?Sized>(
    agent: &A,
    session_id: &str,
    user_prompt: &str,
    consumer: Box<dyn StreamConsumer>,
) -> Result<Session> {
    info!("Continuing existing session");

    // Load configuration from defaults and environment variables only
    // (does NOT load appam.toml automatically - user must load explicitly if needed)
    let mut cfg = crate::config::load_config_from_env()?;

    // Override provider if agent specifies one
    if let Some(provider) = agent.provider() {
        info!(provider = %provider, "Using agent-specific provider override for continuation");
        cfg.provider = provider;
    }

    // Apply agent-specific configuration overrides (programmatic config has highest priority)
    agent.apply_config_overrides(&mut cfg);
    apply_parallel_tool_call_defaults(agent, &mut cfg);

    let logs_dir = crate::logging::init_logging(&cfg.logging)?;

    // Initialize session history
    let history = SessionHistory::new(cfg.history.clone()).await?;

    // Load existing session
    let mut session = history
        .load_session(session_id)
        .await?
        .ok_or_else(|| anyhow::anyhow!("Session not found: {}", session_id))?;

    info!(
        session_id = %session_id,
        existing_messages = session.messages.len(),
        "Continuing session with existing messages"
    );

    // Setup multi-consumer with trace consumer (if enabled)
    let multi_consumer = if cfg.logging.enable_traces {
        let trace_consumer = TraceConsumer::new(&logs_dir, session_id, cfg.logging.trace_format)?;
        MultiConsumer::new()
            .add(Box::new(trace_consumer))
            .add(consumer)
    } else {
        MultiConsumer::new().add(consumer)
    };

    // Emit session started event (continuation)
    multi_consumer.on_event(&StreamEvent::SessionStarted {
        session_id: session_id.to_string(),
    })?;

    // Add new user message to existing messages
    session.messages.push(ChatMessage {
        role: Role::User,
        name: None,
        tool_call_id: None,
        content: Some(user_prompt.to_string()),
        tool_calls: None,
        reasoning: None,
        raw_content_blocks: None,
        tool_metadata: None,
        timestamp: Some(chrono::Utc::now()),
        id: None,
        provider_response_id: None,
        status: None,
    });

    let mut messages = session.messages.clone();
    let tool_specs = agent.available_tools()?;

    debug!(
        session_id = %session_id,
        total_messages = messages.len(),
        tools = tool_specs.len(),
        "Session continuation initialized"
    );

    // Create LLM client based on configured provider
    let client = DynamicLlmClient::from_config(&cfg)?;
    client.set_previous_response_id(latest_provider_response_id(&messages));
    info!(provider = %client.provider(), "LLM client initialized for session continuation");

    // Create or restore usage tracker for this session
    let usage_tracker = session
        .usage
        .clone()
        .map(|u| {
            let tracker = crate::llm::usage::UsageTracker::new();
            tracker.inner.lock().unwrap().clone_from(&u);
            tracker
        })
        .unwrap_or_else(crate::llm::usage::UsageTracker::new);
    let provider_variant = client.provider();
    let provider_usage_key = provider_variant.pricing_key().to_string();
    let model_name = select_usage_model(&cfg, &provider_variant);

    // Ensure the session metadata reflects the active provider/model pair.
    session.model = model_name.clone();

    let emitted_tool_calls = Arc::new(Mutex::new(HashSet::<String>::new()));

    // Multi-round tool-calling loop (same as default_run_streaming)
    loop {
        let mut streamed_text = String::new();
        let mut reasoning_text = String::new();
        let mut pending_tool_calls: Vec<crate::llm::ToolCall> = Vec::new();
        let mut assistant_tool_msg: Option<ChatMessage> = None;
        let mut raw_content_blocks: Vec<crate::llm::UnifiedContentBlock> = Vec::new();

        debug!("Starting LLM stream");

        let emitted_tool_calls_for_partial = Arc::clone(&emitted_tool_calls);

        // Convert to unified format for provider-agnostic client
        let unified_messages = chat_messages_to_unified(&messages);
        let unified_tools = tool_specs_to_unified(&tool_specs);

        // Stream response
        if let Err(error) = client
            .chat_with_tools_streaming(
                &unified_messages,
                &unified_tools,
                |chunk| {
                    streamed_text.push_str(chunk);
                    multi_consumer.on_event(&StreamEvent::Content {
                        content: chunk.to_string(),
                    })?;
                    Ok(())
                },
                |unified_calls| {
                    apply_finalized_tool_calls(
                        &mut pending_tool_calls,
                        &mut assistant_tool_msg,
                        unified_calls,
                    );
                    Ok(())
                },
                |reason| {
                    reasoning_text.push_str(reason);
                    multi_consumer.on_event(&StreamEvent::Reasoning {
                        content: reason.to_string(),
                    })?;
                    Ok(())
                },
                |partial_calls| {
                    // Partial tool calls callback - emit tool call started events
                    for uc in partial_calls {
                        if !uc.name.is_empty() {
                            let args_str = uc.raw_input_json.clone().unwrap_or_else(|| {
                                serde_json::to_string(&uc.input)
                                    .unwrap_or_else(|_| uc.input.to_string())
                            });
                            if serde_json::from_str::<serde_json::Value>(&args_str).is_ok() {
                                let should_emit = {
                                    let mut seen = emitted_tool_calls_for_partial
                                        .lock()
                                        .expect("tool call tracker poisoned");
                                    seen.insert(uc.id.clone())
                                };

                                if should_emit {
                                    multi_consumer.on_event(&StreamEvent::ToolCallStarted {
                                        tool_name: uc.name.clone(),
                                        arguments: args_str,
                                    })?;
                                }
                            }
                        }
                    }
                    Ok(())
                },
                |content_block| {
                    // Complete content block callback - preserves thinking signatures
                    raw_content_blocks.push(content_block);
                    Ok(())
                },
                {
                    let tracker = usage_tracker.clone();
                    let provider = provider_usage_key.clone();
                    let model = model_name.clone();
                    let consumer = &multi_consumer;
                    move |usage| {
                        // Usage callback - track tokens and cost
                        tracker.add_usage(&usage, &provider, &model);
                        let snapshot = tracker.get_snapshot();
                        consumer.on_event(&StreamEvent::UsageUpdate { snapshot })?;
                        Ok(())
                    }
                },
            )
            .await
        {
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        let provider_response_id = client.latest_response_id();

        if pending_tool_calls.is_empty() {
            let derived_tool_calls: Vec<crate::llm::ToolCall> = raw_content_blocks
                .iter()
                .filter_map(|block| {
                    if let crate::llm::UnifiedContentBlock::ToolUse { id, name, input } = block {
                        match serde_json::to_string(input) {
                            Ok(arguments) => Some(crate::llm::ToolCall {
                                id: id.clone(),
                                type_field: "function".to_string(),
                                function: crate::llm::ToolCallFunction {
                                    name: name.clone(),
                                    arguments,
                                },
                            }),
                            Err(e) => {
                                debug!(tool = %name, error = %e, "Failed to serialize tool input");
                                None
                            }
                        }
                    } else {
                        None
                    }
                })
                .collect();

            if !derived_tool_calls.is_empty() {
                for call in &derived_tool_calls {
                    debug!(tool = %call.function.name, call_id = %call.id, "Derived tool call from raw content");
                }
                pending_tool_calls = derived_tool_calls.clone();

                if let Some(msg) = assistant_tool_msg.as_mut() {
                    msg.tool_calls = Some(derived_tool_calls.clone());
                } else {
                    assistant_tool_msg = Some(ChatMessage {
                        role: Role::Assistant,
                        name: None,
                        tool_call_id: None,
                        content: None,
                        tool_calls: Some(derived_tool_calls.clone()),
                        reasoning: None,
                        raw_content_blocks: None,
                        tool_metadata: None,
                        timestamp: Some(chrono::Utc::now()),
                        id: Some(ChatMessage::generate_id()),
                        provider_response_id: None,
                        status: Some(crate::llm::MessageStatus::Completed),
                    });
                }
            }
        }

        let has_tool_calls = !pending_tool_calls.is_empty();
        let has_streamed_text = !streamed_text.is_empty();
        let has_raw_blocks = !raw_content_blocks.is_empty();

        if has_tool_calls {
            if has_streamed_text && !has_raw_blocks {
                messages.push(ChatMessage {
                    role: Role::Assistant,
                    name: None,
                    tool_call_id: None,
                    content: Some(streamed_text.clone()),
                    tool_calls: None,
                    reasoning: if reasoning_text.is_empty() {
                        None
                    } else {
                        Some(reasoning_text.clone())
                    },
                    raw_content_blocks: None,
                    tool_metadata: None,
                    timestamp: Some(chrono::Utc::now()),
                    id: Some(ChatMessage::generate_id()),
                    provider_response_id: provider_response_id.clone(),
                    status: Some(crate::llm::MessageStatus::Completed),
                });
            }
        } else if has_streamed_text || has_raw_blocks {
            messages.push(ChatMessage {
                role: Role::Assistant,
                name: None,
                tool_call_id: None,
                content: if has_streamed_text {
                    Some(streamed_text.clone())
                } else {
                    None
                },
                tool_calls: None,
                reasoning: if reasoning_text.is_empty() {
                    None
                } else {
                    Some(reasoning_text.clone())
                },
                raw_content_blocks: if has_raw_blocks {
                    Some(raw_content_blocks.clone())
                } else {
                    None
                },
                tool_metadata: None,
                timestamp: Some(chrono::Utc::now()),
                id: Some(ChatMessage::generate_id()),
                provider_response_id: provider_response_id.clone(),
                status: Some(crate::llm::MessageStatus::Completed),
            });
        }

        if provider_response_id.is_some() {
            client.set_previous_response_id(provider_response_id.clone());
        }

        if blank_assistant_turn(&streamed_text, &pending_tool_calls, &raw_content_blocks) {
            if pending_tool_calls.is_empty()
                && handle_required_completion_gap(
                    agent,
                    &mut messages,
                    &multi_consumer,
                    &client,
                    "blank assistant turn",
                )?
            {
                continue;
            }

            let error = anyhow::Error::new(SessionFailureError::new(
                SessionFailureKind::BlankAssistantResponse,
                format!(
                    "Agent '{}' completed a turn without assistant text, tool calls, or non-thinking content",
                    agent.name()
                ),
            ));
            emit_stream_error_event(&multi_consumer, &client, &error);
            return Err(error);
        }

        // If no tool calls, check if continuation is needed
        if pending_tool_calls.is_empty() {
            debug!("No tool calls requested, checking completion status");

            if handle_required_completion_gap(
                agent,
                &mut messages,
                &multi_consumer,
                &client,
                "turn ended without tool calls",
            )? {
                continue;
            }

            debug!("Session complete");
            break;
        }

        debug!(
            tool_calls = pending_tool_calls.len(),
            "Executing tool calls"
        );

        // Add tool call message to history with reasoning attached
        if let Some(mut msg) = assistant_tool_msg.take() {
            if !reasoning_text.is_empty() {
                msg.reasoning = Some(reasoning_text.clone());
            }
            if !raw_content_blocks.is_empty() {
                msg.raw_content_blocks = Some(raw_content_blocks.clone());
            }
            msg.provider_response_id = provider_response_id.clone();
            messages.push(msg);
        }

        let completed_via_required_tool = execute_pending_tool_calls(
            agent,
            session_id,
            &pending_tool_calls,
            &mut messages,
            &multi_consumer,
            &emitted_tool_calls,
        )
        .await?;

        if completed_via_required_tool {
            info!(
                agent = agent.name(),
                "Required completion tool executed successfully; ending session without additional continuation turn"
            );
            break;
        }

        // Loop continues: with tool results, prompt model again
    }

    let ended_at = chrono::Utc::now();

    // Update session object with usage tracking
    session.messages = messages;
    session.ended_at = Some(ended_at);
    session.usage = Some(usage_tracker.get_snapshot());

    // Save to history (if enabled and auto_save is true)
    if cfg.history.enabled && cfg.history.auto_save {
        history.save_session(&session).await?;
        info!(session_id = %session_id, "Session updated in history database");
    }

    // Write session log (legacy JSON format) - only if tracing enabled
    if cfg.logging.enable_traces {
        let log_path = write_session_log(&logs_dir, session_id, &session)?;
        info!(path = %log_path.display(), "Session log written");
    }

    // Emit done event
    multi_consumer.on_event(&StreamEvent::Done)?;

    Ok(session)
}

/// Convert ChatMessage to UnifiedMessage for provider-agnostic client calls.
///
/// Maps the legacy ChatMessage format to the unified format that works
/// with both OpenRouter and Anthropic providers.
///
/// # Signature Preservation
///
/// When `raw_content_blocks` is present, it's used directly to preserve:
/// - Thinking block signatures (required for Anthropic tool use)
/// - Redacted thinking blocks
/// - Multimodal content (images, documents)
/// - Exact block ordering from API responses
///
/// Otherwise, content is reconstructed from legacy fields (backward compatibility).
fn chat_messages_to_unified(messages: &[ChatMessage]) -> Vec<UnifiedMessage> {
    messages
        .iter()
        .map(|msg| {
            let role = match msg.role {
                Role::System => UnifiedRole::System,
                Role::User => UnifiedRole::User,
                Role::Assistant => UnifiedRole::Assistant,
                Role::Developer => UnifiedRole::System, // Map developer to system
                Role::Tool => UnifiedRole::User,        // Tool results as user messages
            };

            // FAST PATH: Use raw blocks if available (preserves thinking signatures!)
            // This takes precedence over all legacy fields to avoid duplication
            if let Some(ref raw_blocks) = msg.raw_content_blocks {
                // When raw blocks are present, use them exclusively
                // This preserves exact API response structure with signatures
                return UnifiedMessage {
                    role,
                    content: raw_blocks.clone(),
                    id: msg.id.clone(),
                    timestamp: msg.timestamp,
                    reasoning: msg.reasoning.clone(),
                    reasoning_details: None, // TODO: Add if needed
                };
            }

            // LEGACY PATH: Reconstruct from individual fields (backward compatibility)
            let mut content_blocks = Vec::new();

            // Add text content if present
            if let Some(ref text) = msg.content {
                if !text.trim().is_empty() {
                    content_blocks
                        .push(crate::llm::UnifiedContentBlock::Text { text: text.clone() });
                }
            }

            // Add tool calls if present
            if let Some(ref tool_calls) = msg.tool_calls {
                for tc in tool_calls {
                    let input: serde_json::Value = serde_json::from_str(&tc.function.arguments)
                        .unwrap_or(serde_json::json!({}));

                    content_blocks.push(crate::llm::UnifiedContentBlock::ToolUse {
                        id: tc.id.clone(),
                        name: tc.function.name.clone(),
                        input,
                    });
                }
            }

            // Add reasoning if present (legacy - no signature)
            if let Some(ref reasoning) = msg.reasoning {
                content_blocks.push(crate::llm::UnifiedContentBlock::Thinking {
                    thinking: reasoning.clone(),
                    signature: None,
                    encrypted_content: None,
                    redacted: false,
                });
            }

            // Handle tool result messages
            if msg.role == Role::Tool {
                if let (Some(ref content), Some(ref tool_call_id)) =
                    (&msg.content, &msg.tool_call_id)
                {
                    content_blocks = vec![crate::llm::UnifiedContentBlock::ToolResult {
                        tool_use_id: tool_call_id.clone(),
                        content: serde_json::json!(content),
                        is_error: Some(false),
                    }];
                }
            }

            UnifiedMessage {
                role,
                content: content_blocks,
                id: msg.id.clone(),
                timestamp: msg.timestamp,
                reasoning: msg.reasoning.clone(),
                reasoning_details: None, // TODO: Add if needed
            }
        })
        .collect()
}

/// Convert ToolSpec to UnifiedTool.
fn tool_specs_to_unified(specs: &[crate::llm::ToolSpec]) -> Vec<crate::llm::UnifiedTool> {
    specs
        .iter()
        .map(|spec| crate::llm::UnifiedTool {
            name: spec.name.clone(),
            description: spec.description.clone(),
            parameters: spec.parameters.clone(),
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::{
        apply_finalized_tool_calls, execute_pending_tool_calls,
        required_completion_continuation_decision, select_usage_model,
        RequiredCompletionContinuationDecision,
    };
    use crate::agent::AgentBuilder;
    use crate::config::AppConfig;
    use crate::llm::{ChatMessage, Role, ToolCall, ToolCallFunction, ToolSpec};
    use crate::tools::{AsyncTool, Tool, ToolConcurrency, ToolContext};
    use anyhow::Result;
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    /// Minimal tool used to exercise completion-tool continuation logic.
    ///
    /// The tests only need the tool's schema and name because continuation
    /// decisions are derived from transcript state, not tool execution.
    struct TestCompletionTool {
        name: String,
    }

    impl TestCompletionTool {
        fn new(name: impl Into<String>) -> Self {
            Self { name: name.into() }
        }
    }

    impl Tool for TestCompletionTool {
        fn name(&self) -> &str {
            &self.name
        }

        fn spec(&self) -> Result<ToolSpec> {
            Ok(serde_json::from_value(json!({
                "type": "function",
                "name": self.name,
                "description": "Test completion tool",
                "parameters": {
                    "type": "object",
                    "properties": {},
                }
            }))?)
        }

        fn execute(&self, _args: serde_json::Value) -> Result<serde_json::Value> {
            Ok(json!({"success": true}))
        }
    }

    fn user_message(content: &str) -> ChatMessage {
        ChatMessage {
            role: Role::User,
            name: None,
            tool_call_id: None,
            content: Some(content.to_string()),
            tool_calls: None,
            reasoning: None,
            raw_content_blocks: None,
            tool_metadata: None,
            timestamp: None,
            id: None,
            provider_response_id: None,
            status: None,
        }
    }

    #[test]
    fn apply_finalized_tool_calls_ignores_empty_batches() {
        let mut pending = Vec::new();
        let mut assistant_tool_msg = None;

        apply_finalized_tool_calls(&mut pending, &mut assistant_tool_msg, Vec::new());

        assert!(pending.is_empty());
        assert!(assistant_tool_msg.is_none());
    }

    #[test]
    fn apply_finalized_tool_calls_preserves_non_empty_batches() {
        let mut pending = Vec::new();
        let mut assistant_tool_msg = None;

        apply_finalized_tool_calls(
            &mut pending,
            &mut assistant_tool_msg,
            vec![crate::llm::unified::UnifiedToolCall {
                id: "call_1".to_string(),
                name: "bash".to_string(),
                input: json!({"command": "mkdir poem_generator"}),
                raw_input_json: Some("{\"command\":\"mkdir poem_generator\"}".to_string()),
            }],
        );

        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].function.name, "bash");
        let stored = assistant_tool_msg.expect("assistant tool message should be stored");
        assert_eq!(stored.tool_calls.as_ref().map(Vec::len), Some(1));
    }

    #[test]
    fn select_usage_model_prefers_openai_pricing_model_override() {
        let mut cfg = AppConfig::default();
        cfg.openai.model = "gpt-5.4-fast".to_string();
        cfg.openai.pricing_model = Some("gpt-5.4".to_string());

        let selected = select_usage_model(&cfg, &crate::llm::LlmProvider::OpenAI);
        assert_eq!(selected, "gpt-5.4");
    }

    #[test]
    fn select_usage_model_prefers_anthropic_pricing_model_override() {
        let mut cfg = AppConfig::default();
        cfg.anthropic.model = "claude-4-6-opus".to_string();
        cfg.anthropic.pricing_model = Some("claude-opus-4-6".to_string());

        let selected = select_usage_model(
            &cfg,
            &crate::llm::LlmProvider::AzureAnthropic {
                base_url: "https://example.services.ai.azure.com/anthropic".to_string(),
                auth_method: crate::llm::anthropic::AzureAnthropicAuthMethod::BearerToken,
            },
        );
        assert_eq!(selected, "claude-opus-4-6");
    }

    #[test]
    fn required_completion_continuation_injects_before_budget_is_exhausted() {
        let completion_tool = Arc::new(TestCompletionTool::new("store_custom_prompt"));
        let agent = AgentBuilder::new("init-agent-test")
            .system_prompt("Test")
            .require_completion_tools(vec![completion_tool as Arc<dyn Tool>])
            .continuation_message("Call the completion tool now.")
            .max_continuations(2)
            .build()
            .expect("agent should build");

        let messages = vec![user_message("Analyze the codebase.")];

        let decision = required_completion_continuation_decision(&agent, &messages);
        assert_eq!(
            decision,
            RequiredCompletionContinuationDecision::Inject {
                continuation_message: "Call the completion tool now.".to_string(),
                continuation_attempt: 1,
                required_tools: vec!["store_custom_prompt".to_string()],
            }
        );
    }

    #[test]
    fn required_completion_continuation_exhausts_at_configured_limit() {
        let completion_tool = Arc::new(TestCompletionTool::new("store_custom_prompt"));
        let agent = AgentBuilder::new("init-agent-test")
            .system_prompt("Test")
            .require_completion_tools(vec![completion_tool as Arc<dyn Tool>])
            .continuation_message("Call the completion tool now.")
            .max_continuations(2)
            .build()
            .expect("agent should build");

        let messages = vec![
            user_message("Analyze the codebase."),
            user_message("Call the completion tool now."),
            user_message("Call the completion tool now."),
        ];

        let decision = required_completion_continuation_decision(&agent, &messages);
        assert_eq!(
            decision,
            RequiredCompletionContinuationDecision::Exhausted {
                continuation_count: 2,
                required_tools: vec!["store_custom_prompt".to_string()],
            }
        );
    }

    #[test]
    fn required_completion_continuation_stops_after_required_tool_call() {
        let completion_tool = Arc::new(TestCompletionTool::new("store_custom_prompt"));
        let agent = AgentBuilder::new("init-agent-test")
            .system_prompt("Test")
            .require_completion_tools(vec![completion_tool as Arc<dyn Tool>])
            .continuation_message("Call the completion tool now.")
            .max_continuations(2)
            .build()
            .expect("agent should build");

        let messages = vec![ChatMessage {
            role: Role::Assistant,
            name: None,
            tool_call_id: None,
            content: None,
            tool_calls: Some(vec![ToolCall {
                id: "call_1".to_string(),
                type_field: "function".to_string(),
                function: ToolCallFunction {
                    name: "store_custom_prompt".to_string(),
                    arguments: "{}".to_string(),
                },
            }]),
            reasoning: None,
            raw_content_blocks: None,
            tool_metadata: None,
            timestamp: None,
            id: None,
            provider_response_id: None,
            status: None,
        }];

        let decision = required_completion_continuation_decision(&agent, &messages);
        assert_eq!(decision, RequiredCompletionContinuationDecision::None);
    }

    struct SleepTool {
        name: &'static str,
        concurrency: ToolConcurrency,
    }

    #[async_trait]
    impl AsyncTool for SleepTool {
        fn name(&self) -> &str {
            self.name
        }

        fn spec(&self) -> Result<ToolSpec> {
            Ok(serde_json::from_value(json!({
                "type": "function",
                "name": self.name,
                "description": "Sleep tool",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "delay_ms": {
                            "type": "number",
                            "description": "Delay in milliseconds"
                        }
                    },
                    "required": ["delay_ms"]
                }
            }))?)
        }

        fn concurrency(&self) -> ToolConcurrency {
            self.concurrency
        }

        async fn execute(
            &self,
            _ctx: ToolContext,
            args: serde_json::Value,
        ) -> Result<serde_json::Value> {
            let delay_ms = args["delay_ms"].as_u64().unwrap_or(0);
            tokio::time::sleep(Duration::from_millis(delay_ms)).await;
            Ok(json!({
                "tool": self.name,
                "delay_ms": delay_ms
            }))
        }
    }

    fn tool_call(name: &str, id: &str, delay_ms: u64) -> ToolCall {
        ToolCall {
            id: id.to_string(),
            type_field: "function".to_string(),
            function: ToolCallFunction {
                name: name.to_string(),
                arguments: json!({ "delay_ms": delay_ms }).to_string(),
            },
        }
    }

    #[tokio::test]
    async fn execute_pending_tool_calls_runs_parallel_safe_batches_concurrently() {
        let agent = AgentBuilder::new("parallel-agent")
            .system_prompt("test")
            .with_async_tools(vec![
                Arc::new(SleepTool {
                    name: "sleep_a",
                    concurrency: ToolConcurrency::ParallelSafe,
                }) as Arc<dyn AsyncTool>,
                Arc::new(SleepTool {
                    name: "sleep_b",
                    concurrency: ToolConcurrency::ParallelSafe,
                }) as Arc<dyn AsyncTool>,
            ])
            .enable_parallel_tool_calls(4)
            .build()
            .unwrap();

        let mut messages = Vec::new();
        let pending = vec![
            tool_call("sleep_a", "call-1", 80),
            tool_call("sleep_b", "call-2", 80),
        ];
        let consumer = crate::agent::streaming::MultiConsumer::new();
        let emitted = Arc::new(Mutex::new(std::collections::HashSet::new()));

        let started = Instant::now();
        let completed = execute_pending_tool_calls(
            &agent,
            "session-parallel",
            &pending,
            &mut messages,
            &consumer,
            &emitted,
        )
        .await
        .unwrap();
        let elapsed = started.elapsed();

        assert!(!completed);
        assert!(elapsed < Duration::from_millis(140));
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].tool_call_id.as_deref(), Some("call-1"));
        assert_eq!(messages[1].tool_call_id.as_deref(), Some("call-2"));
    }

    #[tokio::test]
    async fn execute_pending_tool_calls_serializes_mixed_batches() {
        let agent = AgentBuilder::new("serial-agent")
            .system_prompt("test")
            .with_async_tools(vec![
                Arc::new(SleepTool {
                    name: "sleep_parallel",
                    concurrency: ToolConcurrency::ParallelSafe,
                }) as Arc<dyn AsyncTool>,
                Arc::new(SleepTool {
                    name: "sleep_serial",
                    concurrency: ToolConcurrency::SerialOnly,
                }) as Arc<dyn AsyncTool>,
            ])
            .enable_parallel_tool_calls(4)
            .build()
            .unwrap();

        let mut messages = Vec::new();
        let pending = vec![
            tool_call("sleep_parallel", "call-1", 70),
            tool_call("sleep_serial", "call-2", 70),
        ];
        let consumer = crate::agent::streaming::MultiConsumer::new();
        let emitted = Arc::new(Mutex::new(std::collections::HashSet::new()));

        let started = Instant::now();
        execute_pending_tool_calls(
            &agent,
            "session-serial",
            &pending,
            &mut messages,
            &consumer,
            &emitted,
        )
        .await
        .unwrap();
        let elapsed = started.elapsed();

        assert!(elapsed >= Duration::from_millis(130));
        assert_eq!(messages[0].tool_call_id.as_deref(), Some("call-1"));
        assert_eq!(messages[1].tool_call_id.as_deref(), Some("call-2"));
    }
}