github-copilot-sdk 1.0.0-beta.4

Rust SDK for programmatic control of the GitHub Copilot CLI via JSON-RPC. Technical preview, pre-1.0.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![cfg_attr(test, allow(clippy::unwrap_used))]

/// Bundled CLI binary extraction and caching.
pub mod embeddedcli;
/// Event handler traits for session lifecycle.
pub mod handler;
/// Lifecycle hook callbacks (pre/post tool use, prompt submission, session start/end).
pub mod hooks;
mod jsonrpc;
/// Permission-policy helpers that wrap an existing [`handler::SessionHandler`].
pub mod permission;
/// GitHub Copilot CLI binary resolution (env var, embedded, PATH search).
pub mod resolve;
mod router;
/// Session management — create, resume, send messages, and interact with the agent.
pub mod session;
/// Custom session filesystem provider (virtualizable filesystem layer).
pub mod session_fs;
mod session_fs_dispatch;
/// Event subscription handles returned by `subscribe()` methods.
pub mod subscription;
/// Typed tool definition framework and dispatch router.
pub mod tool;
/// W3C Trace Context propagation for distributed tracing.
pub mod trace_context;
/// System message transform callbacks for customizing agent prompts.
pub mod transforms;
/// Protocol types shared between the SDK and the GitHub Copilot CLI.
pub mod types;

/// Auto-generated protocol types from Copilot JSON Schemas.
pub mod generated;

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, OnceLock};
use std::time::Instant;

use async_trait::async_trait;
// JSON-RPC wire types are internal transport details (like Go SDK's internal/jsonrpc2/).
// External callers interact via Client/Session methods, not raw RPC.
pub(crate) use jsonrpc::{
    JsonRpcClient, JsonRpcError, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, error_codes,
};

/// Re-exported JSON-RPC internals for integration tests (requires `test-support` feature).
#[cfg(feature = "test-support")]
pub mod test_support {
    pub use crate::jsonrpc::{
        JsonRpcClient, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse,
        error_codes,
    };
}
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::net::TcpStream;
use tokio::process::{Child, Command};
use tokio::sync::{broadcast, mpsc, oneshot};
use tracing::{Instrument, debug, error, info, warn};
pub use types::*;

mod sdk_protocol_version;
pub use sdk_protocol_version::{SDK_PROTOCOL_VERSION, get_sdk_protocol_version};
pub use subscription::{EventSubscription, Lagged, LifecycleSubscription, RecvError};

/// Minimum protocol version this SDK can communicate with.
const MIN_PROTOCOL_VERSION: u32 = 2;

/// Errors returned by the SDK.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// JSON-RPC transport or protocol violation.
    #[error("protocol error: {0}")]
    Protocol(ProtocolError),

    /// The CLI returned a JSON-RPC error response.
    #[error("RPC error {code}: {message}")]
    Rpc {
        /// JSON-RPC error code.
        code: i32,
        /// Human-readable error message.
        message: String,
    },

    /// Session-scoped error (not found, agent error, timeout, etc.).
    #[error("session error: {0}")]
    Session(SessionError),

    /// I/O error on the stdio transport or during process spawn.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// Failed to serialize or deserialize a JSON-RPC message.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// A required binary was not found on the system.
    #[error("binary not found: {name} ({hint})")]
    BinaryNotFound {
        /// Binary name that was searched for.
        name: &'static str,
        /// Guidance on how to install or configure the binary.
        hint: &'static str,
    },

    /// Invalid combination of [`ClientOptions`] supplied to [`Client::start`].
    /// Surfaces consumer-side configuration errors that would otherwise
    /// produce confusing runtime failures (e.g. a connection token paired
    /// with stdio transport).
    #[error("invalid client configuration: {0}")]
    InvalidConfig(String),
}

impl Error {
    /// Returns true if this error indicates the transport is broken — the CLI
    /// process exited, the connection was lost, or an I/O failure occurred.
    /// Callers should discard the client and create a fresh one.
    pub fn is_transport_failure(&self) -> bool {
        matches!(
            self,
            Error::Protocol(ProtocolError::RequestCancelled) | Error::Io(_)
        )
    }
}

/// Aggregate of errors collected during [`Client::stop`].
///
/// `Client::stop` performs cooperative shutdown across every active
/// session before killing the CLI child process. Errors from any
/// per-session `session.destroy` RPC and from the terminal child-kill
/// step are collected here rather than short-circuiting on the first
/// failure, so callers see the full picture of what went wrong during
/// teardown.
///
/// Implements [`std::error::Error`] and forwards to `Display` for the
/// first error, with a count suffix when there are more.
#[derive(Debug)]
pub struct StopErrors(Vec<Error>);

impl StopErrors {
    /// Borrow the collected errors as a slice, in the order they
    /// occurred (per-session destroys first, then child-kill last).
    pub fn errors(&self) -> &[Error] {
        &self.0
    }

    /// Consume the aggregate and return the underlying error vector.
    pub fn into_errors(self) -> Vec<Error> {
        self.0
    }
}

impl std::fmt::Display for StopErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0.as_slice() {
            [] => write!(f, "stop completed with no errors"),
            [only] => write!(f, "stop failed: {only}"),
            [first, rest @ ..] => write!(
                f,
                "stop failed with {n} errors; first: {first}",
                n = 1 + rest.len(),
            ),
        }
    }
}

impl std::error::Error for StopErrors {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0
            .first()
            .map(|e| e as &(dyn std::error::Error + 'static))
    }
}

/// Specific protocol-level errors in the JSON-RPC transport or CLI lifecycle.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolError {
    /// Missing `Content-Length` header in a JSON-RPC message.
    #[error("missing Content-Length header")]
    MissingContentLength,

    /// Invalid `Content-Length` header value.
    #[error("invalid Content-Length value: \"{0}\"")]
    InvalidContentLength(String),

    /// A pending JSON-RPC request was cancelled (e.g. the response channel was dropped).
    #[error("request cancelled")]
    RequestCancelled,

    /// The CLI process did not report a listening port within the timeout.
    #[error("timed out waiting for CLI to report listening port")]
    CliStartupTimeout,

    /// The CLI process exited before reporting a listening port.
    #[error("CLI exited before reporting listening port")]
    CliStartupFailed,

    /// The CLI server's protocol version is outside the SDK's supported range.
    #[error("version mismatch: server={server}, supported={min}–{max}")]
    VersionMismatch {
        /// Version reported by the server.
        server: u32,
        /// Minimum version supported by this SDK.
        min: u32,
        /// Maximum version supported by this SDK.
        max: u32,
    },

    /// The CLI server's protocol version changed between calls.
    #[error("version changed: was {previous}, now {current}")]
    VersionChanged {
        /// Previously negotiated version.
        previous: u32,
        /// Newly reported version.
        current: u32,
    },
}

/// Session-scoped errors.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SessionError {
    /// The CLI could not find the requested session.
    #[error("session not found: {0}")]
    NotFound(SessionId),

    /// The CLI reported an error during agent execution (via `session.error` event).
    #[error("{0}")]
    AgentError(String),

    /// A `send_and_wait` call exceeded its timeout.
    #[error("timed out after {0:?}")]
    Timeout(std::time::Duration),

    /// `send` was called while a `send_and_wait` is in flight.
    #[error("cannot send while send_and_wait is in flight")]
    SendWhileWaiting,

    /// The session event loop exited before a pending `send_and_wait` completed.
    #[error("event loop closed before session reached idle")]
    EventLoopClosed,

    /// Elicitation is not supported by the host.
    /// Check `session.capabilities().ui.elicitation` before calling UI methods.
    #[error(
        "elicitation not supported by host — check session.capabilities().ui.elicitation first"
    )]
    ElicitationNotSupported,

    /// The client was started with [`ClientOptions::session_fs`] but this
    /// session was created without a [`SessionFsProvider`]. Set one via
    /// [`SessionConfig::with_session_fs_provider`] (or
    /// [`ResumeSessionConfig::with_session_fs_provider`]).
    #[error(
        "session was created on a client with session_fs configured but no SessionFsProvider was supplied"
    )]
    SessionFsProviderRequired,

    /// [`ClientOptions::session_fs`] was provided with empty or invalid
    /// fields. All of `initial_cwd` and `session_state_path` must be
    /// non-empty.
    #[error("invalid SessionFsConfig: {0}")]
    InvalidSessionFsConfig(String),

    /// The CLI returned a different session ID than the one the SDK registered.
    #[error("CLI returned session ID {returned} after SDK registered {requested}")]
    SessionIdMismatch {
        /// Session ID registered by the SDK before the RPC was sent.
        requested: SessionId,
        /// Session ID returned by the CLI.
        returned: SessionId,
    },
}

/// How the SDK communicates with the CLI server.
#[derive(Debug, Default)]
#[non_exhaustive]
pub enum Transport {
    /// Communicate over stdin/stdout pipes (default).
    #[default]
    Stdio,
    /// Spawn the CLI with `--port` and connect via TCP.
    Tcp {
        /// Port to listen on (0 for OS-assigned).
        port: u16,
    },
    /// Connect to an already-running CLI server (no process spawning).
    External {
        /// Hostname or IP of the running server.
        host: String,
        /// Port of the running server.
        port: u16,
    },
}

/// How the SDK locates the GitHub Copilot CLI binary.
#[derive(Debug, Clone, Default)]
pub enum CliProgram {
    /// Auto-resolve: `COPILOT_CLI_PATH` → embedded CLI → PATH + common locations.
    /// This is the default.
    #[default]
    Resolve,
    /// Use an explicit binary path (skips resolution).
    Path(PathBuf),
}

impl From<PathBuf> for CliProgram {
    fn from(path: PathBuf) -> Self {
        Self::Path(path)
    }
}

/// Options for starting a [`Client`].
///
/// When `program` is [`CliProgram::Resolve`] (the default),
/// [`Client::start`] automatically resolves the binary via
/// [`resolve::copilot_binary()`] — checking `COPILOT_CLI_PATH`, the
/// embedded CLI, and then the system PATH and common install locations.
///
/// Set `program` to [`CliProgram::Path`] to use an explicit binary.
#[non_exhaustive]
pub struct ClientOptions {
    /// How to locate the CLI binary.
    pub program: CliProgram,
    /// Arguments prepended before `--server` (e.g. the script path for node).
    pub prefix_args: Vec<OsString>,
    /// Working directory for the CLI process.
    pub cwd: PathBuf,
    /// Environment variables set on the child process.
    pub env: Vec<(OsString, OsString)>,
    /// Environment variable names to remove from the child process.
    pub env_remove: Vec<OsString>,
    /// Extra CLI flags appended after the transport-specific arguments.
    pub extra_args: Vec<String>,
    /// Transport mode used to communicate with the CLI server.
    pub transport: Transport,
    /// GitHub token for authentication. When set, the SDK passes the token
    /// to the CLI via `--auth-token-env COPILOT_SDK_AUTH_TOKEN` and exports
    /// the token in that env var. When set, the CLI defaults to *not*
    /// using the logged-in user (override with [`Self::use_logged_in_user`]).
    pub github_token: Option<String>,
    /// Whether the CLI should fall back to the logged-in `gh` user when no
    /// token is provided. `None` means use the runtime default (true unless
    /// [`Self::github_token`] is set, in which case false).
    pub use_logged_in_user: Option<bool>,
    /// Log level passed to the CLI server via `--log-level`. When `None`,
    /// the SDK uses [`LogLevel::Info`].
    pub log_level: Option<LogLevel>,
    /// Server-wide idle timeout for sessions, in seconds. When set to a
    /// positive value, the SDK passes `--session-idle-timeout <secs>` to
    /// the CLI; sessions without activity for this duration are
    /// automatically cleaned up. `None` or `Some(0)` leaves sessions
    /// running indefinitely (the CLI default).
    pub session_idle_timeout_seconds: Option<u64>,
    /// Optional override for [`Client::list_models`].
    ///
    /// When set, [`Client::list_models`] returns the handler's result
    /// without making a `models.list` RPC. This is the BYOK escape hatch
    /// for environments where the model catalog is provisioned separately
    /// from the GitHub Copilot CLI (e.g. external inference servers selected via
    /// [`Transport::External`]).
    pub on_list_models: Option<Arc<dyn ListModelsHandler>>,
    /// Custom session filesystem provider configuration.
    ///
    /// When set, the SDK calls `sessionFs.setProvider` during
    /// [`Client::start`] to register a virtualizable filesystem layer with
    /// the CLI. Each session created on this client must supply its own
    /// [`SessionFsProvider`] via
    /// [`SessionConfig::with_session_fs_provider`](crate::SessionConfig::with_session_fs_provider).
    pub session_fs: Option<SessionFsConfig>,
    /// Optional [`TraceContextProvider`] used to inject W3C Trace Context
    /// headers (`traceparent` / `tracestate`) on outbound `session.create`,
    /// `session.resume`, and `session.send` requests.
    ///
    /// When [`MessageOptions`] carries a per-turn override (set via
    /// [`MessageOptions::with_trace_context`](crate::types::MessageOptions::with_trace_context)
    /// or the underlying fields), it takes precedence over this provider.
    ///
    /// [`MessageOptions`]: crate::types::MessageOptions
    pub on_get_trace_context: Option<Arc<dyn TraceContextProvider>>,
    /// OpenTelemetry config forwarded to the spawned CLI process. See
    /// [`TelemetryConfig`] for the env-var mapping. The SDK takes no
    /// OpenTelemetry dependency — this is pure spawn-time env injection.
    pub telemetry: Option<TelemetryConfig>,
    /// Override the directory where the CLI persists its state (sessions,
    /// auth, telemetry buffers). When set, exported as `COPILOT_HOME` to
    /// the spawned CLI process. Useful for sandboxing test runs or
    /// running multiple isolated SDK instances side-by-side.
    pub copilot_home: Option<PathBuf>,
    /// Optional connection token for TCP transport. Sent to the CLI in
    /// the `connect` handshake and exported as `COPILOT_CONNECTION_TOKEN`
    /// to spawned CLI processes. Required when the CLI server was started
    /// with a token, ignored otherwise.
    ///
    /// When the SDK spawns its own CLI in TCP mode and this is left
    /// `None`, a UUID is generated automatically so the loopback listener
    /// is safe by default. Combining with [`Transport::Stdio`] is invalid
    /// and surfaces as an error from [`Client::start`].
    pub tcp_connection_token: Option<String>,
    /// Enable remote session support (Mission Control integration).
    /// When `true`, the SDK passes `--remote` to the spawned CLI process so
    /// sessions in a GitHub repository working directory are accessible from
    /// GitHub web and mobile. Ignored when connecting to an external server
    /// via [`Transport::External`].
    pub remote: bool,
}

impl std::fmt::Debug for ClientOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientOptions")
            .field("program", &self.program)
            .field("prefix_args", &self.prefix_args)
            .field("cwd", &self.cwd)
            .field("env", &self.env)
            .field("env_remove", &self.env_remove)
            .field("extra_args", &self.extra_args)
            .field("transport", &self.transport)
            .field(
                "github_token",
                &self.github_token.as_ref().map(|_| "<redacted>"),
            )
            .field("use_logged_in_user", &self.use_logged_in_user)
            .field("log_level", &self.log_level)
            .field(
                "session_idle_timeout_seconds",
                &self.session_idle_timeout_seconds,
            )
            .field(
                "on_list_models",
                &self.on_list_models.as_ref().map(|_| "<set>"),
            )
            .field("session_fs", &self.session_fs)
            .field(
                "on_get_trace_context",
                &self.on_get_trace_context.as_ref().map(|_| "<set>"),
            )
            .field("telemetry", &self.telemetry)
            .field("copilot_home", &self.copilot_home)
            .field(
                "tcp_connection_token",
                &self.tcp_connection_token.as_ref().map(|_| "<redacted>"),
            )
            .field("remote", &self.remote)
            .finish()
    }
}

/// Custom handler for [`Client::list_models`].
///
/// Implementations override the default `models.list` RPC, returning a
/// caller-supplied catalog of models. Set via [`ClientOptions::on_list_models`].
///
/// Implementations must be `Send + Sync` because [`Client`] is shared across
/// tasks. Errors returned by [`list_models`](Self::list_models) are propagated
/// from [`Client::list_models`] unchanged.
#[async_trait]
pub trait ListModelsHandler: Send + Sync + 'static {
    /// Return the list of available models.
    async fn list_models(&self) -> Result<Vec<Model>, Error>;
}

/// Log verbosity for the CLI server (passed via `--log-level`).
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Suppress all CLI logs.
    None,
    /// Errors only.
    Error,
    /// Warnings and errors.
    Warning,
    /// Default. Info and above.
    Info,
    /// Debug, info, warnings, errors.
    Debug,
    /// Everything, including trace output.
    All,
}

impl LogLevel {
    /// CLI argument value (e.g. `"info"`, `"debug"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Info => "info",
            Self::Debug => "debug",
            Self::All => "all",
        }
    }
}

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

/// Backend exporter for the CLI's OpenTelemetry pipeline.
///
/// Maps to the `COPILOT_OTEL_EXPORTER_TYPE` environment variable on the
/// spawned CLI process. Wire values are `"otlp-http"` and `"file"`.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum OtelExporterType {
    /// Export via OTLP HTTP to the endpoint configured by
    /// [`TelemetryConfig::otlp_endpoint`].
    OtlpHttp,
    /// Export to a JSON-lines file at the path configured by
    /// [`TelemetryConfig::file_path`].
    File,
}

impl OtelExporterType {
    /// Environment-variable value (`"otlp-http"` or `"file"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::OtlpHttp => "otlp-http",
            Self::File => "file",
        }
    }
}

/// OpenTelemetry configuration forwarded to the spawned GitHub Copilot CLI
/// process.
///
/// When [`ClientOptions::telemetry`] is `Some(...)`, the SDK sets
/// `COPILOT_OTEL_ENABLED=true` plus any populated fields below as the
/// corresponding `OTEL_*` / `COPILOT_OTEL_*` environment variables. The
/// CLI's built-in OpenTelemetry exporter consumes these at startup. The
/// SDK itself takes no OpenTelemetry dependency.
///
/// Environment-variable mapping:
///
/// | Field                | Variable                                              |
/// |----------------------|-------------------------------------------------------|
/// | (any field set)      | `COPILOT_OTEL_ENABLED=true`                           |
/// | [`otlp_endpoint`]    | `OTEL_EXPORTER_OTLP_ENDPOINT`                         |
/// | [`file_path`]        | `COPILOT_OTEL_FILE_EXPORTER_PATH`                     |
/// | [`exporter_type`]    | `COPILOT_OTEL_EXPORTER_TYPE`                          |
/// | [`source_name`]      | `COPILOT_OTEL_SOURCE_NAME`                            |
/// | [`capture_content`]  | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`  |
///
/// Caller-supplied entries in [`ClientOptions::env`] override these, so a
/// developer can pin any individual variable to a different value while
/// keeping the rest of the config managed by [`TelemetryConfig`].
///
/// Marked `#[non_exhaustive]` so future CLI-side telemetry knobs can be
/// added without breaking callers.
///
/// [`otlp_endpoint`]: Self::otlp_endpoint
/// [`file_path`]: Self::file_path
/// [`exporter_type`]: Self::exporter_type
/// [`source_name`]: Self::source_name
/// [`capture_content`]: Self::capture_content
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct TelemetryConfig {
    /// OTLP HTTP endpoint URL for trace/metric export.
    pub otlp_endpoint: Option<String>,
    /// File path for JSON-lines trace output.
    pub file_path: Option<PathBuf>,
    /// Exporter backend type. Typically [`OtelExporterType::OtlpHttp`] or
    /// [`OtelExporterType::File`].
    pub exporter_type: Option<OtelExporterType>,
    /// Instrumentation scope name. Useful for distinguishing this
    /// embedder's traces from other Copilot-CLI consumers exporting to the
    /// same backend.
    pub source_name: Option<String>,
    /// Whether the CLI captures GenAI message content (prompts and
    /// responses) on emitted spans. `Some(true)` opts in; `Some(false)`
    /// opts out; `None` leaves the CLI default (typically off).
    pub capture_content: Option<bool>,
}

impl TelemetryConfig {
    /// Construct an empty [`TelemetryConfig`]; all fields default to
    /// unset (`is_empty()` returns `true`).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the OTLP HTTP endpoint URL for trace/metric export.
    pub fn with_otlp_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.otlp_endpoint = Some(endpoint.into());
        self
    }

    /// Set the file path for JSON-lines trace output.
    pub fn with_file_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.file_path = Some(path.into());
        self
    }

    /// Set the exporter backend type.
    pub fn with_exporter_type(mut self, exporter_type: OtelExporterType) -> Self {
        self.exporter_type = Some(exporter_type);
        self
    }

    /// Set the instrumentation scope name. Useful for distinguishing
    /// this embedder's traces from other Copilot-CLI consumers
    /// exporting to the same backend.
    pub fn with_source_name(mut self, source_name: impl Into<String>) -> Self {
        self.source_name = Some(source_name.into());
        self
    }

    /// Opt in or out of GenAI message content capture on emitted spans.
    /// `true` opts in; `false` opts out. Leaving this unset preserves
    /// the CLI default (typically off).
    pub fn with_capture_content(mut self, capture: bool) -> Self {
        self.capture_content = Some(capture);
        self
    }

    /// Returns `true` if all fields are unset. Used by [`Client::start`]
    /// to decide whether to set `COPILOT_OTEL_ENABLED`.
    pub fn is_empty(&self) -> bool {
        self.otlp_endpoint.is_none()
            && self.file_path.is_none()
            && self.exporter_type.is_none()
            && self.source_name.is_none()
            && self.capture_content.is_none()
    }
}

impl Default for ClientOptions {
    fn default() -> Self {
        Self {
            program: CliProgram::Resolve,
            prefix_args: Vec::new(),
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            env: Vec::new(),
            env_remove: Vec::new(),
            extra_args: Vec::new(),
            transport: Transport::default(),
            github_token: None,
            use_logged_in_user: None,
            log_level: None,
            session_idle_timeout_seconds: None,
            on_list_models: None,
            session_fs: None,
            on_get_trace_context: None,
            telemetry: None,
            copilot_home: None,
            tcp_connection_token: None,
            remote: false,
        }
    }
}

impl ClientOptions {
    /// Construct a new [`ClientOptions`] with default values.
    ///
    /// Equivalent to [`ClientOptions::default`]; provided as a documented
    /// construction entry point for the builder chain. The struct is
    /// `#[non_exhaustive]`, so external callers cannot use struct-literal
    /// syntax — use this builder or [`Default::default`] plus mut-let.
    ///
    /// # Example
    ///
    /// ```
    /// # use github_copilot_sdk::{ClientOptions, LogLevel};
    /// let opts = ClientOptions::new()
    ///     .with_log_level(LogLevel::Debug)
    ///     .with_github_token("ghp_…");
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// How to locate the CLI binary. See [`CliProgram`].
    pub fn with_program(mut self, program: impl Into<CliProgram>) -> Self {
        self.program = program.into();
        self
    }

    /// Arguments prepended before `--server` (e.g. the script path for node).
    pub fn with_prefix_args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        self.prefix_args = args.into_iter().map(Into::into).collect();
        self
    }

    /// Working directory for the CLI process.
    pub fn with_cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.cwd = cwd.into();
        self
    }

    /// Environment variables to set on the child process.
    pub fn with_env<I, K, V>(mut self, env: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<OsString>,
        V: Into<OsString>,
    {
        self.env = env.into_iter().map(|(k, v)| (k.into(), v.into())).collect();
        self
    }

    /// Environment variable names to remove from the child process.
    pub fn with_env_remove<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        self.env_remove = names.into_iter().map(Into::into).collect();
        self
    }

    /// Extra CLI flags appended after the transport-specific arguments.
    pub fn with_extra_args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.extra_args = args.into_iter().map(Into::into).collect();
        self
    }

    /// Transport mode used to communicate with the CLI server. See [`Transport`].
    pub fn with_transport(mut self, transport: Transport) -> Self {
        self.transport = transport;
        self
    }

    /// GitHub token for authentication. The SDK passes the token to the
    /// CLI via `--auth-token-env COPILOT_SDK_AUTH_TOKEN`.
    pub fn with_github_token(mut self, token: impl Into<String>) -> Self {
        self.github_token = Some(token.into());
        self
    }

    /// Whether the CLI should fall back to the logged-in `gh` user when
    /// no token is provided. See the field docs for default semantics.
    pub fn with_use_logged_in_user(mut self, use_logged_in: bool) -> Self {
        self.use_logged_in_user = Some(use_logged_in);
        self
    }

    /// Log level passed to the CLI server via `--log-level`.
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.log_level = Some(level);
        self
    }

    /// Server-wide idle timeout for sessions (seconds). Pass `0` to leave
    /// sessions running indefinitely (the CLI default).
    pub fn with_session_idle_timeout_seconds(mut self, seconds: u64) -> Self {
        self.session_idle_timeout_seconds = Some(seconds);
        self
    }

    /// Override [`Client::list_models`] with a caller-supplied handler.
    /// The handler is wrapped in `Arc` internally.
    pub fn with_list_models_handler<H>(mut self, handler: H) -> Self
    where
        H: ListModelsHandler + 'static,
    {
        self.on_list_models = Some(Arc::new(handler));
        self
    }

    /// Custom session filesystem provider configuration.
    pub fn with_session_fs(mut self, config: SessionFsConfig) -> Self {
        self.session_fs = Some(config);
        self
    }

    /// Set the [`TraceContextProvider`] used to inject W3C Trace Context
    /// headers on outbound `session.create` / `session.resume` /
    /// `session.send` requests. The provider is wrapped in `Arc` internally.
    pub fn with_trace_context_provider<P>(mut self, provider: P) -> Self
    where
        P: TraceContextProvider + 'static,
    {
        self.on_get_trace_context = Some(Arc::new(provider));
        self
    }

    /// OpenTelemetry config forwarded to the spawned CLI process.
    pub fn with_telemetry(mut self, config: TelemetryConfig) -> Self {
        self.telemetry = Some(config);
        self
    }

    /// Override the directory where the CLI persists its state. Set as
    /// `COPILOT_HOME` on the spawned CLI process.
    pub fn with_copilot_home(mut self, home: impl Into<PathBuf>) -> Self {
        self.copilot_home = Some(home.into());
        self
    }

    /// Set the connection token for TCP transport. Sent in the `connect`
    /// handshake and exported as `COPILOT_CONNECTION_TOKEN` to spawned
    /// CLI processes.
    pub fn with_tcp_connection_token(mut self, token: impl Into<String>) -> Self {
        self.tcp_connection_token = Some(token.into());
        self
    }

    /// Enable remote session support (Mission Control). Passes `--remote`
    /// to the spawned CLI process.
    pub fn with_remote(mut self, enabled: bool) -> Self {
        self.remote = enabled;
        self
    }
}

/// Validate a [`SessionFsConfig`] before sending `sessionFs.setProvider`.
fn validate_session_fs_config(cfg: &SessionFsConfig) -> Result<(), Error> {
    if cfg.initial_cwd.trim().is_empty() {
        return Err(Error::Session(SessionError::InvalidSessionFsConfig(
            "initial_cwd must not be empty".to_string(),
        )));
    }
    if cfg.session_state_path.trim().is_empty() {
        return Err(Error::Session(SessionError::InvalidSessionFsConfig(
            "session_state_path must not be empty".to_string(),
        )));
    }
    Ok(())
}

/// Generate a fresh CSPRNG-backed token for authenticating an SDK-spawned
/// loopback CLI server. 128 bits of entropy, lowercase-hex encoded — not
/// a UUID (the schema-shaped IDs in this crate stay `String` per the
/// pre-1.0 review consensus, so adopting a `Uuid` type just for SDK-
/// generated secrets would be inconsistent and semantically misleading;
/// this is opaque random data, not an identifier).
fn generate_connection_token() -> String {
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes)
        .expect("OS CSPRNG (getrandom) is unavailable; cannot generate connection token");
    let mut hex = String::with_capacity(32);
    for byte in bytes {
        use std::fmt::Write;
        let _ = write!(hex, "{byte:02x}");
    }
    hex
}

/// Connection to a GitHub Copilot CLI server (stdio, TCP, or external).
///
/// Cheaply cloneable — cloning shares the underlying connection.
/// The child process (if any) is killed when the last clone drops.
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("cwd", &self.inner.cwd)
            .field("pid", &self.pid())
            .finish()
    }
}

struct ClientInner {
    child: parking_lot::Mutex<Option<Child>>,
    rpc: JsonRpcClient,
    cwd: PathBuf,
    request_rx: parking_lot::Mutex<Option<mpsc::UnboundedReceiver<JsonRpcRequest>>>,
    notification_tx: broadcast::Sender<JsonRpcNotification>,
    router: router::SessionRouter,
    negotiated_protocol_version: OnceLock<u32>,
    state: parking_lot::Mutex<ConnectionState>,
    lifecycle_tx: broadcast::Sender<SessionLifecycleEvent>,
    on_list_models: Option<Arc<dyn ListModelsHandler>>,
    models_cache: parking_lot::Mutex<Arc<tokio::sync::OnceCell<Vec<Model>>>>,
    session_fs_configured: bool,
    on_get_trace_context: Option<Arc<dyn TraceContextProvider>>,
    /// Token sent in the `connect` handshake. Auto-generated when the
    /// SDK spawns its own CLI in TCP mode and no explicit token is set;
    /// `None` for stdio and for external-server transport without an
    /// explicit token.
    effective_connection_token: Option<String>,
}

impl Client {
    /// Start a CLI server process with the given options.
    ///
    /// For [`Transport::Stdio`], spawns the CLI with `--stdio` and communicates
    /// over stdin/stdout pipes. For [`Transport::Tcp`], spawns with `--port`
    /// and connects via TCP once the server reports it is listening. For
    /// [`Transport::External`], connects to an already-running server.
    ///
    /// After establishing the connection, calls [`verify_protocol_version`](Self::verify_protocol_version)
    /// to ensure the CLI server speaks a compatible protocol version.
    /// When [`ClientOptions::session_fs`] is set, also calls
    /// `sessionFs.setProvider` to register the SDK as the filesystem
    /// backend.
    pub async fn start(options: ClientOptions) -> Result<Self, Error> {
        let start_time = Instant::now();
        if let Some(cfg) = &options.session_fs {
            validate_session_fs_config(cfg)?;
        }
        // Auth options only make sense when the SDK spawns the CLI; with an
        // external server, the server manages its own auth.
        if matches!(options.transport, Transport::External { .. }) {
            if options.github_token.is_some() {
                return Err(Error::InvalidConfig(
                    "github_token cannot be used with Transport::External \
                     (external server manages its own auth)"
                        .to_string(),
                ));
            }
            if options.use_logged_in_user == Some(true) {
                return Err(Error::InvalidConfig(
                    "use_logged_in_user cannot be used with Transport::External \
                     (external server manages its own auth)"
                        .to_string(),
                ));
            }
        }
        // Validate token + transport combination. Stdio cannot use a
        // connection token; auto-generate a UUID when the SDK spawns
        // its own CLI in TCP mode and no explicit token was set.
        if let Some(token) = &options.tcp_connection_token {
            if token.is_empty() {
                return Err(Error::InvalidConfig(
                    "tcp_connection_token must be a non-empty string".to_string(),
                ));
            }
            if matches!(options.transport, Transport::Stdio) {
                return Err(Error::InvalidConfig(
                    "tcp_connection_token cannot be used with Transport::Stdio".to_string(),
                ));
            }
        }
        let effective_connection_token: Option<String> = match &options.transport {
            Transport::Stdio => None,
            Transport::Tcp { .. } => Some(
                options
                    .tcp_connection_token
                    .clone()
                    .unwrap_or_else(generate_connection_token),
            ),
            Transport::External { .. } => options.tcp_connection_token.clone(),
        };
        let mut options = options;
        if matches!(options.transport, Transport::Tcp { .. })
            && options.tcp_connection_token.is_none()
        {
            // Auto-generated tokens flow to the spawned CLI via env, so
            // make the field reflect what we'll actually send.
            options.tcp_connection_token = effective_connection_token.clone();
        }
        let session_fs_config = options.session_fs.clone();
        let program = match &options.program {
            CliProgram::Path(path) => {
                info!(path = %path.display(), "using explicit copilot CLI path");
                path.clone()
            }
            CliProgram::Resolve => {
                let resolved = resolve::copilot_binary()?;
                info!(path = %resolved.display(), "resolved copilot CLI");
                #[cfg(windows)]
                {
                    if let Some(ext) = resolved.extension().and_then(|e| e.to_str()).filter(|ext| {
                        ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")
                    }) {
                        warn!(
                            path = %resolved.display(),
                            ext = %ext,
                            "resolved copilot CLI is a .cmd/.bat wrapper; \
                             this may cause console window flashes on Windows"
                        );
                    }
                }
                resolved
            }
        };

        let client = match options.transport {
            Transport::External { ref host, port } => {
                info!(host = %host, port = %port, "connecting to external CLI server");
                let connect_start = Instant::now();
                let stream = TcpStream::connect((host.as_str(), port)).await?;
                debug!(
                    elapsed_ms = connect_start.elapsed().as_millis(),
                    host = %host,
                    port,
                    "Client::start TCP connect complete"
                );
                let (reader, writer) = tokio::io::split(stream);
                Self::from_transport(
                    reader,
                    writer,
                    None,
                    options.cwd,
                    options.on_list_models,
                    session_fs_config.is_some(),
                    options.on_get_trace_context,
                    effective_connection_token.clone(),
                )?
            }
            Transport::Tcp { port } => {
                let (mut child, actual_port) = Self::spawn_tcp(&program, &options, port).await?;
                let connect_start = Instant::now();
                let stream = TcpStream::connect(("127.0.0.1", actual_port)).await?;
                debug!(
                    elapsed_ms = connect_start.elapsed().as_millis(),
                    port = actual_port,
                    "Client::start TCP connect complete"
                );
                let (reader, writer) = tokio::io::split(stream);
                Self::drain_stderr(&mut child);
                Self::from_transport(
                    reader,
                    writer,
                    Some(child),
                    options.cwd,
                    options.on_list_models,
                    session_fs_config.is_some(),
                    options.on_get_trace_context,
                    effective_connection_token.clone(),
                )?
            }
            Transport::Stdio => {
                let mut child = Self::spawn_stdio(&program, &options)?;
                let stdin = child.stdin.take().expect("stdin is piped");
                let stdout = child.stdout.take().expect("stdout is piped");
                Self::drain_stderr(&mut child);
                Self::from_transport(
                    stdout,
                    stdin,
                    Some(child),
                    options.cwd,
                    options.on_list_models,
                    session_fs_config.is_some(),
                    options.on_get_trace_context,
                    effective_connection_token.clone(),
                )?
            }
        };

        debug!(
            elapsed_ms = start_time.elapsed().as_millis(),
            "Client::start transport setup complete"
        );
        client.verify_protocol_version().await?;
        debug!(
            elapsed_ms = start_time.elapsed().as_millis(),
            "Client::start protocol verification complete"
        );
        if let Some(cfg) = session_fs_config {
            let session_fs_start = Instant::now();
            let request = crate::generated::api_types::SessionFsSetProviderRequest {
                conventions: cfg.conventions.into_wire(),
                initial_cwd: cfg.initial_cwd,
                session_state_path: cfg.session_state_path,
            };
            client.rpc().session_fs().set_provider(request).await?;
            debug!(
                elapsed_ms = session_fs_start.elapsed().as_millis(),
                "Client::start session filesystem setup complete"
            );
        }
        debug!(
            elapsed_ms = start_time.elapsed().as_millis(),
            "Client::start complete"
        );
        Ok(client)
    }

    /// Create a Client from raw async streams (no child process).
    ///
    /// Useful for testing or connecting to a server over a custom transport.
    pub fn from_streams(
        reader: impl AsyncRead + Unpin + Send + 'static,
        writer: impl AsyncWrite + Unpin + Send + 'static,
        cwd: PathBuf,
    ) -> Result<Self, Error> {
        Self::from_transport(reader, writer, None, cwd, None, false, None, None)
    }

    /// Construct a [`Client`] from raw streams with a
    /// [`TraceContextProvider`] preset, for integration testing.
    ///
    /// Mirrors [`from_streams`](Self::from_streams) but exposes the
    /// `on_get_trace_context` plumbing so tests can verify outbound
    /// `traceparent` / `tracestate` injection on `session.create`,
    /// `session.resume`, and `session.send`.
    #[cfg(any(test, feature = "test-support"))]
    pub fn from_streams_with_trace_provider(
        reader: impl AsyncRead + Unpin + Send + 'static,
        writer: impl AsyncWrite + Unpin + Send + 'static,
        cwd: PathBuf,
        provider: Arc<dyn TraceContextProvider>,
    ) -> Result<Self, Error> {
        Self::from_transport(reader, writer, None, cwd, None, false, Some(provider), None)
    }

    /// Construct a [`Client`] from raw streams with a preset
    /// `effective_connection_token`, for integration testing the
    /// `connect` handshake's token-forwarding path.
    #[cfg(any(test, feature = "test-support"))]
    pub fn from_streams_with_connection_token(
        reader: impl AsyncRead + Unpin + Send + 'static,
        writer: impl AsyncWrite + Unpin + Send + 'static,
        cwd: PathBuf,
        token: Option<String>,
    ) -> Result<Self, Error> {
        Self::from_transport(reader, writer, None, cwd, None, false, None, token)
    }

    /// Public test-only wrapper around the random connection-token
    /// generator used by [`Client::start`] when the SDK spawns a TCP
    /// server without an explicit token. Lets integration tests
    /// validate the token shape (32-char lowercase hex, 128 bits of
    /// entropy) without re-implementing the helper.
    #[cfg(any(test, feature = "test-support"))]
    pub fn generate_connection_token_for_test() -> String {
        generate_connection_token()
    }

    #[allow(clippy::too_many_arguments)]
    fn from_transport(
        reader: impl AsyncRead + Unpin + Send + 'static,
        writer: impl AsyncWrite + Unpin + Send + 'static,
        child: Option<Child>,
        cwd: PathBuf,
        on_list_models: Option<Arc<dyn ListModelsHandler>>,
        session_fs_configured: bool,
        on_get_trace_context: Option<Arc<dyn TraceContextProvider>>,
        effective_connection_token: Option<String>,
    ) -> Result<Self, Error> {
        let setup_start = Instant::now();
        let (request_tx, request_rx) = mpsc::unbounded_channel::<JsonRpcRequest>();
        let (notification_broadcast_tx, _) = broadcast::channel::<JsonRpcNotification>(1024);
        let rpc = JsonRpcClient::new(
            writer,
            reader,
            notification_broadcast_tx.clone(),
            request_tx,
        );

        let pid = child.as_ref().and_then(|c| c.id());
        info!(pid = ?pid, "copilot CLI client ready");

        let client = Self {
            inner: Arc::new(ClientInner {
                child: parking_lot::Mutex::new(child),
                rpc,
                cwd,
                request_rx: parking_lot::Mutex::new(Some(request_rx)),
                notification_tx: notification_broadcast_tx,
                router: router::SessionRouter::new(),
                negotiated_protocol_version: OnceLock::new(),
                state: parking_lot::Mutex::new(ConnectionState::Connected),
                lifecycle_tx: broadcast::channel(256).0,
                on_list_models,
                models_cache: parking_lot::Mutex::new(Arc::new(tokio::sync::OnceCell::new())),
                session_fs_configured,
                on_get_trace_context,
                effective_connection_token,
            }),
        };
        client.spawn_lifecycle_dispatcher();
        debug!(
            elapsed_ms = setup_start.elapsed().as_millis(),
            pid = ?pid,
            "Client::from_transport setup complete"
        );
        Ok(client)
    }

    /// Spawn the background task that re-broadcasts `session.lifecycle`
    /// notifications via [`ClientInner::lifecycle_tx`] to subscribers
    /// returned by [`Self::subscribe_lifecycle`].
    fn spawn_lifecycle_dispatcher(&self) {
        let inner = Arc::clone(&self.inner);
        let mut notif_rx = inner.notification_tx.subscribe();
        tokio::spawn(async move {
            loop {
                match notif_rx.recv().await {
                    Ok(notification) => {
                        if notification.method != "session.lifecycle" {
                            continue;
                        }
                        let Some(params) = notification.params.as_ref() else {
                            continue;
                        };
                        let event: SessionLifecycleEvent =
                            match serde_json::from_value(params.clone()) {
                                Ok(e) => e,
                                Err(e) => {
                                    warn!(
                                        error = %e,
                                        "failed to deserialize session.lifecycle notification"
                                    );
                                    continue;
                                }
                            };
                        // `send` only errors when there are no subscribers — that's
                        // the normal case before any consumer calls subscribe_lifecycle.
                        let _ = inner.lifecycle_tx.send(event);
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                        warn!(missed = n, "lifecycle dispatcher lagged");
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
        });
    }

    fn build_command(program: &Path, options: &ClientOptions) -> Command {
        let mut command = Command::new(program);
        for arg in &options.prefix_args {
            command.arg(arg);
        }
        // Inject the SDK auth token first so explicit `env` / `env_remove`
        // entries can override or strip it.
        if let Some(token) = &options.github_token {
            command.env("COPILOT_SDK_AUTH_TOKEN", token);
        }
        // Inject telemetry env vars before user env so callers can still
        // override individual variables via `options.env`.
        if let Some(telemetry) = &options.telemetry {
            command.env("COPILOT_OTEL_ENABLED", "true");
            if let Some(endpoint) = &telemetry.otlp_endpoint {
                command.env("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);
            }
            if let Some(path) = &telemetry.file_path {
                command.env("COPILOT_OTEL_FILE_EXPORTER_PATH", path);
            }
            if let Some(exporter) = telemetry.exporter_type {
                command.env("COPILOT_OTEL_EXPORTER_TYPE", exporter.as_str());
            }
            if let Some(source) = &telemetry.source_name {
                command.env("COPILOT_OTEL_SOURCE_NAME", source);
            }
            if let Some(capture) = telemetry.capture_content {
                command.env(
                    "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
                    if capture { "true" } else { "false" },
                );
            }
        }
        if let Some(home) = &options.copilot_home {
            command.env("COPILOT_HOME", home);
        }
        if let Some(token) = &options.tcp_connection_token {
            command.env("COPILOT_CONNECTION_TOKEN", token);
        }
        for (key, value) in &options.env {
            command.env(key, value);
        }
        for key in &options.env_remove {
            command.env_remove(key);
        }
        command
            .current_dir(&options.cwd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            const CREATE_NO_WINDOW: u32 = 0x08000000;
            command.as_std_mut().creation_flags(CREATE_NO_WINDOW);
        }

        command
    }

    /// Returns the CLI auth flags derived from [`ClientOptions::github_token`]
    /// and [`ClientOptions::use_logged_in_user`].
    ///
    /// When a token is set, adds `--auth-token-env COPILOT_SDK_AUTH_TOKEN`.
    /// When the effective `use_logged_in_user` is `false` (either explicitly
    /// or because a token was provided without an override), adds
    /// `--no-auto-login`.
    fn auth_args(options: &ClientOptions) -> Vec<&'static str> {
        let mut args: Vec<&'static str> = Vec::new();
        if options.github_token.is_some() {
            args.push("--auth-token-env");
            args.push("COPILOT_SDK_AUTH_TOKEN");
        }
        let use_logged_in = options
            .use_logged_in_user
            .unwrap_or(options.github_token.is_none());
        if !use_logged_in {
            args.push("--no-auto-login");
        }
        args
    }

    /// Returns `--session-idle-timeout <secs>` when
    /// [`ClientOptions::session_idle_timeout_seconds`] is `Some(n)` with
    /// `n > 0`. Otherwise returns an empty vector.
    fn session_idle_timeout_args(options: &ClientOptions) -> Vec<String> {
        match options.session_idle_timeout_seconds {
            Some(secs) if secs > 0 => {
                vec!["--session-idle-timeout".to_string(), secs.to_string()]
            }
            _ => Vec::new(),
        }
    }

    fn remote_args(options: &ClientOptions) -> Vec<String> {
        if options.remote {
            vec!["--remote".to_string()]
        } else {
            Vec::new()
        }
    }

    fn spawn_stdio(program: &Path, options: &ClientOptions) -> Result<Child, Error> {
        info!(cwd = ?options.cwd, program = %program.display(), "spawning copilot CLI (stdio)");
        let mut command = Self::build_command(program, options);
        let log_level = options.log_level.unwrap_or(LogLevel::Info);
        command
            .args([
                "--server",
                "--stdio",
                "--no-auto-update",
                "--log-level",
                log_level.as_str(),
            ])
            .args(Self::auth_args(options))
            .args(Self::session_idle_timeout_args(options))
            .args(Self::remote_args(options))
            .args(&options.extra_args)
            .stdin(Stdio::piped());
        let spawn_start = Instant::now();
        let child = command.spawn()?;
        debug!(
            elapsed_ms = spawn_start.elapsed().as_millis(),
            "Client::spawn_stdio subprocess spawned"
        );
        Ok(child)
    }

    async fn spawn_tcp(
        program: &Path,
        options: &ClientOptions,
        port: u16,
    ) -> Result<(Child, u16), Error> {
        info!(cwd = ?options.cwd, program = %program.display(), port = %port, "spawning copilot CLI (tcp)");
        let mut command = Self::build_command(program, options);
        let log_level = options.log_level.unwrap_or(LogLevel::Info);
        command
            .args([
                "--server",
                "--port",
                &port.to_string(),
                "--no-auto-update",
                "--log-level",
                log_level.as_str(),
            ])
            .args(Self::auth_args(options))
            .args(Self::session_idle_timeout_args(options))
            .args(Self::remote_args(options))
            .args(&options.extra_args)
            .stdin(Stdio::null());
        let spawn_start = Instant::now();
        let mut child = command.spawn()?;
        debug!(
            elapsed_ms = spawn_start.elapsed().as_millis(),
            "Client::spawn_tcp subprocess spawned"
        );
        let stdout = child.stdout.take().expect("stdout is piped");

        let (port_tx, port_rx) = oneshot::channel::<u16>();
        let span = tracing::error_span!("copilot_cli_port_scan");
        tokio::spawn(
            async move {
                // Scan stdout for the port announcement.
                let port_re = regex::Regex::new(r"listening on port (\d+)").expect("valid regex");
                let mut lines = BufReader::new(stdout).lines();
                let mut port_tx = Some(port_tx);
                while let Ok(Some(line)) = lines.next_line().await {
                    debug!(line = %line, "CLI stdout");
                    if let Some(tx) = port_tx.take() {
                        if let Some(caps) = port_re.captures(&line)
                            && let Some(p) =
                                caps.get(1).and_then(|m| m.as_str().parse::<u16>().ok())
                        {
                            let _ = tx.send(p);
                            continue;
                        }
                        // Not the port line — put tx back
                        port_tx = Some(tx);
                    }
                }
            }
            .instrument(span),
        );

        let port_wait_start = Instant::now();
        let actual_port = tokio::time::timeout(std::time::Duration::from_secs(10), port_rx)
            .await
            .map_err(|_| Error::Protocol(ProtocolError::CliStartupTimeout))?
            .map_err(|_| Error::Protocol(ProtocolError::CliStartupFailed))?;

        debug!(
            elapsed_ms = port_wait_start.elapsed().as_millis(),
            port = actual_port,
            "Client::spawn_tcp TCP port wait complete"
        );
        info!(port = %actual_port, "CLI server listening");
        Ok((child, actual_port))
    }

    fn drain_stderr(child: &mut Child) {
        if let Some(stderr) = child.stderr.take() {
            let span = tracing::error_span!("copilot_cli");
            tokio::spawn(
                async move {
                    let mut reader = BufReader::new(stderr).lines();
                    while let Ok(Some(line)) = reader.next_line().await {
                        warn!(line = %line, "CLI stderr");
                    }
                }
                .instrument(span),
            );
        }
    }

    /// Returns the working directory of the CLI process.
    pub fn cwd(&self) -> &PathBuf {
        &self.inner.cwd
    }

    /// Typed RPC namespace for server-level methods.
    ///
    /// Every protocol method lives here under its schema-aligned path —
    /// e.g. `client.rpc().models().list()`. Wire method names and request/
    /// response types are generated from the protocol schema, so the typed
    /// namespace can't drift from the wire contract.
    ///
    /// The hand-authored helpers on [`Client`] delegate to this namespace
    /// and remain the recommended entry point for everyday use; reach for
    /// `rpc()` when you want a method without a hand-written wrapper.
    pub fn rpc(&self) -> crate::generated::rpc::ClientRpc<'_> {
        crate::generated::rpc::ClientRpc { client: self }
    }

    /// Send a JSON-RPC request and wait for the response.
    pub(crate) async fn send_request(
        &self,
        method: &str,
        params: Option<serde_json::Value>,
    ) -> Result<JsonRpcResponse, Error> {
        self.inner.rpc.send_request(method, params).await
    }

    /// Send a JSON-RPC request, check for errors, and return the result value.
    ///
    /// This is the primary method for session-level RPC calls. It wraps
    /// the internal send/receive cycle with error checking so callers
    /// don't need to inspect the response manually.
    ///
    /// # Cancel safety
    ///
    /// **Cancel-safe.** The frame is committed to the wire via the
    /// writer-actor task before the future yields; cancelling the await
    /// (via `tokio::time::timeout`, `select!`, or dropped JoinHandle)
    /// drops the response oneshot but does not desync the transport.
    /// The pending-requests entry is cleaned up by an RAII guard.
    /// However, the call's *side effect* on the CLI may still occur —
    /// the CLI receives the request and processes it; the caller just
    /// won't see the response. For idempotent methods this is fine; for
    /// non-idempotent methods (e.g. `session.create`) the caller should
    /// avoid wrapping the call in a timeout shorter than the expected
    /// CLI processing window.
    pub async fn call(
        &self,
        method: &str,
        params: Option<serde_json::Value>,
    ) -> Result<serde_json::Value, Error> {
        let session_id: Option<SessionId> = params
            .as_ref()
            .and_then(|p| p.get("sessionId"))
            .and_then(|v| v.as_str())
            .map(SessionId::from);
        let response = self.send_request(method, params).await?;
        if let Some(err) = response.error {
            if err.message.contains("Session not found") {
                return Err(Error::Session(SessionError::NotFound(
                    session_id.unwrap_or_else(|| "unknown".into()),
                )));
            }
            return Err(Error::Rpc {
                code: err.code,
                message: err.message,
            });
        }
        Ok(response.result.unwrap_or(serde_json::Value::Null))
    }

    /// Send a JSON-RPC response back to the CLI (e.g. for permission or tool call requests).
    pub(crate) async fn send_response(&self, response: &JsonRpcResponse) -> Result<(), Error> {
        self.inner.rpc.write(response).await
    }

    /// Take the receiver for incoming JSON-RPC requests from the CLI.
    ///
    /// Can only be called once — subsequent calls return `None`.
    #[expect(dead_code, reason = "reserved for future pub(crate) use")]
    pub(crate) fn take_request_rx(&self) -> Option<mpsc::UnboundedReceiver<JsonRpcRequest>> {
        self.inner.request_rx.lock().take()
    }

    /// Register a session to receive filtered events and requests.
    ///
    /// Returns per-session channels for notifications and requests, routed
    /// by `sessionId`. Starts the internal router on first call.
    ///
    /// When done, call [`unregister_session`](Self::unregister_session) to
    /// clean up (typically on session destroy).
    pub(crate) fn register_session(
        &self,
        session_id: &SessionId,
    ) -> crate::router::SessionChannels {
        self.inner
            .router
            .ensure_started(&self.inner.notification_tx, &self.inner.request_rx);
        self.inner.router.register(session_id)
    }

    /// Unregister a session, dropping its per-session channels.
    pub(crate) fn unregister_session(&self, session_id: &SessionId) {
        self.inner.router.unregister(session_id);
    }

    /// Returns the protocol version negotiated with the CLI server, if any.
    ///
    /// Set during [`start`](Self::start). Returns `None` if the server didn't
    /// report a version, or if the client was created via
    /// [`from_streams`](Self::from_streams) without calling
    /// [`verify_protocol_version`](Self::verify_protocol_version).
    pub fn protocol_version(&self) -> Option<u32> {
        self.inner.negotiated_protocol_version.get().copied()
    }

    /// Verify the CLI server's protocol version is within the supported range.
    ///
    /// Called automatically by [`start`](Self::start). Call manually after
    /// [`from_streams`](Self::from_streams) if you need version verification
    /// on a custom transport.
    ///
    /// # Handshake sequence
    ///
    /// 1. Sends the `connect` JSON-RPC method, forwarding
    ///    [`ClientOptions::tcp_connection_token`] (or the auto-generated
    ///    token for SDK-spawned TCP servers) as the `token` param. This
    ///    is the canonical handshake used by all SDK languages and is
    ///    what the CLI uses to enforce loopback authentication when
    ///    started with `COPILOT_CONNECTION_TOKEN`.
    /// 2. If the server returns `-32601` (`MethodNotFound`), falls back
    ///    to the legacy `ping` RPC. This preserves compatibility with
    ///    older CLI versions that predate `connect`.
    ///
    /// # Result
    ///
    /// Returns an error if the negotiated `protocolVersion` is outside
    /// `MIN_PROTOCOL_VERSION`..=[`SDK_PROTOCOL_VERSION`]. If the server
    /// doesn't report a version, logs a warning and succeeds.
    pub async fn verify_protocol_version(&self) -> Result<(), Error> {
        let handshake_start = Instant::now();
        let mut used_fallback_ping = false;
        // Try the new `connect` handshake first (sends the connection
        // token, if any). Fall back to `ping` for legacy CLI servers
        // that don't expose `connect` (-32601 MethodNotFound).
        let server_version = match self.connect_handshake().await {
            Ok(v) => v,
            Err(Error::Rpc { code, .. }) if code == error_codes::METHOD_NOT_FOUND => {
                used_fallback_ping = true;
                self.ping(None).await?.protocol_version
            }
            Err(e) => return Err(e),
        };

        match server_version {
            None => {
                warn!("CLI server did not report protocolVersion; skipping version check");
            }
            Some(v) if !(MIN_PROTOCOL_VERSION..=SDK_PROTOCOL_VERSION).contains(&v) => {
                return Err(Error::Protocol(ProtocolError::VersionMismatch {
                    server: v,
                    min: MIN_PROTOCOL_VERSION,
                    max: SDK_PROTOCOL_VERSION,
                }));
            }
            Some(v) => {
                if let Some(&existing) = self.inner.negotiated_protocol_version.get() {
                    if existing != v {
                        return Err(Error::Protocol(ProtocolError::VersionChanged {
                            previous: existing,
                            current: v,
                        }));
                    }
                } else {
                    let _ = self.inner.negotiated_protocol_version.set(v);
                }
            }
        }

        debug!(
            elapsed_ms = handshake_start.elapsed().as_millis(),
            protocol_version = ?server_version,
            used_fallback_ping,
            "Client::verify_protocol_version protocol handshake complete"
        );
        Ok(())
    }

    /// Send the `connect` JSON-RPC handshake. Returns the server's
    /// reported protocol version, or `None` if the server omits it.
    /// Forwards [`ClientOptions::tcp_connection_token`] (or the
    /// auto-generated token for SDK-spawned TCP servers) as the `token`
    /// param. Server-side, the token is required when the server was
    /// started with `COPILOT_CONNECTION_TOKEN`.
    async fn connect_handshake(&self) -> Result<Option<u32>, Error> {
        let result = self
            .rpc()
            .connect(crate::generated::api_types::ConnectRequest {
                token: self.inner.effective_connection_token.clone(),
            })
            .await?;
        Ok(u32::try_from(result.protocol_version).ok())
    }

    /// Send a `ping` RPC and return the typed [`PingResponse`].
    ///
    /// Pass `Some(message)` to have the server echo it back; pass `None` for
    /// a bare health check. The response includes a `protocolVersion` when
    /// the CLI reports one.
    ///
    /// [`PingResponse`]: crate::types::PingResponse
    pub async fn ping(&self, message: Option<&str>) -> Result<crate::types::PingResponse, Error> {
        let params = match message {
            Some(m) => serde_json::json!({ "message": m }),
            None => serde_json::json!({}),
        };
        let value = self
            .call(generated::api_types::rpc_methods::PING, Some(params))
            .await?;
        Ok(serde_json::from_value(value)?)
    }

    /// List persisted sessions, optionally filtered by working directory,
    /// repository, or git context.
    pub async fn list_sessions(
        &self,
        filter: Option<SessionListFilter>,
    ) -> Result<Vec<SessionMetadata>, Error> {
        let params = match filter {
            Some(f) => serde_json::json!({ "filter": f }),
            None => serde_json::json!({}),
        };
        let result = self.call("session.list", Some(params)).await?;
        let response: ListSessionsResponse = serde_json::from_value(result)?;
        Ok(response.sessions)
    }

    /// Fetch metadata for a specific persisted session by ID.
    ///
    /// Returns `Ok(None)` if no session with the given ID exists. More
    /// efficient than calling [`list_sessions`](Self::list_sessions) and
    /// filtering when you only need data for a single session.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(client: &github_copilot_sdk::Client) -> Result<(), github_copilot_sdk::Error> {
    /// use github_copilot_sdk::types::SessionId;
    /// if let Some(metadata) = client.get_session_metadata(&SessionId::new("session-123")).await? {
    ///     println!("Session started at: {}", metadata.start_time);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_session_metadata(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<SessionMetadata>, Error> {
        let result = self
            .call(
                "session.getMetadata",
                Some(serde_json::json!({ "sessionId": session_id })),
            )
            .await?;
        let response: GetSessionMetadataResponse = serde_json::from_value(result)?;
        Ok(response.session)
    }

    /// Delete a persisted session by ID.
    pub async fn delete_session(&self, session_id: &SessionId) -> Result<(), Error> {
        self.call(
            "session.delete",
            Some(serde_json::json!({ "sessionId": session_id })),
        )
        .await?;
        Ok(())
    }

    /// Return the ID of the most recently updated session, if any.
    ///
    /// Useful for resuming the last conversation when the session ID was
    /// not stored. Returns `Ok(None)` if no sessions exist.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(client: &github_copilot_sdk::Client) -> Result<(), github_copilot_sdk::Error> {
    /// if let Some(last_id) = client.get_last_session_id().await? {
    ///     println!("Last session: {last_id}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_last_session_id(&self) -> Result<Option<SessionId>, Error> {
        let result = self
            .call("session.getLastId", Some(serde_json::json!({})))
            .await?;
        let response: GetLastSessionIdResponse = serde_json::from_value(result)?;
        Ok(response.session_id)
    }

    /// Return the ID of the session currently displayed in the TUI, if any.
    ///
    /// Only meaningful when connected to a server running in TUI+server mode
    /// (`--ui-server`). Returns `Ok(None)` if no foreground session is set.
    pub async fn get_foreground_session_id(&self) -> Result<Option<SessionId>, Error> {
        let result = self
            .call("session.getForeground", Some(serde_json::json!({})))
            .await?;
        let response: GetForegroundSessionResponse = serde_json::from_value(result)?;
        Ok(response.session_id)
    }

    /// Request that the TUI switch to displaying the specified session.
    ///
    /// Only meaningful when connected to a server running in TUI+server mode
    /// (`--ui-server`).
    pub async fn set_foreground_session_id(&self, session_id: &SessionId) -> Result<(), Error> {
        self.call(
            "session.setForeground",
            Some(serde_json::json!({ "sessionId": session_id })),
        )
        .await?;
        Ok(())
    }

    /// Get the CLI server status.
    pub async fn get_status(&self) -> Result<GetStatusResponse, Error> {
        let result = self.call("status.get", Some(serde_json::json!({}))).await?;
        Ok(serde_json::from_value(result)?)
    }

    /// Get authentication status.
    pub async fn get_auth_status(&self) -> Result<GetAuthStatusResponse, Error> {
        let result = self
            .call("auth.getStatus", Some(serde_json::json!({})))
            .await?;
        Ok(serde_json::from_value(result)?)
    }

    /// List available models.
    ///
    /// When [`ClientOptions::on_list_models`] is set, returns the handler's
    /// result without making a `models.list` RPC. Otherwise queries the CLI.
    pub async fn list_models(&self) -> Result<Vec<Model>, Error> {
        let cache = self.inner.models_cache.lock().clone();
        let models = cache
            .get_or_try_init(|| async {
                if let Some(handler) = &self.inner.on_list_models {
                    handler.list_models().await
                } else {
                    Ok(self.rpc().models().list().await?.models)
                }
            })
            .await?;
        Ok(models.clone())
    }

    /// Invoke [`ClientOptions::on_get_trace_context`] when configured,
    /// otherwise return [`TraceContext::default()`].
    pub(crate) async fn resolve_trace_context(&self) -> TraceContext {
        if let Some(provider) = &self.inner.on_get_trace_context {
            provider.get_trace_context().await
        } else {
            TraceContext::default()
        }
    }

    /// Return the OS process ID of the CLI child process, if one was spawned.
    pub fn pid(&self) -> Option<u32> {
        self.inner.child.lock().as_ref().and_then(|c| c.id())
    }

    /// Cooperatively shut down the client and the CLI child process.
    ///
    /// Walks every still-registered session and sends `session.destroy`
    /// for each one, then kills the CLI child. Errors from per-session
    /// destroys and the final child-kill are collected into
    /// [`StopErrors`] rather than short-circuiting on the first failure
    /// — so callers see the full picture of teardown.
    ///
    /// If you have already called [`Session::disconnect`] on every
    /// session this client created, the per-session destroy step is a
    /// no-op (the router map is empty); only the child-kill remains.
    ///
    /// [`Session::disconnect`]: crate::session::Session::disconnect
    ///
    /// # Cancel safety
    ///
    /// **Cancel-unsafe but recoverable.** The body sequentially destroys
    /// every registered session (each via [`Client::call`](Self::call),
    /// individually cancel-safe) before killing the child. Cancelling
    /// `stop()` mid-loop leaves some sessions still in the router map
    /// and the child still running. Recovery: call [`force_stop`](Self::force_stop)
    /// (sync, kills the child unconditionally and clears router state)
    /// or call `stop()` again with a fresh future. The documented
    /// `tokio::time::timeout(..., client.stop())` pattern in the example
    /// below uses `force_stop` as the fallback for exactly this case.
    pub async fn stop(&self) -> Result<(), StopErrors> {
        let pid = self.pid();
        info!(pid = ?pid, "stopping CLI process");
        let mut errors: Vec<Error> = Vec::new();

        // Snapshot the registered session IDs without holding the router
        // lock across the destroy RPCs.
        for session_id in self.inner.router.session_ids() {
            match self
                .call(
                    "session.destroy",
                    Some(serde_json::json!({ "sessionId": session_id })),
                )
                .await
            {
                Ok(_) => {}
                Err(e) => {
                    warn!(
                        session_id = %session_id,
                        error = %e,
                        "session.destroy failed during Client::stop",
                    );
                    errors.push(e);
                }
            }
            self.inner.router.unregister(&session_id);
        }

        let child = self.inner.child.lock().take();
        *self.inner.state.lock() = ConnectionState::Disconnected;
        *self.inner.models_cache.lock() = Arc::new(tokio::sync::OnceCell::new());
        if let Some(mut child) = child
            && let Err(e) = child.kill().await
        {
            errors.push(Error::Io(e));
        }

        info!(pid = ?pid, errors = errors.len(), "CLI process stopped");
        if errors.is_empty() {
            Ok(())
        } else {
            Err(StopErrors(errors))
        }
    }

    /// Forcibly stop the CLI process without waiting for it to exit.
    ///
    /// Synchronous fallback when [`stop`](Self::stop) is unsuitable — for
    /// example when the awaiting tokio runtime is shutting down or the
    /// process is wedged on I/O. Sends a kill signal without awaiting
    /// reaper completion and immediately drops all per-session router
    /// state so dependent tasks observe a closed channel rather than a
    /// hang.
    ///
    /// # Cancel safety
    ///
    /// **Synchronous and infallible by construction.** Not async; cannot
    /// be cancelled. Designed as the recovery path when [`stop`](Self::stop)
    /// is wrapped in a timeout that elapses.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(client: github_copilot_sdk::Client) {
    /// // Try graceful shutdown first; fall back to force_stop if hung.
    /// match tokio::time::timeout(
    ///     std::time::Duration::from_secs(5),
    ///     client.stop(),
    /// ).await {
    ///     Ok(_) => {}
    ///     Err(_) => client.force_stop(),
    /// }
    /// # }
    /// ```
    pub fn force_stop(&self) {
        let pid = self.pid();
        info!(pid = ?pid, "force-stopping CLI process");
        if let Some(mut child) = self.inner.child.lock().take()
            && let Err(e) = child.start_kill()
        {
            error!(pid = ?pid, error = %e, "failed to send kill signal");
        }
        self.inner.rpc.force_close();
        // Drop all session channels so any awaiters see a closed channel
        // instead of waiting for responses that will never arrive.
        self.inner.router.clear();
        *self.inner.state.lock() = ConnectionState::Disconnected;
        *self.inner.models_cache.lock() = Arc::new(tokio::sync::OnceCell::new());
    }

    /// Subscribe to lifecycle events.
    ///
    /// Returns a [`LifecycleSubscription`] that yields every
    /// [`SessionLifecycleEvent`] sent by the CLI. Drop the value to
    /// unsubscribe; there is no separate cancel handle.
    ///
    /// The returned handle implements both an inherent
    /// [`recv`](LifecycleSubscription::recv) method and [`Stream`](tokio_stream::Stream),
    /// so callers can use a `while let` loop or any combinator from
    /// `tokio_stream::StreamExt` / `futures::StreamExt`.
    ///
    /// Each subscriber maintains its own queue. If a consumer cannot keep
    /// up, the oldest events are dropped and `recv` returns
    /// [`RecvError::Lagged`] with the count of skipped events; consumers
    /// should match on it and continue. Slow consumers do not block the
    /// producer.
    ///
    /// To filter by event type, match on `event.event_type` in the
    /// consumer task. There is no built-in typed filter — `match` is more
    /// flexible and keeps the API surface small.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(client: github_copilot_sdk::Client) {
    /// let mut events = client.subscribe_lifecycle();
    /// tokio::spawn(async move {
    ///     while let Ok(event) = events.recv().await {
    ///         println!("session {} -> {:?}", event.session_id, event.event_type);
    ///     }
    /// });
    /// # }
    /// ```
    pub fn subscribe_lifecycle(&self) -> LifecycleSubscription {
        LifecycleSubscription::new(self.inner.lifecycle_tx.subscribe())
    }

    /// Return the current [`ConnectionState`].
    ///
    /// The state advances to [`Connected`](ConnectionState::Connected) once
    /// [`Client::start`] / [`Client::from_streams`] returns successfully and
    /// drops to [`Disconnected`](ConnectionState::Disconnected) after
    /// [`stop`](Self::stop) or [`force_stop`](Self::force_stop).
    pub fn state(&self) -> ConnectionState {
        *self.inner.state.lock()
    }
}

impl Drop for ClientInner {
    fn drop(&mut self) {
        if let Some(ref mut child) = *self.child.lock() {
            let pid = child.id();
            if let Err(e) = child.start_kill() {
                error!(pid = ?pid, error = %e, "failed to kill CLI process on drop");
            } else {
                info!(pid = ?pid, "kill signal sent for CLI process on drop");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_transport_failure_matches_request_cancelled() {
        let err = Error::Protocol(ProtocolError::RequestCancelled);
        assert!(err.is_transport_failure());
    }

    #[test]
    fn is_transport_failure_matches_io_error() {
        let err = Error::Io(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "gone"));
        assert!(err.is_transport_failure());
    }

    #[test]
    fn is_transport_failure_rejects_rpc_error() {
        let err = Error::Rpc {
            code: -1,
            message: "bad".into(),
        };
        assert!(!err.is_transport_failure());
    }

    #[test]
    fn is_transport_failure_rejects_session_error() {
        let err = Error::Session(SessionError::NotFound("s1".into()));
        assert!(!err.is_transport_failure());
    }

    #[test]
    fn client_options_builder_composes() {
        let opts = ClientOptions::new()
            .with_program(CliProgram::Path(PathBuf::from("/usr/local/bin/copilot")))
            .with_prefix_args(["node"])
            .with_cwd(PathBuf::from("/tmp"))
            .with_env([("KEY", "value")])
            .with_env_remove(["UNWANTED"])
            .with_extra_args(["--quiet"])
            .with_github_token("ghp_test")
            .with_use_logged_in_user(false)
            .with_log_level(LogLevel::Debug)
            .with_session_idle_timeout_seconds(120)
            .with_remote(true);
        assert!(matches!(opts.program, CliProgram::Path(_)));
        assert_eq!(opts.prefix_args, vec![std::ffi::OsString::from("node")]);
        assert_eq!(opts.cwd, PathBuf::from("/tmp"));
        assert_eq!(
            opts.env,
            vec![(
                std::ffi::OsString::from("KEY"),
                std::ffi::OsString::from("value")
            )]
        );
        assert_eq!(opts.env_remove, vec![std::ffi::OsString::from("UNWANTED")]);
        assert_eq!(opts.extra_args, vec!["--quiet".to_string()]);
        assert_eq!(opts.github_token.as_deref(), Some("ghp_test"));
        assert_eq!(opts.use_logged_in_user, Some(false));
        assert!(matches!(opts.log_level, Some(LogLevel::Debug)));
        assert_eq!(opts.session_idle_timeout_seconds, Some(120));
        assert!(opts.remote);
    }

    #[test]
    fn is_transport_failure_rejects_other_protocol_errors() {
        let err = Error::Protocol(ProtocolError::CliStartupTimeout);
        assert!(!err.is_transport_failure());
    }

    #[test]
    fn build_command_lets_env_remove_strip_injected_token() {
        let opts = ClientOptions {
            github_token: Some("secret".to_string()),
            env_remove: vec![std::ffi::OsString::from("COPILOT_SDK_AUTH_TOKEN")],
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        // get_envs() iter yields the latest action per key — None means removed.
        let action = cmd
            .as_std()
            .get_envs()
            .find(|(k, _)| *k == std::ffi::OsStr::new("COPILOT_SDK_AUTH_TOKEN"))
            .map(|(_, v)| v);
        assert_eq!(
            action,
            Some(None),
            "env_remove should win over github_token"
        );
    }

    #[test]
    fn build_command_lets_env_override_injected_token() {
        let opts = ClientOptions {
            github_token: Some("from-options".to_string()),
            env: vec![(
                std::ffi::OsString::from("COPILOT_SDK_AUTH_TOKEN"),
                std::ffi::OsString::from("from-env"),
            )],
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        let value = cmd
            .as_std()
            .get_envs()
            .find(|(k, _)| *k == std::ffi::OsStr::new("COPILOT_SDK_AUTH_TOKEN"))
            .and_then(|(_, v)| v);
        assert_eq!(value, Some(std::ffi::OsStr::new("from-env")));
    }

    #[test]
    fn build_command_injects_github_token_by_default() {
        let opts = ClientOptions {
            github_token: Some("just-the-token".to_string()),
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        let value = cmd
            .as_std()
            .get_envs()
            .find(|(k, _)| *k == std::ffi::OsStr::new("COPILOT_SDK_AUTH_TOKEN"))
            .and_then(|(_, v)| v);
        assert_eq!(value, Some(std::ffi::OsStr::new("just-the-token")));
    }

    fn env_value<'a>(cmd: &'a tokio::process::Command, key: &str) -> Option<&'a std::ffi::OsStr> {
        cmd.as_std()
            .get_envs()
            .find(|(k, _)| *k == std::ffi::OsStr::new(key))
            .and_then(|(_, v)| v)
    }

    #[test]
    fn telemetry_config_builder_composes() {
        let cfg = TelemetryConfig::new()
            .with_otlp_endpoint("http://collector:4318")
            .with_file_path(PathBuf::from("/var/log/copilot.jsonl"))
            .with_exporter_type(OtelExporterType::OtlpHttp)
            .with_source_name("my-app")
            .with_capture_content(true);

        assert_eq!(cfg.otlp_endpoint.as_deref(), Some("http://collector:4318"));
        assert_eq!(
            cfg.file_path.as_deref(),
            Some(Path::new("/var/log/copilot.jsonl")),
        );
        assert_eq!(cfg.exporter_type, Some(OtelExporterType::OtlpHttp));
        assert_eq!(cfg.source_name.as_deref(), Some("my-app"));
        assert_eq!(cfg.capture_content, Some(true));
        assert!(!cfg.is_empty());
        assert!(TelemetryConfig::new().is_empty());
    }

    #[test]
    fn build_command_sets_otel_env_when_telemetry_enabled() {
        let opts = ClientOptions {
            telemetry: Some(TelemetryConfig {
                otlp_endpoint: Some("http://collector:4318".to_string()),
                file_path: Some(PathBuf::from("/var/log/copilot.jsonl")),
                exporter_type: Some(OtelExporterType::OtlpHttp),
                source_name: Some("my-app".to_string()),
                capture_content: Some(true),
            }),
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert_eq!(
            env_value(&cmd, "COPILOT_OTEL_ENABLED"),
            Some(std::ffi::OsStr::new("true")),
        );
        assert_eq!(
            env_value(&cmd, "OTEL_EXPORTER_OTLP_ENDPOINT"),
            Some(std::ffi::OsStr::new("http://collector:4318")),
        );
        assert_eq!(
            env_value(&cmd, "COPILOT_OTEL_FILE_EXPORTER_PATH"),
            Some(std::ffi::OsStr::new("/var/log/copilot.jsonl")),
        );
        assert_eq!(
            env_value(&cmd, "COPILOT_OTEL_EXPORTER_TYPE"),
            Some(std::ffi::OsStr::new("otlp-http")),
        );
        assert_eq!(
            env_value(&cmd, "COPILOT_OTEL_SOURCE_NAME"),
            Some(std::ffi::OsStr::new("my-app")),
        );
        assert_eq!(
            env_value(&cmd, "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"),
            Some(std::ffi::OsStr::new("true")),
        );
    }

    #[test]
    fn build_command_omits_otel_env_when_telemetry_none() {
        let opts = ClientOptions::default();
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        for key in [
            "COPILOT_OTEL_ENABLED",
            "OTEL_EXPORTER_OTLP_ENDPOINT",
            "COPILOT_OTEL_FILE_EXPORTER_PATH",
            "COPILOT_OTEL_EXPORTER_TYPE",
            "COPILOT_OTEL_SOURCE_NAME",
            "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
        ] {
            assert!(
                env_value(&cmd, key).is_none(),
                "expected {key} to be unset when telemetry is None",
            );
        }
    }

    #[test]
    fn build_command_omits_unset_telemetry_fields() {
        let opts = ClientOptions {
            telemetry: Some(TelemetryConfig {
                otlp_endpoint: Some("http://collector:4318".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        // The one set field plus the implicit enabled flag should propagate.
        assert_eq!(
            env_value(&cmd, "COPILOT_OTEL_ENABLED"),
            Some(std::ffi::OsStr::new("true")),
        );
        assert_eq!(
            env_value(&cmd, "OTEL_EXPORTER_OTLP_ENDPOINT"),
            Some(std::ffi::OsStr::new("http://collector:4318")),
        );
        // None of the other fields should leak as env vars.
        for key in [
            "COPILOT_OTEL_FILE_EXPORTER_PATH",
            "COPILOT_OTEL_EXPORTER_TYPE",
            "COPILOT_OTEL_SOURCE_NAME",
            "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
        ] {
            assert!(env_value(&cmd, key).is_none(), "{key} should be unset");
        }
    }

    #[test]
    fn build_command_lets_user_env_override_telemetry() {
        let opts = ClientOptions {
            telemetry: Some(TelemetryConfig {
                otlp_endpoint: Some("http://from-config:4318".to_string()),
                ..Default::default()
            }),
            env: vec![(
                std::ffi::OsString::from("OTEL_EXPORTER_OTLP_ENDPOINT"),
                std::ffi::OsString::from("http://from-user-env:4318"),
            )],
            ..Default::default()
        };
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert_eq!(
            env_value(&cmd, "OTEL_EXPORTER_OTLP_ENDPOINT"),
            Some(std::ffi::OsStr::new("http://from-user-env:4318")),
            "user-supplied options.env should override telemetry config",
        );
    }

    #[test]
    fn build_command_sets_copilot_home_env_when_configured() {
        let opts = ClientOptions::new().with_copilot_home(PathBuf::from("/custom/copilot"));
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert_eq!(
            env_value(&cmd, "COPILOT_HOME"),
            Some(std::ffi::OsStr::new("/custom/copilot")),
        );

        let opts = ClientOptions::default();
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert!(env_value(&cmd, "COPILOT_HOME").is_none());
    }

    #[test]
    fn build_command_sets_connection_token_env_when_configured() {
        let opts = ClientOptions::new().with_tcp_connection_token("secret-token");
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert_eq!(
            env_value(&cmd, "COPILOT_CONNECTION_TOKEN"),
            Some(std::ffi::OsStr::new("secret-token")),
        );

        let opts = ClientOptions::default();
        let cmd = Client::build_command(Path::new("/bin/echo"), &opts);
        assert!(env_value(&cmd, "COPILOT_CONNECTION_TOKEN").is_none());
    }

    #[tokio::test]
    async fn start_rejects_token_with_stdio_transport() {
        let opts = ClientOptions::new()
            .with_tcp_connection_token("token-123")
            .with_program(CliProgram::Path(PathBuf::from("/bin/echo")));
        let err = Client::start(opts).await.unwrap_err();
        assert!(matches!(err, Error::InvalidConfig(_)), "got {err:?}");
        let Error::InvalidConfig(msg) = err else {
            unreachable!()
        };
        assert!(
            msg.contains("Stdio"),
            "error should explain the stdio incompatibility: {msg}"
        );
    }

    #[tokio::test]
    async fn start_rejects_empty_connection_token() {
        let opts = ClientOptions::new()
            .with_tcp_connection_token("")
            .with_transport(Transport::Tcp { port: 0 })
            .with_program(CliProgram::Path(PathBuf::from("/bin/echo")));
        let err = Client::start(opts).await.unwrap_err();
        assert!(matches!(err, Error::InvalidConfig(_)), "got {err:?}");
    }

    #[test]
    fn telemetry_config_capture_content_serializes_as_lowercase_bool() {
        let opts_true = ClientOptions {
            telemetry: Some(TelemetryConfig {
                capture_content: Some(true),
                ..Default::default()
            }),
            ..Default::default()
        };
        let opts_false = ClientOptions {
            telemetry: Some(TelemetryConfig {
                capture_content: Some(false),
                ..Default::default()
            }),
            ..Default::default()
        };
        let cmd_true = Client::build_command(Path::new("/bin/echo"), &opts_true);
        let cmd_false = Client::build_command(Path::new("/bin/echo"), &opts_false);
        assert_eq!(
            env_value(
                &cmd_true,
                "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
            ),
            Some(std::ffi::OsStr::new("true")),
        );
        assert_eq!(
            env_value(
                &cmd_false,
                "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
            ),
            Some(std::ffi::OsStr::new("false")),
        );
    }

    #[test]
    fn session_idle_timeout_args_are_omitted_by_default() {
        let opts = ClientOptions::default();
        assert!(Client::session_idle_timeout_args(&opts).is_empty());
    }

    #[test]
    fn session_idle_timeout_args_omitted_for_zero() {
        let opts = ClientOptions {
            session_idle_timeout_seconds: Some(0),
            ..Default::default()
        };
        assert!(Client::session_idle_timeout_args(&opts).is_empty());
    }

    #[test]
    fn session_idle_timeout_args_emit_flag_for_positive_value() {
        let opts = ClientOptions {
            session_idle_timeout_seconds: Some(300),
            ..Default::default()
        };
        assert_eq!(
            Client::session_idle_timeout_args(&opts),
            vec!["--session-idle-timeout".to_string(), "300".to_string()]
        );
    }

    #[test]
    fn remote_args_omitted_by_default() {
        let opts = ClientOptions::default();
        assert!(Client::remote_args(&opts).is_empty());
    }

    #[test]
    fn remote_args_emit_flag_when_enabled() {
        let opts = ClientOptions {
            remote: true,
            ..Default::default()
        };
        assert_eq!(Client::remote_args(&opts), vec!["--remote".to_string()]);
    }

    #[test]
    fn log_level_str_round_trips() {
        for level in [
            LogLevel::None,
            LogLevel::Error,
            LogLevel::Warning,
            LogLevel::Info,
            LogLevel::Debug,
            LogLevel::All,
        ] {
            let s = level.as_str();
            let json = serde_json::to_string(&level).unwrap();
            assert_eq!(json, format!("\"{s}\""));
            let parsed: LogLevel = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, level);
        }
    }

    #[test]
    fn client_options_debug_redacts_handler() {
        struct StubHandler;
        #[async_trait]
        impl ListModelsHandler for StubHandler {
            async fn list_models(&self) -> Result<Vec<Model>, Error> {
                Ok(vec![])
            }
        }
        let opts = ClientOptions {
            on_list_models: Some(Arc::new(StubHandler)),
            github_token: Some("secret-token".into()),
            ..Default::default()
        };
        let debug = format!("{opts:?}");
        assert!(debug.contains("on_list_models: Some(\"<set>\")"));
        assert!(debug.contains("github_token: Some(\"<redacted>\")"));
        assert!(!debug.contains("secret-token"));
    }

    #[tokio::test]
    async fn list_models_uses_on_list_models_handler_when_set() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CountingHandler {
            calls: Arc<AtomicUsize>,
            models: Vec<Model>,
        }
        #[async_trait]
        impl ListModelsHandler for CountingHandler {
            async fn list_models(&self) -> Result<Vec<Model>, Error> {
                self.calls.fetch_add(1, Ordering::SeqCst);
                Ok(self.models.clone())
            }
        }

        let calls = Arc::new(AtomicUsize::new(0));
        let model = Model {
            billing: None,
            capabilities: ModelCapabilities {
                limits: None,
                supports: None,
            },
            default_reasoning_effort: None,
            id: "byok-gpt-4".into(),
            model_picker_category: None,
            model_picker_price_category: None,
            name: "BYOK GPT-4".into(),
            policy: None,
            supported_reasoning_efforts: Vec::new(),
        };
        let handler: Arc<dyn ListModelsHandler> = Arc::new(CountingHandler {
            calls: Arc::clone(&calls),
            models: vec![model.clone()],
        });

        let client = client_with_list_models_handler(handler);

        let result = client.list_models().await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "byok-gpt-4");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn list_models_serializes_concurrent_cache_misses() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct SlowCountingHandler {
            calls: Arc<AtomicUsize>,
            models: Vec<Model>,
        }
        #[async_trait]
        impl ListModelsHandler for SlowCountingHandler {
            async fn list_models(&self) -> Result<Vec<Model>, Error> {
                self.calls.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(std::time::Duration::from_millis(25)).await;
                Ok(self.models.clone())
            }
        }

        let calls = Arc::new(AtomicUsize::new(0));
        let model = Model {
            billing: None,
            capabilities: ModelCapabilities {
                limits: None,
                supports: None,
            },
            default_reasoning_effort: None,
            id: "single-flight-model".into(),
            model_picker_category: None,
            model_picker_price_category: None,
            name: "Single Flight Model".into(),
            policy: None,
            supported_reasoning_efforts: Vec::new(),
        };
        let handler: Arc<dyn ListModelsHandler> = Arc::new(SlowCountingHandler {
            calls: Arc::clone(&calls),
            models: vec![model],
        });
        let client = client_with_list_models_handler(handler);

        let (first, second) = tokio::join!(client.list_models(), client.list_models());
        assert_eq!(first.unwrap()[0].id, "single-flight-model");
        assert_eq!(second.unwrap()[0].id, "single-flight-model");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn cancelled_create_session_unregisters_pending_session() {
        let (client_write, _server_read) = tokio::io::duplex(8192);
        let (_server_write, client_read) = tokio::io::duplex(8192);
        let client = Client::from_streams(client_read, client_write, std::env::temp_dir()).unwrap();
        let handle = tokio::spawn({
            let client = client.clone();
            async move { client.create_session(SessionConfig::default()).await }
        });

        wait_for_pending_session_registration(&client).await;
        handle.abort();
        let _ = handle.await;

        assert!(client.inner.router.session_ids().is_empty());
        client.force_stop();
    }

    #[tokio::test]
    async fn cancelled_resume_session_unregisters_pending_session() {
        let (client_write, _server_read) = tokio::io::duplex(8192);
        let (_server_write, client_read) = tokio::io::duplex(8192);
        let client = Client::from_streams(client_read, client_write, std::env::temp_dir()).unwrap();
        let session_id = SessionId::new("resume-cancel-test");
        let handle = tokio::spawn({
            let client = client.clone();
            async move {
                client
                    .resume_session(ResumeSessionConfig::new(session_id))
                    .await
            }
        });

        wait_for_pending_session_registration(&client).await;
        handle.abort();
        let _ = handle.await;

        assert!(client.inner.router.session_ids().is_empty());
        client.force_stop();
    }

    fn client_with_list_models_handler(handler: Arc<dyn ListModelsHandler>) -> Client {
        Client {
            inner: Arc::new(ClientInner {
                child: parking_lot::Mutex::new(None),
                rpc: {
                    let (req_tx, _req_rx) = mpsc::unbounded_channel();
                    let (notif_tx, _notif_rx) = broadcast::channel(16);
                    let (read_pipe, _write_pipe) = tokio::io::duplex(64);
                    let (_unused_read, write_pipe) = tokio::io::duplex(64);
                    JsonRpcClient::new(write_pipe, read_pipe, notif_tx, req_tx)
                },
                cwd: PathBuf::from("."),
                request_rx: parking_lot::Mutex::new(None),
                notification_tx: broadcast::channel(16).0,
                router: router::SessionRouter::new(),
                negotiated_protocol_version: OnceLock::new(),
                state: parking_lot::Mutex::new(ConnectionState::Connected),
                lifecycle_tx: broadcast::channel(16).0,
                on_list_models: Some(handler),
                models_cache: parking_lot::Mutex::new(Arc::new(tokio::sync::OnceCell::new())),
                session_fs_configured: false,
                on_get_trace_context: None,
                effective_connection_token: None,
            }),
        }
    }

    async fn wait_for_pending_session_registration(client: &Client) {
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(1);
        while client.inner.router.session_ids().is_empty() {
            assert!(
                tokio::time::Instant::now() < deadline,
                "session was not registered"
            );
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }
}