microclaw-engine 0.23.0

Channel-independent Agent Engine and default services for MicroClaw
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
//! Headless one-shot mode: `microclaw run -p "<prompt>"`.
//!
//! Runs a single prompt through the shared agent loop without starting any
//! channel, prints the final reply to stdout, and exits non-zero on failure
//! — the scripting/CI entry point (grok-build's headless mode equivalent).
//! Runs share the `headless` channel; `--session <name>` selects a named
//! chat so consecutive runs can keep conversation context.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use tokio::sync::{mpsc, RwLock};

use crate::agent_engine::{run_agent_turn, AgentEvent, AgentRequestContext, AgentTurn};
use crate::chat_turn_queue::PendingMessage;
use crate::config::Config;
use crate::hooks::HookManager;
use crate::internal::channels::channel_adapter::ChannelRegistry;
use crate::internal::runtime::{ExecutionContext, ExecutionResult, RunExecutor};
use crate::internal::storage::db::{call_blocking, Database, StoredMessage};
use crate::memory::MemoryManager;
use crate::memory_backend::{MemoryBackend, MemoryMcpClient};
use crate::runtime::AppState;
use crate::skill_management::{archive_skill, install_skill, SkillInstallOutcome};
use crate::skills::{SkillAvailability, SkillManager};
use crate::tools::ToolRegistry;
use crate::{embedding, llm};
use microclaw_core::run_protocol::{
    AgentProfile, RunRequest, RuntimeCapabilities, RuntimeControl, RuntimeError, RuntimeErrorCode,
    SessionId,
};
use microclaw_core::runtime_event::RuntimeEventEnvelope;

pub const HEADLESS_CHANNEL: &str = "headless";
pub const CODE_CHANNEL: &str = "code";
/// `RunRequest::metadata` key: `true` makes gated tool calls wait in-run for
/// `RuntimeControl::ResolveApproval` (see [`crate::approval_broker`]).
pub const INTERACTIVE_APPROVALS_KEY: &str = "interactive_approvals";

#[derive(Debug, Clone)]
pub struct HeadlessRunRequest {
    pub prompt: String,
    pub session: Option<String>,
    pub sender_name: String,
    pub run_id: Option<String>,
    pub caller_channel: String,
    /// `(base64, media type)` image attached to the prompt.
    pub image: Option<(String, String)>,
}

impl HeadlessRunRequest {
    pub fn cli(prompt: String, session: Option<String>) -> Self {
        Self {
            prompt,
            session,
            sender_name: "cli".into(),
            run_id: None,
            caller_channel: HEADLESS_CHANNEL.into(),
            image: None,
        }
    }

    pub fn code(prompt: String, session: Option<String>, run_id: String) -> Self {
        Self {
            prompt,
            session,
            sender_name: "code".into(),
            run_id: Some(run_id),
            caller_channel: CODE_CHANNEL.into(),
            image: None,
        }
    }
}

/// `RunRequest::metadata` key carrying an image for the prompt:
/// `{"media_type": "image/png", "data": "<base64>"}`.
pub const IMAGE_KEY: &str = "image";

fn image_from_metadata(
    metadata: &std::collections::BTreeMap<String, serde_json::Value>,
) -> Option<(String, String)> {
    let image = metadata.get(IMAGE_KEY)?;
    let data = image.get("data")?.as_str()?.to_string();
    let media_type = image.get("media_type")?.as_str()?.to_string();
    (!data.is_empty() && media_type.starts_with("image/")).then_some((data, media_type))
}

#[derive(Debug, Clone)]
pub struct HeadlessRunResult {
    pub run_id: String,
    pub chat_id: i64,
    pub response: String,
}

/// One stored message of an embedded session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessSessionMessage {
    /// `true` for the agent's replies, `false` for user prompts.
    pub from_agent: bool,
    pub content: String,
    pub timestamp: String,
}

/// One filesystem checkpoint of a session's working directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessCheckpoint {
    pub commit: String,
    pub label: String,
    pub timestamp: String,
}

/// Token usage of one session.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HeadlessUsage {
    pub requests: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
    /// `(model, requests, input_tokens, output_tokens)`, largest first.
    pub by_model: Vec<(String, i64, i64, i64)>,
}

/// Result of compacting a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessCompaction {
    pub messages_before: usize,
    pub messages_after: usize,
    pub tokens_before: usize,
    pub tokens_after: usize,
    /// `none`, `pruned`, `summarized` or `fallback`.
    pub method: String,
}

/// How full a session's context is (see [`HeadlessRuntime::context_usage`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessContextUsage {
    pub model: String,
    pub window: usize,
    pub reserved_output: usize,
    /// Tokens at which automatic compaction starts (0: disabled).
    pub auto_compact_threshold: usize,
    /// Input tokens of the session's last request, as reported by the
    /// provider (system prompt, tools and messages).
    pub last_request_tokens: Option<usize>,
    /// Estimated tokens of the stored conversation, by kind.
    pub conversation: crate::context_window::ContextBreakdown,
}

impl HeadlessContextUsage {
    /// Tokens the next request will carry: the last measured request, or
    /// the conversation estimate when there is none yet.
    pub fn used(&self) -> usize {
        self.last_request_tokens
            .unwrap_or_else(|| self.conversation.total())
            .max(self.conversation.total())
    }
}

/// UI-neutral projection of one durable Subagent run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeadlessSubagentRun {
    pub run_id: String,
    pub parent_run_id: Option<String>,
    pub depth: u32,
    pub label: Option<String>,
    pub task: String,
    pub status: String,
    pub progress: Option<String>,
    pub result: Option<String>,
    pub error: Option<String>,
    pub created_at: String,
    pub started_at: Option<String>,
    pub finished_at: Option<String>,
    pub cancel_requested: bool,
}

/// Reusable application service for one-shot tasks.
///
/// It owns the existing provider-neutral Agent Engine state but starts no
/// channel, Web server, or scheduler. Both `microclaw run` and MicroClaw Code call this
/// service instead of assembling or copying an Agent Loop.
#[derive(Clone)]
pub struct HeadlessRuntime {
    state: Arc<AppState>,
}

/// Adapter from the existing shared Agent Engine to the embeddable Runtime contract.
///
/// This is intentionally channel-free: the caller selects the logical channel used for policy,
/// persistence, cancellation, and steering. Product UIs consume `microclaw-engine` rather than
/// calling the Agent Engine directly.
pub struct HeadlessRunExecutor {
    runtime: HeadlessRuntime,
    caller_channel: String,
}

impl HeadlessRunExecutor {
    pub fn new(runtime: HeadlessRuntime, caller_channel: impl Into<String>) -> Self {
        Self {
            runtime,
            caller_channel: caller_channel.into(),
        }
    }
}

#[async_trait::async_trait]
impl RunExecutor for HeadlessRunExecutor {
    async fn execute(
        &self,
        profile: AgentProfile,
        request: RunRequest,
        mut context: ExecutionContext,
    ) -> Result<ExecutionResult, RuntimeError> {
        let session = request
            .session_id
            .clone()
            .unwrap_or_else(|| SessionId::new("default"));
        // Opt-in in-run approvals: while this guard lives, gated tool calls
        // wait for `RuntimeControl::ResolveApproval` instead of ending the
        // run with a text prompt.
        let interactive_approvals = request
            .metadata
            .get(INTERACTIVE_APPROVALS_KEY)
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        let approval_chat_id = if interactive_approvals {
            Some(
                self.runtime
                    .resolve_session_chat_id(session.as_str())
                    .await
                    .map_err(runtime_internal_error)?,
            )
        } else {
            None
        };
        let _approval_broker = approval_chat_id
            .map(|chat_id| crate::approval_broker::register(&self.caller_channel, chat_id));
        let (legacy_event_tx, mut legacy_event_rx) = mpsc::unbounded_channel();
        let run = self.runtime.run_with_profile(
            HeadlessRunRequest {
                image: image_from_metadata(&request.metadata),
                prompt: request.prompt,
                session: Some(session.to_string()),
                sender_name: self.caller_channel.clone(),
                run_id: Some(context.run_id().to_string()),
                caller_channel: self.caller_channel.clone(),
            },
            profile,
            Some(legacy_event_tx),
        );
        tokio::pin!(run);

        let result = loop {
            tokio::select! {
                result = &mut run => break result,
                event = legacy_event_rx.recv() => {
                    if let Some(envelope) = event {
                        forward_runtime_event(&context, envelope.event)?;
                    }
                }
                control = context.next_control_request() => {
                    if let Some(control) = control {
                        match control.control().clone() {
                        RuntimeControl::Cancel { .. } => {
                            let cancelled = self.runtime
                                .cancel_session_for_channel(&self.caller_channel, session.as_str())
                                .await
                                .map_err(runtime_internal_error)?;
                            if cancelled > 0 {
                                control.accept();
                            } else {
                                control.reject(RuntimeError {
                                    code: RuntimeErrorCode::Unavailable,
                                    message: "the run finished before cancellation was accepted".into(),
                                    retryable: false,
                                });
                            }
                        }
                        RuntimeControl::Steer { message, .. } => {
                            let accepted = self.runtime
                                .steer_session_for_channel(
                                    &self.caller_channel,
                                    session.as_str(),
                                    &message,
                                )
                                .await
                                .map_err(runtime_internal_error)?;
                            if accepted {
                                control.accept();
                            } else {
                                control.reject(RuntimeError {
                                    code: RuntimeErrorCode::Unavailable,
                                    message: "the run finished before the update could be queued".into(),
                                    retryable: false,
                                });
                            }
                        }
                        RuntimeControl::ResolveApproval { approval_id, decision, .. } => {
                            let Some(chat_id) = approval_chat_id else {
                                control.reject(RuntimeError {
                                    code: RuntimeErrorCode::Unavailable,
                                    message: format!(
                                        "in-run approvals are off for this run; set request metadata `{INTERACTIVE_APPROVALS_KEY}: true`"
                                    ),
                                    retryable: false,
                                });
                                continue;
                            };
                            let Some(decision) = crate::approval_broker::ApprovalDecision::parse(&decision) else {
                                control.reject(RuntimeError {
                                    code: RuntimeErrorCode::InvalidRequest,
                                    message: format!(
                                        "unknown approval decision `{decision}` (use 1/approve, 2/always, 3/deny or defer)"
                                    ),
                                    retryable: false,
                                });
                                continue;
                            };
                            if crate::approval_broker::resolve(
                                &self.caller_channel,
                                chat_id,
                                &approval_id,
                                decision,
                            ) {
                                control.accept();
                            } else {
                                control.reject(RuntimeError {
                                    code: RuntimeErrorCode::Unavailable,
                                    message: format!("no pending approval `{approval_id}`"),
                                    retryable: false,
                                });
                            }
                        }
                        }
                    }
                }
            }
        }
        .map_err(runtime_internal_error)?;

        while let Ok(envelope) = legacy_event_rx.try_recv() {
            forward_runtime_event(&context, envelope.event)?;
        }

        let mut output = ExecutionResult::new(session, result.response);
        output.metadata.insert(
            "chat_id".into(),
            serde_json::Value::Number(result.chat_id.into()),
        );
        Ok(output)
    }

    fn capabilities(&self) -> RuntimeCapabilities {
        RuntimeCapabilities {
            streaming: true,
            cancellation: true,
            steering: true,
            approvals: true,
            skills: true,
            subagents: true,
            remote_workers: false,
        }
    }
}

fn forward_runtime_event(
    context: &ExecutionContext,
    event: microclaw_core::runtime_event::RuntimeEvent,
) -> Result<(), RuntimeError> {
    if matches!(
        event,
        microclaw_core::runtime_event::RuntimeEvent::FinalResponse { .. }
            | microclaw_core::runtime_event::RuntimeEvent::Cancelled { .. }
    ) {
        return Ok(());
    }
    context.emit(event)
}

fn runtime_internal_error(error: impl std::fmt::Display) -> RuntimeError {
    RuntimeError {
        code: RuntimeErrorCode::Internal,
        message: error.to_string(),
        retryable: false,
    }
}

impl HeadlessRuntime {
    /// Return the Skills visible to this runtime, including availability diagnostics when
    /// requested. Embedding facades use this to present a catalog without exposing runtime state.
    pub fn skill_catalog(&self, include_unavailable: bool) -> Vec<SkillAvailability> {
        self.state
            .skills
            .discover_skills_with_status(include_unavailable)
    }

    /// Invalidate cached integrity verdicts and rebuild the runtime's Skill catalog.
    pub fn reload_skill_catalog(&self, include_unavailable: bool) -> Vec<SkillAvailability> {
        self.state.skills.reload();
        self.skill_catalog(include_unavailable)
    }

    /// Change runtime-scoped Skill enablement without rewriting the Skill package.
    pub fn set_skill_enabled(&self, name: &str, enabled: bool) -> Result<(), String> {
        self.state.skills.set_enabled(name, enabled)?;
        self.state.skills.reload();
        Ok(())
    }

    /// Install or update a Skill through the shared governed package path.
    pub async fn install_skill(&self, reference: &str) -> Result<SkillInstallOutcome, String> {
        install_skill(&self.state.config, &self.state.skills, reference).await
    }

    /// Recoverably remove a Skill and return its archive location.
    pub fn archive_skill(&self, name: &str) -> Result<std::path::PathBuf, String> {
        archive_skill(&self.state.skills, name)
    }

    /// List durable Subagent runs belonging to a named embedded session.
    pub fn subagent_runs(
        &self,
        session: &str,
        limit: usize,
    ) -> anyhow::Result<Vec<HeadlessSubagentRun>> {
        let external_chat_id = format!("headless:{}", session.trim());
        let Some(chat_id) = self
            .state
            .db
            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
        else {
            return Ok(Vec::new());
        };
        Ok(self
            .state
            .db
            .list_subagent_runs(chat_id, limit.clamp(1, 1_000))?
            .into_iter()
            .map(|run| HeadlessSubagentRun {
                run_id: run.run_id,
                parent_run_id: run.parent_run_id,
                depth: run.depth.max(0) as u32,
                label: run.label,
                task: run.task,
                status: run.status,
                progress: run.progress_text,
                result: run.result_text,
                error: run.error_text,
                created_at: run.created_at,
                started_at: run.started_at,
                finished_at: run.finished_at,
                cancel_requested: run.cancel_requested,
            })
            .collect())
    }

    /// The most recent `limit` stored messages of a named embedded session,
    /// oldest first: user prompts (including steering) and final replies.
    /// Empty for a session that never ran.
    pub fn session_messages(
        &self,
        session: &str,
        limit: usize,
    ) -> anyhow::Result<Vec<HeadlessSessionMessage>> {
        let external_chat_id = format!("headless:{}", session.trim());
        let Some(chat_id) = self
            .state
            .db
            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
        else {
            return Ok(Vec::new());
        };
        Ok(self
            .state
            .db
            .get_recent_messages(chat_id, limit.clamp(1, 10_000))?
            .into_iter()
            .map(|message| HeadlessSessionMessage {
                from_agent: message.is_from_bot,
                content: message.content,
                timestamp: message.timestamp,
            })
            .collect())
    }

    async fn existing_session_chat_id(&self, session: &str) -> anyhow::Result<Option<i64>> {
        let external_chat_id = format!("headless:{}", session.trim());
        let db = self.state.db.clone();
        Ok(call_blocking(db, move |db| {
            db.find_chat_id(HEADLESS_CHANNEL, &external_chat_id)
        })
        .await?)
    }

    fn checkpoint_paths(
        &self,
        channel: &str,
        chat_id: i64,
    ) -> anyhow::Result<(std::path::PathBuf, std::path::PathBuf)> {
        if !self.state.config.checkpoints_enabled {
            anyhow::bail!("checkpoints are disabled for this runtime");
        }
        let working_dir = crate::internal::tool_runtime::runtime::working_dir_for_context(
            Path::new(&self.state.config.working_dir),
            self.state.config.working_dir_isolation,
            channel,
            chat_id,
        );
        let shadow_root = std::path::PathBuf::from(&self.state.config.data_dir).join("checkpoints");
        let shadow_repo = crate::checkpoint::shadow_repo_path(&shadow_root, &working_dir);
        Ok((shadow_repo, working_dir))
    }

    /// Snapshot the session's working directory now and return the checkpoint
    /// that holds its current state (a new one, or the latest when nothing
    /// changed since). Requires `checkpoints_enabled`.
    pub async fn checkpoint_session(
        &self,
        channel: &str,
        session: &str,
        label: &str,
    ) -> anyhow::Result<Option<HeadlessCheckpoint>> {
        let chat_id = self.resolve_session_chat_id(session).await?;
        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
        crate::checkpoint::snapshot(&shadow_repo, &working_dir, label)
            .await
            .map_err(anyhow::Error::msg)?;
        Ok(crate::checkpoint::list(&shadow_repo, &working_dir, 1)
            .await
            .map_err(anyhow::Error::msg)?
            .into_iter()
            .next()
            .map(|c| HeadlessCheckpoint {
                commit: c.commit,
                label: c.label,
                timestamp: c.timestamp,
            }))
    }

    /// Recent checkpoints of the session's working directory, newest first.
    pub async fn session_checkpoints(
        &self,
        channel: &str,
        session: &str,
        limit: usize,
    ) -> anyhow::Result<Vec<HeadlessCheckpoint>> {
        let chat_id = self.resolve_session_chat_id(session).await?;
        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
        Ok(
            crate::checkpoint::list(&shadow_repo, &working_dir, limit.clamp(1, 500))
                .await
                .map_err(anyhow::Error::msg)?
                .into_iter()
                .map(|c| HeadlessCheckpoint {
                    commit: c.commit,
                    label: c.label,
                    timestamp: c.timestamp,
                })
                .collect(),
        )
    }

    /// Restore the session's working directory to `commit`. The current
    /// state is checkpointed first, so a restore can itself be undone.
    pub async fn restore_session_checkpoint(
        &self,
        channel: &str,
        session: &str,
        commit: &str,
    ) -> anyhow::Result<Option<HeadlessCheckpoint>> {
        let before = self
            .checkpoint_session(channel, session, &format!("before restoring {commit}"))
            .await?;
        let chat_id = self.resolve_session_chat_id(session).await?;
        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
        crate::checkpoint::restore(&shadow_repo, &working_dir, commit)
            .await
            .map_err(anyhow::Error::msg)?;
        Ok(before)
    }

    /// Token usage recorded for a session.
    pub async fn session_usage(&self, session: &str) -> anyhow::Result<HeadlessUsage> {
        let Some(chat_id) = self.existing_session_chat_id(session).await? else {
            return Ok(HeadlessUsage::default());
        };
        let db = self.state.db.clone();
        Ok(call_blocking(db, move |db| {
            let summary = db.get_llm_usage_summary(Some(chat_id))?;
            let by_model = db
                .get_llm_usage_by_model(Some(chat_id), None, Some(20))?
                .into_iter()
                .map(|m| (m.model, m.requests, m.input_tokens, m.output_tokens))
                .collect();
            Ok::<_, microclaw_core::error::MicroClawError>(HeadlessUsage {
                requests: summary.requests,
                input_tokens: summary.input_tokens,
                output_tokens: summary.output_tokens,
                by_model,
            })
        })
        .await?)
    }

    /// The model the next run of this session uses.
    pub async fn session_model(&self, channel: &str, session: &str) -> anyhow::Result<String> {
        let chat_id = self.resolve_session_chat_id(session).await?;
        Ok(
            crate::agent_engine::resolve_effective_provider_and_model(
                &self.state,
                channel,
                chat_id,
            )
            .await
            .1,
        )
    }

    /// Override the model for one session (`None` clears the override).
    /// Runtime-only, like `/model here`. Returns the effective model.
    pub async fn set_session_model(
        &self,
        channel: &str,
        session: &str,
        model: Option<&str>,
    ) -> anyhow::Result<String> {
        let chat_id = self.resolve_session_chat_id(session).await?;
        let key = crate::chat_commands::chat_scoped_override_key(channel, chat_id);
        {
            let mut overrides = self.state.llm_model_overrides.write().await;
            match model {
                Some(model) => {
                    let model = crate::config::normalize_model_name(model)
                        .ok_or_else(|| anyhow::anyhow!("invalid model name `{model}`"))?;
                    overrides.insert(key, model);
                }
                None => {
                    overrides.remove(&key);
                }
            }
        }
        self.session_model(channel, session).await
    }

    /// Summarize older messages of a session now (the same compaction a long
    /// session gets automatically, but always summarizing). `focus` steers
    /// what the summary keeps.
    pub async fn compact_session(
        &self,
        channel: &str,
        session: &str,
        keep_recent: usize,
        focus: Option<&str>,
    ) -> anyhow::Result<HeadlessCompaction> {
        let Some(chat_id) = self.existing_session_chat_id(session).await? else {
            anyhow::bail!("session `{session}` has no conversation yet");
        };
        let db = self.state.db.clone();
        let Some((json, _)) = call_blocking(db, move |db| db.load_session(chat_id)).await? else {
            anyhow::bail!("session `{session}` has no conversation yet");
        };
        let messages: Vec<microclaw_core::llm_types::Message> = serde_json::from_str(&json)?;
        let before = messages.len();
        crate::agent_engine::archive_conversation(
            &self.state.config.data_dir,
            channel,
            chat_id,
            &messages,
        );
        let outcome = crate::agent_engine::compact_conversation(
            &self.state,
            channel,
            chat_id,
            &messages,
            crate::agent_engine::CompactOptions {
                keep_recent: keep_recent.max(2),
                focus: focus.map(str::to_string),
                force_summary: true,
                target_tokens: None,
            },
        )
        .await;
        if outcome.changed() {
            let json = serde_json::to_string(&outcome.messages)?;
            let db = self.state.db.clone();
            call_blocking(db, move |db| db.save_session(chat_id, &json)).await?;
        }
        Ok(HeadlessCompaction {
            messages_before: before,
            messages_after: outcome.messages.len(),
            tokens_before: outcome.tokens_before,
            tokens_after: outcome.tokens_after,
            method: outcome.method.to_string(),
        })
    }

    /// How full a session's context is: the model's window and compaction
    /// threshold, the last request's size and where the conversation's
    /// tokens go.
    pub async fn context_usage(
        &self,
        channel: &str,
        session: &str,
    ) -> anyhow::Result<HeadlessContextUsage> {
        let model = self.session_model(channel, session).await?;
        let budget = crate::context_window::ContextBudget::for_model(&self.state.config, &model);
        let mut usage = HeadlessContextUsage {
            model: model.clone(),
            window: budget.window,
            reserved_output: budget.reserved_output,
            auto_compact_threshold: budget.threshold,
            last_request_tokens: None,
            conversation: Default::default(),
        };
        let Some(chat_id) = self.existing_session_chat_id(session).await? else {
            return Ok(usage);
        };
        let db = self.state.db.clone();
        let (stored, latest) = call_blocking(db, move |db| {
            Ok::<_, microclaw_core::error::MicroClawError>((
                db.load_session(chat_id)?,
                db.latest_agent_request(chat_id)?,
            ))
        })
        .await?;
        if let Some((json, _)) = stored {
            let messages: Vec<microclaw_core::llm_types::Message> =
                serde_json::from_str(&json).unwrap_or_default();
            usage.conversation = crate::context_window::breakdown(&messages);
        }
        usage.last_request_tokens = latest
            .filter(|(_, last_model)| last_model == &model)
            .map(|(tokens, _)| tokens.max(0) as usize);
        Ok(usage)
    }

    /// Copy a session's conversation (agent context and stored messages)
    /// into a new session. Fails when `to` already has a conversation.
    pub async fn fork_session(&self, from: &str, to: &str) -> anyhow::Result<()> {
        let Some(from_id) = self.existing_session_chat_id(from).await? else {
            anyhow::bail!("session `{from}` has no conversation to fork");
        };
        let to_id = self.resolve_session_chat_id(to).await?;
        let parent_key = format!("headless:{}", from.trim());
        let db = self.state.db.clone();
        call_blocking(db, move |db| {
            if db.load_session(to_id)?.is_some() {
                return Err(microclaw_core::error::MicroClawError::Config(
                    "the target session already has a conversation".into(),
                ));
            }
            for message in db.get_all_messages(from_id)? {
                db.store_message(&StoredMessage {
                    id: uuid::Uuid::new_v4().to_string(),
                    chat_id: to_id,
                    ..message
                })?;
            }
            if let Some((json, _)) = db.load_session(from_id)? {
                let fork_point = serde_json::from_str::<Vec<serde_json::Value>>(&json)
                    .map(|m| m.len() as i64)
                    .ok();
                db.save_session_with_meta(to_id, &json, Some(&parent_key), fork_point, None)?;
            }
            Ok(())
        })
        .await?;
        Ok(())
    }

    /// Start session `to` from a summary of session `from` focused on
    /// `goal` (the original session is unchanged). Returns the estimated
    /// tokens of the seeded context.
    pub async fn handoff_session(
        &self,
        channel: &str,
        from: &str,
        to: &str,
        goal: &str,
    ) -> anyhow::Result<usize> {
        let Some(from_id) = self.existing_session_chat_id(from).await? else {
            anyhow::bail!("session `{from}` has no conversation to hand off");
        };
        let db = self.state.db.clone();
        let Some((json, _)) = call_blocking(db, move |db| db.load_session(from_id)).await? else {
            anyhow::bail!("session `{from}` has no conversation to hand off");
        };
        let messages: Vec<microclaw_core::llm_types::Message> = serde_json::from_str(&json)?;
        let to_id = self.resolve_session_chat_id(to).await?;
        let previous = crate::context_window::previous_summary(&messages);
        let focus = format!(
            "Only what matters for the next task: {}. Leave out finished work that does not affect it.",
            goal.trim()
        );
        let mut summary = previous.clone();
        for chunk in crate::context_window::chunk_text(
            &crate::context_window::render_for_summary(&messages),
            60_000,
        ) {
            let request = crate::context_window::summary_request(
                summary.as_deref(),
                &chunk,
                Some(&focus),
                self.state.config.compact_instructions.as_deref(),
            );
            match crate::agent_engine::summarize_once(&self.state, channel, from_id, request).await
            {
                Ok(text) if !text.trim().is_empty() => summary = Some(text),
                _ => {
                    summary = Some(crate::context_window::fallback_summary(&messages));
                    break;
                }
            }
        }
        let summary = summary.unwrap_or_else(|| crate::context_window::fallback_summary(&messages));
        let mut text = crate::context_window::summary_message_text(&summary, &messages);
        text.push_str(&format!(
            "\n## Next task\n{}\n(This session was started from a handoff of session `{}`.)\n",
            goal.trim(),
            from.trim()
        ));
        let seeded = vec![
            microclaw_core::llm_types::Message {
                role: "user".into(),
                content: microclaw_core::llm_types::MessageContent::Text(text),
            },
            microclaw_core::llm_types::Message {
                role: "assistant".into(),
                content: microclaw_core::llm_types::MessageContent::Text(
                    "Understood. I have the handoff summary and the next task.".into(),
                ),
            },
        ];
        let tokens = crate::context_window::estimate_messages_tokens(&seeded);
        let json = serde_json::to_string(&seeded)?;
        let parent_key = format!("headless:{}", from.trim());
        let db = self.state.db.clone();
        call_blocking(db, move |db| {
            if db.load_session(to_id)?.is_some() {
                return Err(microclaw_core::error::MicroClawError::Config(
                    "the target session already has a conversation".into(),
                ));
            }
            db.save_session_with_meta(to_id, &json, Some(&parent_key), None, None)
        })
        .await?;
        Ok(tokens)
    }

    /// Persist and promptly signal cancellation for one Subagent owned by the session.
    pub fn cancel_subagent(&self, session: &str, run_id: &str) -> anyhow::Result<bool> {
        let external_chat_id = format!("headless:{}", session.trim());
        let Some(chat_id) = self
            .state
            .db
            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
        else {
            return Ok(false);
        };
        Ok(crate::tools::subagents::request_subagent_cancel(
            &self.state.config,
            &self.state.db,
            chat_id,
            run_id,
        )?)
    }

    /// Build a standalone runtime from a loaded product config.
    ///
    /// This is the Code/headless bootstrap path. It intentionally initializes
    /// no chat adapters, Web routes, scheduler, or gateway.
    pub async fn load(mut config: Config) -> anyhow::Result<Self> {
        let data_root = config.data_root_dir();
        let runtime_data_dir = config.runtime_data_dir();
        let skills_data_dir = config.skills_data_dir();
        crate::builtin_skills::ensure_builtin_skills(Path::new(&skills_data_dir))?;

        let db = Database::new(&runtime_data_dir)?;
        let memory = MemoryManager::new(&runtime_data_dir);
        let skills = SkillManager::from_skills_and_runtime(&skills_data_dir, &runtime_data_dir)
            .with_config_verification(&config);
        let mcp_manager = crate::mcp::McpManager::from_config_paths(
            &crate::mcp::collect_config_paths(&data_root),
            config.mcp_request_timeout_secs(),
        )
        .await;

        config.data_dir = runtime_data_dir;
        config.skills_dir = Some(skills_data_dir);
        Ok(Self::new(config, db, memory, skills, mcp_manager))
    }

    pub fn new(
        config: Config,
        db: Database,
        memory: MemoryManager,
        skills: SkillManager,
        mcp_manager: crate::mcp::McpManager,
    ) -> Self {
        let db = Arc::new(db);
        let llm = llm::create_provider(&config);
        let embedding = embedding::create_provider(&config);
        let channel_registry = Arc::new(ChannelRegistry::new());

        let memory_backend = Arc::new(MemoryBackend::new(
            db.clone(),
            MemoryMcpClient::discover(&mcp_manager),
            &config.data_dir,
        ));
        let mut tools = ToolRegistry::new(
            &config,
            channel_registry.clone(),
            db.clone(),
            memory_backend.clone(),
        );
        tools.register_mcp_tools(&mcp_manager);

        let chat_turn_queue = Arc::new(crate::chat_turn_queue::ChatTurnQueue::new(
            config.chat_turn_queue_max_pending,
        ));
        let (skill_review_queue, _skill_review_worker) =
            crate::skill_review::build_skill_review_channel();
        let state = Arc::new(AppState {
            config: config.clone(),
            channel_registry,
            db: db.clone(),
            memory: Arc::new(memory),
            skills: Arc::new(skills),
            hooks: Arc::new(HookManager::from_config(&config).with_db(db.clone())),
            llm: Arc::from(llm),
            llm_provider_overrides: Arc::new(RwLock::new(HashMap::new())),
            llm_model_overrides: Arc::new(RwLock::new(HashMap::new())),
            embedding,
            memory_backend,
            tools: Arc::new(tools),
            chat_turn_queue,
            skill_review_queue,
            metric_exporter: None,
            trace_exporter: None,
            log_exporter: None,
        });
        Self { state }
    }

    /// Build the public embeddable Runtime over this configured Agent Engine.
    pub fn into_embedded_runtime(
        self,
        caller_channel: impl Into<String>,
        max_concurrent_runs: usize,
    ) -> Result<crate::internal::runtime::Runtime, crate::internal::runtime::RuntimeBuildError>
    {
        crate::internal::runtime::Runtime::builder()
            .executor(HeadlessRunExecutor::new(self, caller_channel))
            .max_concurrent_runs(max_concurrent_runs)
            .build()
    }

    pub async fn run(
        &self,
        request: HeadlessRunRequest,
        event_tx: Option<mpsc::UnboundedSender<RuntimeEventEnvelope>>,
    ) -> anyhow::Result<HeadlessRunResult> {
        self.run_with_profile(request, AgentProfile::default(), event_tx)
            .await
    }

    pub async fn run_with_profile(
        &self,
        request: HeadlessRunRequest,
        profile: AgentProfile,
        event_tx: Option<mpsc::UnboundedSender<RuntimeEventEnvelope>>,
    ) -> anyhow::Result<HeadlessRunResult> {
        let session_name = request
            .session
            .clone()
            .unwrap_or_else(|| "default".to_string());
        let chat_id = self.resolve_session_chat_id(&session_name).await?;
        let caller_channel = request.caller_channel;

        let stored = StoredMessage {
            id: uuid::Uuid::new_v4().to_string(),
            chat_id,
            sender_name: request.sender_name,
            content: request.prompt,
            is_from_bot: false,
            timestamp: chrono::Utc::now().to_rfc3339(),
        };
        let _ = call_blocking(self.state.db.clone(), move |db| db.store_message(&stored)).await;

        let run_id = request
            .run_id
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let (raw_event_tx, bridge) = match event_tx {
            Some(envelope_tx) => {
                let (raw_tx, raw_rx) = mpsc::unbounded_channel();
                let bridge = spawn_event_envelope_bridge(run_id.clone(), raw_rx, envelope_tx);
                (Some(raw_tx), Some(bridge))
            }
            None => (None, None),
        };
        let response = run_agent_turn(
            &self.state,
            AgentTurn::new(AgentRequestContext {
                caller_channel: &caller_channel,
                chat_id,
                chat_type: "private",
            })
            .events(raw_event_tx.as_ref())
            .profile(profile)
            .image(request.image.clone()),
        )
        .await;
        drop(raw_event_tx);
        if let Some(bridge) = bridge {
            bridge.await?;
        }
        let response = response?;

        let bot_msg = StoredMessage {
            id: uuid::Uuid::new_v4().to_string(),
            chat_id,
            sender_name: "microclaw".to_string(),
            content: response.clone(),
            is_from_bot: true,
            timestamp: chrono::Utc::now().to_rfc3339(),
        };
        let _ = call_blocking(self.state.db.clone(), move |db| db.store_message(&bot_msg)).await;

        Ok(HeadlessRunResult {
            run_id,
            chat_id,
            response,
        })
    }

    /// Cancel active work for a named headless session.
    ///
    /// This delegates to the same run-control registry used by chat, Web, and
    /// scheduler adapters, so callers stop the real Agent Engine rather than
    /// merely hiding its output.
    pub async fn cancel_session(&self, session: &str) -> anyhow::Result<usize> {
        self.cancel_session_for_channel(HEADLESS_CHANNEL, session)
            .await
    }

    pub async fn cancel_code_session(&self, session: &str) -> anyhow::Result<usize> {
        self.cancel_session_for_channel(CODE_CHANNEL, session).await
    }

    async fn cancel_session_for_channel(
        &self,
        channel: &str,
        session: &str,
    ) -> anyhow::Result<usize> {
        let chat_id = self.resolve_session_chat_id(session).await?;
        Ok(crate::run_control::abort_runs(channel, chat_id).await)
    }

    /// Add a user update to an active named session.
    ///
    /// The shared Agent Engine drains this queue at its normal tool/end-turn
    /// breakpoints. Returning `false` means the run ended before the update
    /// could be queued; callers must not report it as accepted.
    pub async fn steer_session(&self, session: &str, content: &str) -> anyhow::Result<bool> {
        self.steer_session_for_channel(HEADLESS_CHANNEL, session, content)
            .await
    }

    pub async fn steer_code_session(&self, session: &str, content: &str) -> anyhow::Result<bool> {
        self.steer_session_for_channel(CODE_CHANNEL, session, content)
            .await
    }

    async fn steer_session_for_channel(
        &self,
        channel: &str,
        session: &str,
        content: &str,
    ) -> anyhow::Result<bool> {
        let content = content.trim();
        if content.is_empty() {
            anyhow::bail!("steering update must not be empty");
        }
        let chat_id = self.resolve_session_chat_id(session).await?;
        let message_id = uuid::Uuid::new_v4().to_string();
        let timestamp = chrono::Utc::now().to_rfc3339();
        let pending = PendingMessage {
            sender_name: "code".into(),
            content: content.to_string(),
            message_id: message_id.clone(),
            timestamp: timestamp.clone(),
        };
        if !self
            .state
            .chat_turn_queue
            .enqueue_if_busy(channel, chat_id, pending)
            .await
        {
            return Ok(false);
        }

        let stored = StoredMessage {
            id: message_id,
            chat_id,
            sender_name: "code".into(),
            content: content.to_string(),
            is_from_bot: false,
            timestamp,
        };
        call_blocking(self.state.db.clone(), move |db| db.store_message(&stored)).await?;
        Ok(true)
    }

    async fn resolve_session_chat_id(&self, session: &str) -> anyhow::Result<i64> {
        let external_chat_id = format!("headless:{session}");
        let title = format!("headless-{session}");
        Ok(call_blocking(self.state.db.clone(), move |db| {
            db.resolve_or_create_chat_id(
                HEADLESS_CHANNEL,
                &external_chat_id,
                Some(&title),
                "headless",
            )
        })
        .await?)
    }
}

fn spawn_event_envelope_bridge(
    run_id: String,
    mut raw_rx: mpsc::UnboundedReceiver<AgentEvent>,
    envelope_tx: mpsc::UnboundedSender<RuntimeEventEnvelope>,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut sequence = 0_u64;
        while let Some(event) = raw_rx.recv().await {
            sequence = sequence.saturating_add(1);
            if envelope_tx
                .send(RuntimeEventEnvelope::new(&run_id, sequence, event))
                .is_err()
            {
                break;
            }
        }
    })
}

#[allow(clippy::too_many_arguments)]
pub async fn run_once(
    config: Config,
    db: Database,
    memory: MemoryManager,
    skills: SkillManager,
    mcp_manager: crate::mcp::McpManager,
    prompt: String,
    session: Option<String>,
    json: bool,
) -> anyhow::Result<i32> {
    let runtime = HeadlessRuntime::new(config, db, memory, skills, mcp_manager)
        .into_embedded_runtime(HEADLESS_CHANNEL, 1)?;
    let mut request = RunRequest::new(prompt);
    request.session_id = session.map(SessionId::new);
    let result = runtime
        .agent(AgentProfile {
            name: "MicroClaw CLI".into(),
            ..AgentProfile::default()
        })
        .run(request)
        .result()
        .await;

    match result {
        Ok(result) => {
            let chat_id = result
                .metadata
                .get("chat_id")
                .and_then(serde_json::Value::as_i64);
            if json {
                println!(
                    "{}",
                    serde_json::json!({
                        "ok": true,
                        "response": result.final_text,
                        "chat_id": chat_id,
                        "run_id": result.run_id.to_string(),
                    })
                );
            } else {
                println!("{}", result.final_text);
            }
            Ok(0)
        }
        Err(e) => {
            if json {
                println!(
                    "{}",
                    serde_json::json!({"ok": false, "error": e.to_string()})
                );
            } else {
                eprintln!("Error: {e}");
            }
            Ok(1)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::WorkingDirIsolation;
    use crate::llm::LlmProvider;
    use microclaw_core::error::MicroClawError;
    use microclaw_core::llm_types::{
        Message, MessagesResponse, ResponseContentBlock, ToolDefinition,
    };
    use microclaw_core::runtime_event::RuntimeEvent;

    static RUNTIME_TEST_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
        std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));

    struct FakeLlm;

    struct SlowLlm;

    struct CapturingLlm {
        system_prompt: Arc<std::sync::Mutex<String>>,
    }

    struct ToolCapturingLlm {
        tools: Arc<std::sync::Mutex<Vec<String>>>,
    }

    struct SteeringLlm {
        calls: Arc<std::sync::atomic::AtomicUsize>,
        first_call_started: Arc<tokio::sync::Notify>,
        saw_update: Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl LlmProvider for FakeLlm {
        async fn send_message(
            &self,
            _system: &str,
            _messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text {
                    text: "real agent loop response".into(),
                }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    #[async_trait::async_trait]
    impl LlmProvider for SlowLlm {
        async fn send_message(
            &self,
            _system: &str,
            _messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            tokio::time::sleep(std::time::Duration::from_secs(30)).await;
            unreachable!("the cancellation test must stop the pending model call")
        }
    }

    #[async_trait::async_trait]
    impl LlmProvider for CapturingLlm {
        async fn send_message(
            &self,
            system: &str,
            _messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            *self.system_prompt.lock().unwrap() = system.to_string();
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text {
                    text: "profile applied".into(),
                }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    #[async_trait::async_trait]
    impl LlmProvider for ToolCapturingLlm {
        async fn send_message(
            &self,
            _system: &str,
            _messages: Vec<Message>,
            tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            *self.tools.lock().unwrap() = tools
                .unwrap_or_default()
                .into_iter()
                .map(|tool| tool.name)
                .collect();
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text {
                    text: "policy applied".into(),
                }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    #[async_trait::async_trait]
    impl LlmProvider for SteeringLlm {
        async fn send_message(
            &self,
            _system: &str,
            messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if call == 0 {
                self.first_call_started.notify_one();
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                return Ok(MessagesResponse {
                    content: vec![ResponseContentBlock::ToolUse {
                        id: "todo-read-1".into(),
                        name: "todo_read".into(),
                        input: serde_json::json!({}),
                        thought_signature: None,
                    }],
                    stop_reason: Some("tool_use".into()),
                    usage: None,
                });
            }
            let rendered = format!("{messages:?}");
            self.saw_update.store(
                rendered.contains("Focus on the parser first"),
                std::sync::atomic::Ordering::SeqCst,
            );
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text {
                    text: "steering applied".into(),
                }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    fn runtime_with_fake_llm(base: &Path) -> HeadlessRuntime {
        runtime_with_llm(base, Box::new(FakeLlm))
    }

    fn runtime_with_llm(base: &Path, llm: Box<dyn LlmProvider>) -> HeadlessRuntime {
        let runtime_dir = base.join("runtime");
        std::fs::create_dir_all(&runtime_dir).unwrap();
        let mut config = Config::test_defaults();
        config.data_dir = runtime_dir.display().to_string();
        config.working_dir = base.display().to_string();
        config.working_dir_isolation = WorkingDirIsolation::Shared;
        let runtime_dir = runtime_dir.display().to_string();
        let db = Arc::new(Database::new(&runtime_dir).unwrap());
        let memory_backend = Arc::new(MemoryBackend::local_only(db.clone()));
        let channel_registry = Arc::new(ChannelRegistry::new());
        HeadlessRuntime {
            state: Arc::new(AppState {
                config: config.clone(),
                channel_registry: channel_registry.clone(),
                db: db.clone(),
                memory: Arc::new(MemoryManager::new(&runtime_dir)),
                skills: Arc::new(SkillManager::from_skills_dir(&config.skills_data_dir())),
                hooks: Arc::new(HookManager::from_config(&config)),
                llm: Arc::from(llm),
                llm_provider_overrides: Arc::new(RwLock::new(HashMap::new())),
                llm_model_overrides: Arc::new(RwLock::new(HashMap::new())),
                embedding: None,
                memory_backend: memory_backend.clone(),
                tools: Arc::new(ToolRegistry::new(
                    &config,
                    channel_registry,
                    db,
                    memory_backend,
                )),
                chat_turn_queue: Arc::new(crate::chat_turn_queue::ChatTurnQueue::new(20)),
                skill_review_queue: crate::skill_review::build_skill_review_channel().0,
                metric_exporter: None,
                trace_exporter: None,
                log_exporter: None,
            }),
        }
    }

    #[tokio::test]
    async fn event_bridge_adds_stable_run_id_and_monotonic_sequence() {
        let (raw_tx, raw_rx) = mpsc::unbounded_channel();
        let (envelope_tx, mut envelope_rx) = mpsc::unbounded_channel();
        let bridge = spawn_event_envelope_bridge("work-run-1".into(), raw_rx, envelope_tx);

        raw_tx
            .send(RuntimeEvent::Iteration { iteration: 1 })
            .unwrap();
        raw_tx
            .send(RuntimeEvent::FinalResponse {
                text: "done".into(),
            })
            .unwrap();
        drop(raw_tx);
        bridge.await.unwrap();

        let first = envelope_rx.recv().await.unwrap();
        let second = envelope_rx.recv().await.unwrap();
        assert_eq!(first.run_id, "work-run-1");
        assert_eq!(first.sequence, 1);
        assert_eq!(second.run_id, "work-run-1");
        assert_eq!(second.sequence, 2);
        assert!(envelope_rx.recv().await.is_none());
    }

    #[tokio::test]
    async fn reusable_runtime_executes_real_agent_loop_and_emits_envelopes() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = runtime_with_fake_llm(directory.path());
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();

        let result = runtime
            .run(
                HeadlessRunRequest::code(
                    "answer through the shared loop".into(),
                    Some("work-test".into()),
                    "work-run-test".into(),
                ),
                Some(event_tx),
            )
            .await
            .unwrap();
        let mut events = Vec::new();
        while let Some(event) = event_rx.recv().await {
            events.push(event);
        }

        assert_eq!(result.run_id, "work-run-test");
        assert_eq!(result.response, "real agent loop response");
        assert!(!events.is_empty());
        assert!(events.iter().enumerate().all(|(index, envelope)| {
            envelope.run_id == "work-run-test" && envelope.sequence == index as u64 + 1
        }));
        assert!(events.iter().any(|envelope| matches!(
            envelope.event,
            RuntimeEvent::FinalResponse { ref text } if text == "real agent loop response"
        )));
    }

    #[tokio::test]
    async fn durable_subagents_are_observable_and_cancellable_through_headless_runtime() {
        use crate::storage::db::subagents::CreateSubagentRunParams;

        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = runtime_with_fake_llm(directory.path());
        let chat_id = runtime
            .resolve_session_chat_id("sdk-session")
            .await
            .unwrap();
        runtime
            .state
            .db
            .create_subagent_run(CreateSubagentRunParams {
                run_id: "delegated-1",
                parent_run_id: Some("main-1"),
                depth: 1,
                token_budget: 10_000,
                chat_id,
                caller_channel: HEADLESS_CHANNEL,
                task: "inspect the parser",
                context: "",
                provider: "test",
                model: "test",
                label: Some("parser review"),
            })
            .unwrap();

        let tasks = runtime.subagent_runs("sdk-session", 20).unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].parent_run_id.as_deref(), Some("main-1"));
        assert_eq!(tasks[0].depth, 1);
        assert_eq!(tasks[0].label.as_deref(), Some("parser review"));
        assert!(runtime
            .cancel_subagent("sdk-session", "delegated-1")
            .unwrap());
        assert!(runtime.subagent_runs("sdk-session", 20).unwrap()[0].cancel_requested);
    }

    #[tokio::test]
    async fn embedded_agent_profile_applies_prompt_and_selected_skills() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let captured = Arc::new(std::sync::Mutex::new(String::new()));
        let headless = runtime_with_llm(
            directory.path(),
            Box::new(CapturingLlm {
                system_prompt: captured.clone(),
            }),
        );
        let skill_dir = headless.state.skills.skills_dir().join("rust-review");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: rust-review\ndescription: Review Rust\n---\nCHECK_AGENT_SKILL_BODY\n",
        )
        .unwrap();
        let runtime = headless.into_embedded_runtime(CODE_CHANNEL, 1).unwrap();
        let profile = AgentProfile {
            name: "reviewer".into(),
            system_prompt: Some("CHECK_AGENT_PROFILE_PROMPT".into()),
            skills: vec!["rust-review".into()],
            ..AgentProfile::default()
        };

        let result = runtime
            .agent(profile)
            .run(RunRequest::new("review this crate"))
            .result()
            .await
            .unwrap();

        assert_eq!(result.final_text, "profile applied");
        let system = captured.lock().unwrap();
        assert!(system.contains("CHECK_AGENT_PROFILE_PROMPT"), "{system}");
        assert!(system.contains("CHECK_AGENT_SKILL_BODY"), "{system}");
    }

    #[tokio::test]
    async fn embedded_read_only_profile_hides_mutating_tools() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = runtime_with_llm(
            directory.path(),
            Box::new(ToolCapturingLlm {
                tools: captured.clone(),
            }),
        )
        .into_embedded_runtime(CODE_CHANNEL, 1)
        .unwrap();
        let profile = AgentProfile {
            name: "reviewer".into(),
            tool_policy: microclaw_core::run_protocol::ToolPolicy::ReadOnly,
            ..AgentProfile::default()
        };

        runtime
            .agent(profile)
            .run(RunRequest::new("inspect this project"))
            .result()
            .await
            .unwrap();

        let tools = captured.lock().unwrap();
        assert!(tools.iter().any(|name| name == "read_file"), "{tools:?}");
        assert!(!tools.iter().any(|name| name == "write_file"), "{tools:?}");
        assert!(!tools.iter().any(|name| name == "bash"), "{tools:?}");
    }

    #[tokio::test]
    async fn cancelling_a_headless_session_stops_the_real_agent_loop() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = Arc::new(runtime_with_llm(directory.path(), Box::new(SlowLlm)));
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let running_runtime = runtime.clone();
        let run = tokio::spawn(async move {
            running_runtime
                .run(
                    HeadlessRunRequest::code(
                        "wait for cancellation".into(),
                        Some("cancel-test".into()),
                        "cancel-run-test".into(),
                    ),
                    Some(event_tx),
                )
                .await
        });

        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                if runtime.cancel_code_session("cancel-test").await.unwrap() > 0 {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("run should register for cancellation");

        let result = tokio::time::timeout(std::time::Duration::from_secs(5), run)
            .await
            .expect("cancelled run should finish promptly")
            .unwrap()
            .unwrap();
        assert_eq!(result.response, crate::run_control::STOPPED_TEXT);

        let mut cancelled = false;
        while let Some(envelope) = event_rx.recv().await {
            cancelled |= matches!(envelope.event, RuntimeEvent::Cancelled { .. });
        }
        assert!(cancelled);
    }

    #[tokio::test]
    async fn steering_uses_the_active_agent_turn_queue() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = runtime_with_fake_llm(directory.path());
        let chat_id = runtime.resolve_session_chat_id("steer-test").await.unwrap();
        let turn = runtime
            .state
            .chat_turn_queue
            .acquire(HEADLESS_CHANNEL, chat_id)
            .await
            .unwrap();

        assert!(runtime
            .steer_session("steer-test", "Focus on the parser first")
            .await
            .unwrap());
        let pending = runtime
            .state
            .chat_turn_queue
            .drain_pending(HEADLESS_CHANNEL, chat_id)
            .await;
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].sender_name, "code");
        assert_eq!(pending[0].content, "Focus on the parser first");
        drop(turn);

        assert!(!runtime
            .steer_session("steer-test", "This run is already idle")
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn steering_reaches_the_real_agent_loop_after_a_tool_breakpoint() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let first_call_started = Arc::new(tokio::sync::Notify::new());
        let saw_update = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let runtime = Arc::new(runtime_with_llm(
            directory.path(),
            Box::new(SteeringLlm {
                calls: calls.clone(),
                first_call_started: first_call_started.clone(),
                saw_update: saw_update.clone(),
            }),
        ));
        let running_runtime = runtime.clone();
        let run = tokio::spawn(async move {
            running_runtime
                .run(
                    HeadlessRunRequest::code(
                        "Start with the whole task".into(),
                        Some("live-steer".into()),
                        "live-steer-run".into(),
                    ),
                    None,
                )
                .await
        });

        tokio::time::timeout(
            std::time::Duration::from_secs(5),
            first_call_started.notified(),
        )
        .await
        .expect("first model call should start");
        assert!(runtime
            .steer_code_session("live-steer", "Focus on the parser first")
            .await
            .unwrap());
        let result = run.await.unwrap().unwrap();

        assert_eq!(result.response, "steering applied");
        assert!(calls.load(std::sync::atomic::Ordering::SeqCst) >= 2);
        assert!(saw_update.load(std::sync::atomic::Ordering::SeqCst));
    }

    /// Calls `bash` once, then reports what the tool result said.
    struct ApprovalLlm {
        calls: Arc<std::sync::atomic::AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl LlmProvider for ApprovalLlm {
        async fn send_message(
            &self,
            _system: &str,
            messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if call == 0 {
                return Ok(MessagesResponse {
                    content: vec![ResponseContentBlock::ToolUse {
                        id: "bash-1".into(),
                        name: "bash".into(),
                        input: serde_json::json!({"command": "echo in-run-ok"}),
                        thought_signature: None,
                    }],
                    stop_reason: Some("tool_use".into()),
                    usage: None,
                });
            }
            let rendered = format!("{messages:?}");
            let text = if rendered.contains("denied this bash call") {
                "saw denial"
            } else if rendered.contains("in-run-ok") {
                "saw output"
            } else {
                "saw nothing"
            };
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text { text: text.into() }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    async fn run_with_in_run_answer(session: &str, answer: Option<&str>) -> (String, usize) {
        let directory = tempfile::tempdir().unwrap();
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let engine = runtime_with_llm(
            directory.path(),
            Box::new(ApprovalLlm {
                calls: calls.clone(),
            }),
        );
        let runtime = engine.into_embedded_runtime(CODE_CHANNEL, 1).unwrap();
        let mut request = RunRequest::new("run the command");
        request.session_id = Some(SessionId::new(session));
        if answer.is_some() {
            request.metadata.insert(
                INTERACTIVE_APPROVALS_KEY.into(),
                serde_json::Value::Bool(true),
            );
        }
        let mut run = runtime.agent(AgentProfile::default()).run(request);
        let controller = run.controller();
        let mut approvals = 0;
        tokio::time::timeout(std::time::Duration::from_secs(20), async {
            while let Some(envelope) = run.next_event().await {
                if let RuntimeEvent::ApprovalRequired { approval_id, .. } = envelope.event {
                    approvals += 1;
                    // Only the in-run request has a waiter; a deferral is
                    // followed by the text-path card.
                    if let Some(answer) = answer.filter(|_| approvals == 1) {
                        controller
                            .resolve_approval_confirmed(approval_id, answer)
                            .await
                            .unwrap();
                    }
                }
            }
        })
        .await
        .expect("run should finish");
        let result = run.result().await.unwrap();
        (result.final_text, approvals)
    }

    #[tokio::test]
    async fn in_run_approval_continues_the_same_run() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let (text, approvals) = run_with_in_run_answer("in-run-approve", Some("1")).await;
        assert_eq!(approvals, 1);
        assert_eq!(text, "saw output");
    }

    #[tokio::test]
    async fn in_run_denial_reaches_the_model_without_running_the_tool() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let (text, approvals) = run_with_in_run_answer("in-run-deny", Some("deny")).await;
        assert_eq!(approvals, 1);
        assert_eq!(text, "saw denial");
    }

    #[tokio::test]
    async fn a_deferred_approval_ends_the_run_with_the_text_prompt() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let (text, approvals) = run_with_in_run_answer("in-run-defer", Some("defer")).await;
        // The in-run request, then the text-path card that ends the run.
        assert_eq!(approvals, 2);
        assert!(text.contains("bash"), "{text}");
    }

    #[tokio::test]
    async fn without_the_opt_in_an_approval_still_ends_the_run() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let (text, approvals) = run_with_in_run_answer("text-approval", None).await;
        assert_eq!(approvals, 1);
        assert!(text.contains("bash"), "{text}");
        assert!(!crate::approval_broker::is_registered(CODE_CHANNEL, 1));
    }

    #[tokio::test]
    async fn sessions_fork_switch_models_and_compact() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = runtime_with_fake_llm(directory.path());
        runtime
            .run(
                HeadlessRunRequest::code("first".into(), Some("orig".into()), "r1".into()),
                None,
            )
            .await
            .unwrap();
        runtime.fork_session("orig", "copy").await.unwrap();
        let copied = runtime.session_messages("copy", 10).unwrap();
        assert_eq!(copied.len(), 2);
        assert_eq!(copied[0].content, "first");
        assert!(runtime.fork_session("orig", "copy").await.is_err());
        assert!(runtime.fork_session("missing", "x").await.is_err());

        let default_model = runtime.session_model(CODE_CHANNEL, "copy").await.unwrap();
        assert_eq!(
            runtime
                .set_session_model(CODE_CHANNEL, "copy", Some("other-model"))
                .await
                .unwrap(),
            "other-model"
        );
        assert_eq!(
            runtime.session_model(CODE_CHANNEL, "orig").await.unwrap(),
            default_model
        );
        assert_eq!(
            runtime
                .set_session_model(CODE_CHANNEL, "copy", None)
                .await
                .unwrap(),
            default_model
        );

        let short = runtime
            .compact_session(CODE_CHANNEL, "orig", 8, None)
            .await
            .unwrap();
        assert_eq!(short.messages_before, short.messages_after);
        assert!(runtime
            .compact_session(CODE_CHANNEL, "never-ran", 8, None)
            .await
            .is_err());
    }

    /// Answers agent turns with a fixed reply and summarization requests
    /// with a structured summary (or an error when `fail_summaries`).
    struct SummarizingLlm {
        summary_requests: Arc<std::sync::Mutex<Vec<String>>>,
        fail_summaries: bool,
    }

    #[async_trait::async_trait]
    impl LlmProvider for SummarizingLlm {
        async fn send_message(
            &self,
            system: &str,
            messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            let text = if system == crate::context_window::SUMMARY_SYSTEM_PROMPT {
                let request = messages
                    .iter()
                    .map(crate::agent_engine::message_to_text)
                    .collect::<Vec<_>>()
                    .join("\n");
                self.summary_requests.lock().unwrap().push(request);
                if self.fail_summaries {
                    return Err(MicroClawError::LlmApi("summarizer down".into()));
                }
                "## Goal and constraints\nSUMMARY-OK".to_string()
            } else {
                "done".to_string()
            };
            Ok(MessagesResponse {
                content: vec![ResponseContentBlock::Text { text }],
                stop_reason: Some("end_turn".into()),
                usage: None,
            })
        }
    }

    async fn run_turns(runtime: &HeadlessRuntime, session: &str, prompts: &[String]) {
        for (index, prompt) in prompts.iter().enumerate() {
            runtime
                .run(
                    HeadlessRunRequest::code(
                        prompt.clone(),
                        Some(session.into()),
                        format!("{session}-{index}"),
                    ),
                    None,
                )
                .await
                .unwrap();
        }
    }

    fn stored_session(runtime: &HeadlessRuntime, session: &str) -> Vec<Message> {
        let chat_id = runtime
            .state
            .db
            .find_chat_id(HEADLESS_CHANNEL, &format!("headless:{session}"))
            .ok()
            .flatten()
            .expect("session chat");
        let (json, _) = runtime.state.db.load_session(chat_id).unwrap().unwrap();
        serde_json::from_str(&json).unwrap()
    }

    #[tokio::test]
    async fn manual_compaction_summarizes_with_focus_and_keeps_user_words() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = runtime_with_llm(
            directory.path(),
            Box::new(SummarizingLlm {
                summary_requests: requests.clone(),
                fail_summaries: false,
            }),
        );
        let mut prompts = vec!["Rule: always use pnpm, never npm.".to_string()];
        prompts.extend((0..5).map(|i| format!("step {i}")));
        run_turns(&runtime, "long", &prompts).await;

        let usage = runtime.context_usage(CODE_CHANNEL, "long").await.unwrap();
        assert_eq!(usage.conversation.messages, 12);
        assert!(usage.window > 0 && usage.auto_compact_threshold > 0);

        let compaction = runtime
            .compact_session(CODE_CHANNEL, "long", 2, Some("the package manager"))
            .await
            .unwrap();
        assert_eq!(compaction.method, "summarized");
        assert!(compaction.messages_after < compaction.messages_before);
        let request = requests.lock().unwrap().last().cloned().unwrap();
        assert!(request.contains("the package manager"), "{request}");
        assert!(request.contains("## Goal and constraints"));

        let stored = stored_session(&runtime, "long");
        let first = crate::agent_engine::message_to_text(&stored[0]);
        assert!(first.starts_with(crate::context_window::SUMMARY_MARKER));
        assert!(first.contains("SUMMARY-OK"));
        assert!(first.contains("always use pnpm, never npm."), "{first}");

        // A second compaction builds on the first summary.
        run_turns(
            &runtime,
            "long",
            &["step 9".to_string(), "step 10".to_string()],
        )
        .await;
        runtime
            .compact_session(CODE_CHANNEL, "long", 2, None)
            .await
            .unwrap();
        let request = requests.lock().unwrap().last().cloned().unwrap();
        assert!(request.contains("The summary so far"), "{request}");
        assert!(request.contains("SUMMARY-OK"));
    }

    #[tokio::test]
    async fn handoff_seeds_a_new_session_from_a_focused_summary() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = runtime_with_llm(
            directory.path(),
            Box::new(SummarizingLlm {
                summary_requests: requests.clone(),
                fail_summaries: false,
            }),
        );
        run_turns(
            &runtime,
            "src",
            &["Use tabs in the Makefile.".to_string(), "step".to_string()],
        )
        .await;
        runtime
            .handoff_session(CODE_CHANNEL, "src", "next", "add a release target")
            .await
            .unwrap();
        let request = requests.lock().unwrap().last().cloned().unwrap();
        assert!(request.contains("add a release target"));
        let seeded = stored_session(&runtime, "next");
        assert_eq!(seeded.len(), 2);
        let text = crate::agent_engine::message_to_text(&seeded[0]);
        assert!(
            text.contains("## Next task\nadd a release target"),
            "{text}"
        );
        assert!(text.contains("Use tabs in the Makefile."));
        // The source session is unchanged and the target cannot be reused.
        assert_eq!(stored_session(&runtime, "src").len(), 4);
        assert!(runtime
            .handoff_session(CODE_CHANNEL, "src", "next", "again")
            .await
            .is_err());
    }

    /// Saves a checkpoint, takes a useless step, rewinds with a note, then
    /// answers; records the messages it was shown on its last call.
    struct RewindingLlm {
        calls: Arc<std::sync::atomic::AtomicUsize>,
        last_seen: Arc<std::sync::Mutex<Vec<Message>>>,
    }

    #[async_trait::async_trait]
    impl LlmProvider for RewindingLlm {
        async fn send_message(
            &self,
            _system: &str,
            messages: Vec<Message>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<MessagesResponse, MicroClawError> {
            let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            *self.last_seen.lock().unwrap() = messages;
            let tool = |id: &str, name: &str, input: serde_json::Value| MessagesResponse {
                content: vec![ResponseContentBlock::ToolUse {
                    id: id.into(),
                    name: name.into(),
                    input,
                    thought_signature: None,
                }],
                stop_reason: Some("tool_use".into()),
                usage: None,
            };
            Ok(match call {
                0 => tool("n1", "context_note", serde_json::json!({"note": "start"})),
                1 => tool("g1", "glob", serde_json::json!({"pattern": "**/*.nothing"})),
                2 => tool(
                    "r1",
                    "rewind_context",
                    serde_json::json!({"checkpoint": "cp-1", "note": "glob found nothing"}),
                ),
                _ => MessagesResponse {
                    content: vec![ResponseContentBlock::Text {
                        text: "done".into(),
                    }],
                    stop_reason: Some("end_turn".into()),
                    usage: None,
                },
            })
        }
    }

    #[tokio::test]
    async fn rewind_context_drops_steps_after_the_checkpoint() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let last_seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut runtime = runtime_with_llm(
            directory.path(),
            Box::new(RewindingLlm {
                calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                last_seen: last_seen.clone(),
            }),
        );
        Arc::get_mut(&mut runtime.state)
            .unwrap()
            .config
            .context_tools = true;
        let result = runtime
            .run(
                HeadlessRunRequest::code("find it".into(), Some("rw".into()), "rw-1".into()),
                None,
            )
            .await
            .unwrap();
        assert!(result.response.contains("done"), "{}", result.response);
        let seen = last_seen.lock().unwrap().clone();
        let text: Vec<String> = seen
            .iter()
            .map(crate::agent_engine::message_to_text)
            .collect();
        let joined = text.join("\n");
        assert!(
            !joined.contains("[tool_use: glob("),
            "the glob step should be gone: {joined}"
        );
        assert!(
            joined.contains("Note from your later self: glob found nothing"),
            "{joined}"
        );
        assert!(joined.contains("Checkpoint cp-1 saved"));
    }

    #[tokio::test]
    async fn an_attached_image_reaches_the_model() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let last_seen = Arc::new(std::sync::Mutex::new(Vec::new()));
        let runtime = runtime_with_llm(
            directory.path(),
            Box::new(RewindingLlm {
                // Starting past the scripted tool calls: answer directly.
                calls: Arc::new(std::sync::atomic::AtomicUsize::new(3)),
                last_seen: last_seen.clone(),
            }),
        );
        let mut request =
            HeadlessRunRequest::code("what is this?".into(), Some("img".into()), "img-1".into());
        request.image = Some(("iVBORw==".into(), "image/png".into()));
        runtime.run(request, None).await.unwrap();
        let seen = last_seen.lock().unwrap().clone();
        let has_image = seen.iter().any(|m| match &m.content {
            microclaw_core::llm_types::MessageContent::Blocks(blocks) => blocks.iter().any(|b| {
                matches!(b, microclaw_core::llm_types::ContentBlock::Image { source } if source.media_type == "image/png")
            }),
            microclaw_core::llm_types::MessageContent::Text(_) => false,
        });
        assert!(has_image, "{seen:?}");
        assert_eq!(
            image_from_metadata(&std::collections::BTreeMap::from([(
                IMAGE_KEY.to_string(),
                serde_json::json!({"media_type": "image/png", "data": "x"})
            )])),
            Some(("x".to_string(), "image/png".to_string()))
        );
    }

    #[tokio::test]
    async fn failed_summaries_fall_back_to_a_digest_instead_of_dropping_history() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let runtime = runtime_with_llm(
            directory.path(),
            Box::new(SummarizingLlm {
                summary_requests: Arc::new(std::sync::Mutex::new(Vec::new())),
                fail_summaries: true,
            }),
        );
        let mut prompts = vec!["Never touch the public API.".to_string()];
        prompts.extend((0..4).map(|i| format!("step {i}")));
        run_turns(&runtime, "fb", &prompts).await;
        let compaction = runtime
            .compact_session(CODE_CHANNEL, "fb", 2, None)
            .await
            .unwrap();
        assert_eq!(compaction.method, "fallback");
        let first = crate::agent_engine::message_to_text(&stored_session(&runtime, "fb")[0]);
        assert!(first.contains("Never touch the public API."), "{first}");
        assert!(first.contains("mechanical digest"), "{first}");
    }

    #[tokio::test]
    async fn sessions_compact_automatically_by_tokens() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let mut runtime = runtime_with_llm(
            directory.path(),
            Box::new(SummarizingLlm {
                summary_requests: Arc::new(std::sync::Mutex::new(Vec::new())),
                fail_summaries: false,
            }),
        );
        {
            let config = &mut Arc::get_mut(&mut runtime.state).unwrap().config;
            config.max_session_messages = 0;
            config.model_context_window = 6_000;
            config.max_tokens = 500;
            config.compact_keep_recent_tokens = 300;
        }
        // Each prompt is ~500 tokens; the window fills after a few turns.
        let prompts: Vec<String> = (0..8)
            .map(|i| format!("turn {i}: {}", "lorem ipsum dolor ".repeat(110)))
            .collect();
        run_turns(&runtime, "auto", &prompts).await;
        let stored = stored_session(&runtime, "auto");
        assert!(
            crate::context_window::is_summary_message(&stored[0]),
            "expected an automatic summary, got {} messages",
            stored.len()
        );
        assert!(stored.len() < 16);
    }

    #[tokio::test]
    async fn session_checkpoints_restore_the_workspace() {
        let _guard = RUNTIME_TEST_LOCK.lock().await;
        let directory = tempfile::tempdir().unwrap();
        let mut runtime = runtime_with_fake_llm(directory.path());
        Arc::get_mut(&mut runtime.state)
            .unwrap()
            .config
            .checkpoints_enabled = true;
        let workspace = directory.path().join("shared");
        std::fs::create_dir_all(&workspace).unwrap();
        std::fs::write(workspace.join("a.txt"), "one").unwrap();

        let first = runtime
            .checkpoint_session(CODE_CHANNEL, "cp", "start")
            .await
            .unwrap()
            .unwrap();
        // Nothing changed: the same checkpoint comes back.
        let again = runtime
            .checkpoint_session(CODE_CHANNEL, "cp", "again")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(again.commit, first.commit);

        std::fs::write(workspace.join("a.txt"), "two").unwrap();
        std::fs::write(workspace.join("b.txt"), "new").unwrap();
        let before = runtime
            .restore_session_checkpoint(CODE_CHANNEL, "cp", &first.commit)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(workspace.join("a.txt")).unwrap(),
            "one"
        );
        assert!(!workspace.join("b.txt").exists());
        // The state before the restore was kept and can be restored too.
        runtime
            .restore_session_checkpoint(CODE_CHANNEL, "cp", &before.commit)
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(workspace.join("a.txt")).unwrap(),
            "two"
        );
        assert!(workspace.join("b.txt").exists());
        assert!(
            runtime
                .session_checkpoints(CODE_CHANNEL, "cp", 10)
                .await
                .unwrap()
                .len()
                >= 3
        );
    }
}