granite-cli 0.2.0

CLI for discovering, configuring, and launching AI workflows powered by IBM Granite models.
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
//! Launcher for the `opencode` coding agent (<https://opencode.ai>).
//!
//! Unlike `pi`, OpenCode's config sources are additive: `OPENCODE_CONFIG`
//! points at one extra file that gets merged into the chain (loaded after the
//! global config, before the project config) rather than a whole directory to
//! redirect wholesale. This launcher reads the user's global and project
//! `opencode.json` configs to discover configured providers, registers them on
//! the session proxy for usage tracking, then writes its own small generated
//! file under `GRANITE_CLI_HOME` and points `OPENCODE_CONFIG` at it. The
//! generated config includes granite-cli providers plus any user providers
//! merged in with their `baseURL` redirected to the proxy.

// Standard
use std::collections::HashSet;
use std::path::{Path, PathBuf};

// Third Party
use alog::{MessageLevel, alog_channel, use_channel};
use anyhow::Context;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

// Local
use crate::capabilities::{
    AgentModelBinding, Binding, BindingType, Capability, KnownSubAgent, McpBinding,
    SubAgentBinding, ToolName,
};
use crate::launchers::base::{EnvBinding, LaunchContext, Launcher, LauncherMetadata, run_command};
use crate::launchers::shared::mcp_cli::mcp_binding_request;
use crate::providers::ApiType;
use crate::proxy::ProxyHandle;
use crate::registry::ConfigConstructable;
use crate::utils::resolve_shell_command;
use crate::utils::ui::Ui;

use_channel!("OPNCD");

/*-- public --*/

#[derive(Debug, Clone, Serialize, Deserialize, Default, schemars::JsonSchema)]
pub struct OpenCodeLauncherConfig {
    /// Override path to the `opencode` binary for non-PATH installs.
    /// Leave unset to use PATH lookup.
    #[serde(default)]
    pub command_path: Option<String>,

    /// Extra keys merged (shallow, last-write-wins) into every generated
    /// provider entry -- e.g. `headers` a particular server needs. Necessary
    /// because the entries are regenerated on every launch. Applied
    /// uniformly to the main model's provider entry *and* every bound
    /// sub-agent's, since there is no per-sub-agent override knob yet -- an
    /// override meant for one provider (e.g. a dialect-specific `npm`
    /// package) will also land on any other bound provider.
    #[serde(default)]
    pub provider_overrides: Option<serde_json::Value>,
}

pub struct OpenCodeLauncher {
    instance_id: String,
    config: OpenCodeLauncherConfig,
    bound_agent_model: Option<AgentModelBinding>,
    /// `(server_name, binding)` for every MCP-capable capability bound to
    /// this launcher, written into the generated config's `mcp` block.
    bound_mcp_bindings: Vec<(String, McpBinding)>,
    /// `(name, binding)` for every `SubAgentCapability` bound to this
    /// launcher -- `name` is the capability's own `instance_id`, used as the
    /// key in the generated config's `agent` block. Unlike Claude Code (one
    /// `ANTHROPIC_BASE_URL` for the whole session), OpenCode's config natively
    /// supports any number of named providers, so each sub-agent's model gets
    /// its own `provider.<name>` entry and is referenced directly as
    /// `<provider>/<model>` in `agent.<name>.model` -- no mini-router needed.
    bound_sub_agents: Vec<(String, SubAgentBinding)>,
    /// The session-scoped model proxy, if one was booted for this launch
    /// (see `run_launch`) -- present whenever usage tracking or sub-agent
    /// routing is needed. Used to redirect provider baseURLs so all traffic
    /// flows through the proxy for usage accounting.
    model_proxy: Option<ProxyHandle>,
}

impl ConfigConstructable for OpenCodeLauncher {
    type Config = OpenCodeLauncherConfig;

    fn new(
        instance_id: &str,
        cfg: &serde_json::Value,
        global_config: &crate::config::Config,
    ) -> Self {
        let config: OpenCodeLauncherConfig =
            serde_json::from_value(cfg.clone()).unwrap_or_default();
        Self {
            instance_id: instance_id.to_string(),
            config,
            bound_agent_model: None,
            bound_mcp_bindings: vec![],
            bound_sub_agents: vec![],
            model_proxy: global_config.model_proxy.clone(),
        }
    }
}

impl crate::registry::Named for OpenCodeLauncher {
    fn instance_id(&self) -> &str {
        &self.instance_id
    }
}

#[async_trait]
impl Launcher for OpenCodeLauncher {
    fn name(&self) -> &str {
        "OpenCode CLI"
    }

    fn command(&self) -> &str {
        self.config.command_path.as_deref().unwrap_or("opencode")
    }

    async fn bind_capability(&mut self, capability: &dyn Capability) -> anyhow::Result<()> {
        let supported = Self::metadata().supported_capabilities;
        let capability_types = capability.binding_types();
        if !capability_types.is_subset(&supported) {
            anyhow::bail!(
                "capability supports {:?} which this launcher does not support",
                capability_types.difference(&supported).collect::<Vec<_>>()
            );
        }

        if capability_types.contains(&BindingType::Mcp) {
            let binding = capability.bind(mcp_binding_request()).await?;
            match binding {
                Binding::Mcp(binding) => {
                    self.bound_mcp_bindings
                        .push((capability.instance_id().to_string(), binding));
                }
                other => anyhow::bail!("expected an Mcp binding, got {:?}", other.binding_type()),
            }
            return Ok(());
        }

        if capability_types.contains(&BindingType::SubAgent) {
            // Same dialect choice as the main-model request below: every
            // granite-cli provider can serve `@ai-sdk/openai-compatible`.
            let request = crate::capabilities::BindingRequest::SubAgent(
                crate::capabilities::SubAgentBindingRequest {
                    api_type: ApiType::OpenAI,
                },
            );
            let binding = capability.bind(request).await?;
            match binding {
                Binding::SubAgent(binding) => {
                    self.bound_sub_agents
                        .push((capability.instance_id().to_string(), binding));
                }
                other => anyhow::bail!(
                    "expected a SubAgent binding, got {:?}",
                    other.binding_type()
                ),
            }
            return Ok(());
        }

        // OpenCode's custom-provider config speaks whatever dialect its `npm`
        // SDK package implements. `@ai-sdk/openai-compatible` is the one every
        // granite-cli provider can serve, so that is what we ask for.
        let request = crate::capabilities::BindingRequest::AgentModel(
            crate::capabilities::AgentModelBindingRequest {
                api_type: ApiType::OpenAI,
            },
        );

        let binding = capability.bind(request).await?;
        match binding {
            Binding::AgentModel(binding) => {
                self.bound_agent_model = Some(binding);
            }
            other => anyhow::bail!(
                "expected an AgentModel binding, got {:?}",
                other.binding_type()
            ),
        }
        Ok(())
    }

    fn validate_command(&self) -> anyhow::Result<PathBuf> {
        resolve_shell_command(&self.config.command_path, "opencode")
    }

    /// Maps a canonical `ToolName` onto the tool-id strings OpenCode's own
    /// (legacy, but still supported) `tools` boolean map uses -- confirmed
    /// against current official docs (<https://opencode.ai/docs/agents/>,
    /// <https://opencode.ai/docs/permissions/>). `edit`/`write` are two
    /// distinct tool ids at this granularity even though OpenCode's newer
    /// `permission` config consolidates both under one `edit` category. MCP
    /// tools are named `<server>_<tool>`, with `<server>_*` disabling/enabling
    /// every tool from that server (confirmed via the docs' own example for
    /// disabling a whole MCP server's tools).
    fn map_tool_name(&self, tool: &ToolName) -> Option<String> {
        Some(match tool {
            ToolName::FileRead => "read".to_string(),
            ToolName::FileWrite => "write".to_string(),
            ToolName::FileEdit => "edit".to_string(),
            ToolName::Search => "grep".to_string(),
            ToolName::FileSearch => "glob".to_string(),
            ToolName::Shell => "bash".to_string(),
            ToolName::WebFetch => "webfetch".to_string(),
            ToolName::WebSearch => "websearch".to_string(),
            ToolName::Mcp { server, tool: None } => format!("{server}_*"),
            ToolName::Mcp {
                server,
                tool: Some(t),
            } => format!("{server}_{t}"),
            ToolName::Other(raw) => raw.clone(),
        })
    }

    /// Points OpenCode at the granite-cli-generated config file and supplies
    /// the credential the file interpolates.
    ///
    /// The `apiKey` is written as an environment reference
    /// (`${GRANITE_CLI_OPENCODE_API_KEY}`) rather than a literal, so the
    /// secret stays out of the generated file and off OpenCode's command
    /// line. Providers with no key omit `apiKey` entirely -- OpenCode's
    /// custom-provider config does not require one.
    async fn env_overlay(&self, ctx: &LaunchContext) -> anyhow::Result<Vec<EnvBinding>> {
        let mut overlay = vec![];
        if self.bound_agent_model.is_some()
            || !self.bound_mcp_bindings.is_empty()
            || !self.bound_sub_agents.is_empty()
        {
            overlay.push(EnvBinding {
                key: CONFIG_ENV.to_string(),
                value: opencode_config_path(ctx)?.to_string_lossy().to_string(),
            });

            for (index, (binding, _)) in self.provider_groups().iter().enumerate() {
                if let Some(api_key) = binding
                    .api_key
                    .as_ref()
                    .map(|api_key| api_key.0.clone())
                    .filter(|key| !key.is_empty())
                {
                    overlay.push(EnvBinding {
                        key: provider_api_key_env(index),
                        value: api_key,
                    });
                }
            }
        }
        Ok(overlay)
    }

    /// Writes the granite-cli OpenCode config file, then execs `opencode`
    /// with the caller's arguments untouched.
    ///
    /// Model selection goes through the config's top-level `model` key
    /// rather than a `--model` CLI flag: that flag only exists on some of
    /// OpenCode's subcommands (`run`, `attach`, the default TUI), so
    /// injecting it ahead of an arbitrary subcommand (e.g. `models`,
    /// `agent`) would either be rejected or silently misparsed. The config
    /// key is documented to apply uniformly across all of those surfaces.
    ///
    /// When usage tracking is active (proxy is running), discovers all
    /// providers the user has configured in their global and project
    /// `opencode.json` files and any env-based providers, registers them on
    /// the proxy, and merges them into the generated config with their
    /// `baseURL` redirected to the proxy. This ensures all model calls
    /// (granite-cli managed and user-configured) flow through the proxy for
    /// usage accounting.
    async fn launch(
        &self,
        args: &[String],
        ctx: &LaunchContext,
        ui: &dyn Ui,
    ) -> anyhow::Result<std::process::ExitStatus> {
        if self.bound_agent_model.is_some()
            || !self.bound_mcp_bindings.is_empty()
            || !self.bound_sub_agents.is_empty()
        {
            // Build granite-cli provider entries
            let mut granite_providers = serde_json::Map::new();
            for (index, (binding, model_names)) in self.provider_groups().iter().enumerate() {
                let entry =
                    self.provider_entry(binding, model_names, &provider_api_key_env(index))?;
                granite_providers.insert(binding.provider_name.clone(), entry);
            }

            // Discover and register user providers for usage tracking.
            // Every provider merged into the generated config must also be
            // registered on the proxy: a provider path the proxy doesn't
            // recognize is rejected rather than forwarded (see
            // `target_and_label_for`), so an entry in one set but not the
            // other would break that provider outright.
            if let Some(proxy_handle) = &self.model_proxy {
                let user_providers = Self::discover_user_providers(ctx).unwrap_or_default();
                let env_providers = Self::discover_env_providers();
                if !user_providers.is_empty() || !env_providers.is_empty() {
                    self.register_user_providers_on_proxy(proxy_handle, &env_providers);
                    self.register_user_providers_on_proxy(proxy_handle, &user_providers);
                    granite_providers = self.merge_user_providers_into_config(
                        &user_providers,
                        &env_providers,
                        &granite_providers,
                    );
                }
            }

            let agent = self.build_agent_config(ui);
            let config = generate_config(
                self.bound_agent_model.as_ref(),
                granite_providers,
                agent,
                &self.bound_mcp_bindings,
            );
            let config_path = opencode_config_path(ctx)?;

            if ctx.dry_run {
                ui.info(&format!(
                    "Would write OpenCode config to {}:",
                    config_path.display()
                ));
                ui.info(&serde_json::to_string_pretty(&config)?);
            } else {
                write_opencode_config(&config_path, &config)?;
                ui.info(&format!(
                    "Wrote OpenCode config to {}",
                    config_path.display()
                ));
            }
        }

        let binary = self.validate_command()?;
        let overlay = self.env_overlay(ctx).await?;
        alog_channel!(MessageLevel::Debug2, "Env Overlay: {:#?}", overlay);

        run_command(binary, &overlay, args, ctx, ui).await
    }
}

impl HasOpenCodeLauncherMetadata for OpenCodeLauncher {
    fn metadata() -> LauncherMetadata {
        LauncherMetadata {
            name: "OpenCode CLI".to_string(),
            description: "OpenCode terminal coding agent".to_string(),
            default_command: "opencode".to_string(),
            supported_capabilities: HashSet::from([
                BindingType::AgentModel,
                BindingType::Mcp,
                BindingType::SubAgent,
            ]),
            tags: vec!["opencode".to_string(), "coding-agent".to_string()],
        }
    }
}

/*-- private --*/

// HasOpenCodeLauncherMetadata is the macro-generated trait; re-exported via mod.rs.
use crate::launchers::base::HasLauncherMetadata as HasOpenCodeLauncherMetadata;

/// Env var OpenCode merges an extra config file from, in addition to its own
/// global/project config.
const CONFIG_ENV: &str = "OPENCODE_CONFIG";

/// Env var the generated provider entry interpolates its `apiKey` from.
const API_KEY_ENV: &str = "GRANITE_CLI_OPENCODE_API_KEY";

/// The generated config file's name, relative to the launcher state dir.
const CONFIG_FILE: &str = "opencode.json";

impl OpenCodeLauncher {
    /// Builds the `provider.<name>` entry describing `binding`'s provider,
    /// with one `models` entry per name in `model_names` -- plural because a
    /// single provider instance may back both the main model and one or more
    /// sub-agents' models, all of which must land in the same generated
    /// `provider.<name>` entry rather than clobbering each other.
    ///
    /// When a session proxy is active (usage tracking or sub-agent routing
    /// enabled), the provider's `baseURL` is overridden to point at the proxy
    /// so all traffic flows through it for usage accounting. The proxy
    /// dispatches based on the `"model"` field in each request body, which
    /// means the provider name is irrelevant for routing -- only the model
    /// name matters.
    fn provider_entry(
        &self,
        binding: &AgentModelBinding,
        model_names: &[&str],
        api_key_env: &str,
    ) -> anyhow::Result<serde_json::Value> {
        let base_url = self.proxy_base_url(binding);
        let mut options = serde_json::json!({ "baseURL": base_url });
        if binding
            .api_key
            .as_ref()
            .is_some_and(|key| !key.0.is_empty())
        {
            options["apiKey"] = serde_json::Value::String(format!("{{env:{api_key_env}}}"));
        }
        if let Some(headers) = &binding.custom_headers {
            let header_map: serde_json::Map<String, serde_json::Value> = headers
                .iter()
                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.0.clone())))
                .collect();
            options["headers"] = serde_json::Value::Object(header_map);
        }

        // `limit` is all-or-nothing in OpenCode's schema: if present, both
        // `context` and `output` are required. granite-cli only tracks a
        // context length, so `limit` is left out entirely rather than
        // guessing an output cap.
        let mut models = serde_json::Map::new();
        for name in model_names {
            models.insert(
                (*name).to_string(),
                serde_json::json!({
                    "name": name,
                }),
            );
        }

        let mut entry = serde_json::json!({
            "npm": "@ai-sdk/openai-compatible",
            "name": binding.provider_name,
            "options": options,
            "models": serde_json::Value::Object(models),
        });

        // Shallow merge so a user override of e.g. `headers` doesn't clobber
        // the generated `options`/`models`, and vice versa. Applied uniformly
        // to every generated provider entry (main model's and every
        // sub-agent's) -- there is deliberately no per-sub-agent override
        // knob yet.
        if let (Some(overrides), Some(target)) = (
            self.config
                .provider_overrides
                .as_ref()
                .and_then(serde_json::Value::as_object),
            entry.as_object_mut(),
        ) {
            for (key, value) in overrides {
                target.insert(key.clone(), value.clone());
            }
        }
        Ok(entry)
    }

    /// Groups the main model binding (if any) and every bound sub-agent's
    /// model binding by `provider_name`, collecting each group's distinct
    /// model names -- so two sub-agents (or a sub-agent and the main model)
    /// that happen to share the same underlying granite-cli provider instance
    /// land in one `provider.<name>` entry with multiple `models`, instead of
    /// one overwriting the other. Order is main-model-first, then
    /// `bound_sub_agents` order, which is also the order `env_overlay` and
    /// `launch` use to number each group's API-key env var
    /// (`provider_api_key_env`) -- the two must stay in lock-step.
    fn provider_groups(&self) -> Vec<(&AgentModelBinding, Vec<&str>)> {
        fn add<'a>(
            groups: &mut Vec<(&'a AgentModelBinding, Vec<&'a str>)>,
            binding: &'a AgentModelBinding,
        ) {
            if let Some((_, model_names)) = groups
                .iter_mut()
                .find(|(b, _)| b.provider_name == binding.provider_name)
            {
                if !model_names.contains(&binding.model_name.as_str()) {
                    model_names.push(&binding.model_name);
                }
            } else {
                groups.push((binding, vec![binding.model_name.as_str()]));
            }
        }

        let mut groups = Vec::new();
        if let Some(binding) = &self.bound_agent_model {
            add(&mut groups, binding);
        }
        for (_, sub_agent) in &self.bound_sub_agents {
            add(&mut groups, &sub_agent.model);
        }
        groups
    }

    /// Builds the `agent.<name>` entries for every bound sub-agent:
    /// `description`, `prompt`, `model` (as `<provider>/<model>`, per
    /// <https://opencode.ai/docs/agents/>), and `tools` when a tool
    /// allow-list was given. `tools` is OpenCode's legacy-but-still-supported
    /// boolean map (<https://opencode.ai/docs/agents/>,
    /// <https://opencode.ai/docs/permissions/>) rather than the newer
    /// `permission` config: `permission`'s named categories default to
    /// "allow" for anything not mentioned, which can't express "only these
    /// tools, everything else off" the way `{"*": false, ...}` can -- the
    /// same allow-list semantics `SubAgentBinding.tools` already has for the
    /// `claude` launcher. A tool with no mapping is dropped with a warning
    /// (per sub-agent), matching `ClaudeLauncher::build_agents_json`.
    ///
    /// `known_type` maps onto OpenCode's own built-in agent names (`explore`,
    /// `plan` -- see <https://opencode.ai/docs/agents/>) the same way
    /// `ClaudeLauncher` overrides Claude Code's built-in `Explore`/`Plan`
    /// sub-agents.
    fn build_agent_config(&self, ui: &dyn Ui) -> serde_json::Map<String, serde_json::Value> {
        self.bound_sub_agents
            .iter()
            .map(|(name, binding)| {
                let mut entry = serde_json::json!({
                    "description": binding.description,
                    "prompt": binding.prompt,
                    "mode": "subagent",
                    "model": format!("{}/{}", binding.model.provider_name, binding.model.model_name),
                });
                if !binding.tools.is_empty() {
                    let mut tools = serde_json::Map::new();
                    tools.insert("*".to_string(), serde_json::Value::Bool(false));
                    for tool in &binding.tools {
                        match self.map_tool_name(tool) {
                            Some(mapped) => {
                                tools.insert(mapped, serde_json::Value::Bool(true));
                            }
                            None => ui.warn(&format!(
                                "sub-agent '{name}': tool {tool:?} has no mapping for the opencode launcher, skipping"
                            )),
                        }
                    }
                    entry["tools"] = serde_json::Value::Object(tools);
                }
                let mapped_name = match binding.known_type {
                    Some(KnownSubAgent::Explore) => "explore".to_string(),
                    Some(KnownSubAgent::Plan) => "plan".to_string(),
                    _ => name.clone(),
                };
                (mapped_name, entry)
            })
            .collect()
    }

    /// Returns the baseURL to use for OpenCode provider entries. When a
    /// session proxy is active (usage tracking enabled), returns the proxy's
    /// local URL so all traffic flows through it for accounting -- the proxy
    /// dispatches by the `"model"` field in each request body. Otherwise
    /// delegates to `opencode_base_url` to compute the provider's real URL.
    fn proxy_base_url(&self, binding: &AgentModelBinding) -> String {
        match &self.model_proxy {
            Some(handle) => handle.local_base_url.clone(),
            None => opencode_base_url(binding),
        }
    }

    /// Resolves `{env:VAR_NAME}` placeholders in a JSON value with the current
    /// process environment. Leaves unknown variables as empty strings (matching
    /// OpenCode's own behavior). Recurses into objects and arrays.
    fn resolve_env_vars(value: &serde_json::Value) -> serde_json::Value {
        match value {
            serde_json::Value::String(s) => {
                if s.starts_with("{env:") && s.ends_with('}') {
                    let var_name = &s[5..s.len() - 1];
                    serde_json::Value::String(std::env::var(var_name).unwrap_or_default())
                } else {
                    value.clone()
                }
            }
            serde_json::Value::Object(map) => {
                let resolved: serde_json::Map<_, _> = map
                    .iter()
                    .map(|(k, v)| (k.clone(), Self::resolve_env_vars(v)))
                    .collect();
                serde_json::Value::Object(resolved)
            }
            serde_json::Value::Array(arr) => {
                let resolved: Vec<_> = arr.iter().map(Self::resolve_env_vars).collect();
                serde_json::Value::Array(resolved)
            }
            other => other.clone(),
        }
    }

    /// Loads and parses a user's OpenCode config file (JSON or JSONC).
    /// Strips `//` and `/* ... */` comments before parsing. Returns `None` if
    /// the file doesn't exist or can't be parsed.
    fn load_user_config(path: &Path) -> Option<serde_json::Value> {
        let content = std::fs::read_to_string(path).ok()?;
        let content = Self::strip_jsonc_comments(&content);
        serde_json::from_str(&content).ok()
    }

    /// Strip JSONC comments from `content`, respecting string literals (doesn't
    /// strip `//` or `/*` inside quoted strings).
    fn strip_jsonc_comments(content: &str) -> String {
        let mut result = String::with_capacity(content.len());
        let mut chars = content.chars().peekable();
        let mut in_string = false;
        let mut escape = false;

        while let Some(c) = chars.next() {
            if escape {
                result.push(c);
                escape = false;
                continue;
            }
            if c == '\\' && in_string {
                result.push(c);
                escape = true;
                continue;
            }
            if c == '"' {
                in_string = !in_string;
                result.push(c);
                continue;
            }
            if in_string {
                result.push(c);
                continue;
            }
            if c == '/' {
                if let Some(&next) = chars.peek() {
                    if next == '/' {
                        // Line comment: skip to end of line
                        while let Some(&ch) = chars.peek() {
                            if ch == '\n' {
                                break;
                            }
                            chars.next();
                        }
                        continue;
                    } else if next == '*' {
                        // Block comment: skip to */
                        chars.next(); // consume '*'
                        while let Some(ch) = chars.next() {
                            if ch == '*' && chars.peek() == Some(&'/') {
                                chars.next();
                                break;
                            }
                        }
                        continue;
                    }
                }
            }
            result.push(c);
        }
        result
    }

    /// Extracts the `provider` object from a parsed OpenCode config. Returns
    /// `None` if the config has no provider key or it's not an object.
    fn extract_providers(
        config: &serde_json::Value,
    ) -> Option<&serde_json::Map<String, serde_json::Value>> {
        config.get("provider").and_then(|v| v.as_object())
    }

    /// Discovers all providers the user has configured in their global and
    /// project OpenCode configs. Reads `~/.config/opencode/opencode.json`
    /// (global) and `{working_dir}/opencode.json` (project), extracts
    /// `provider` entries, and returns the merged provider map (project
    /// overrides global for conflicting keys).
    fn discover_user_providers(
        ctx: &LaunchContext,
    ) -> Option<serde_json::Map<String, serde_json::Value>> {
        let mut providers = serde_json::Map::new();

        // Load global config (~/.config/opencode/opencode.json). Entries are
        // kept verbatim -- `{env:VAR}` references included -- so secrets
        // never land in the generated config; only `baseURL` is resolved,
        // at proxy-registration time.
        if let Some(global_config) = Self::load_global_opencode_config()
            && let Some(global_providers) = Self::extract_providers(&global_config)
        {
            for (key, value) in global_providers {
                providers.insert(key.clone(), value.clone());
            }
        }

        // Load project config (overwrites global for conflicting keys)
        let project_path = ctx.working_dir.join("opencode.json");
        if let Some(project_config) = Self::load_user_config(&project_path)
            && let Some(project_providers) = Self::extract_providers(&project_config)
        {
            for (key, value) in project_providers {
                providers.insert(key.clone(), value.clone());
            }
        }

        if providers.is_empty() {
            None
        } else {
            Some(providers)
        }
    }

    /// Returns the path to OpenCode's global config file:
    /// `$XDG_CONFIG_HOME/opencode/opencode.json`, falling back to
    /// `~/.config/opencode/opencode.json`.
    fn global_opencode_config_path() -> Option<PathBuf> {
        if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME")
            && !xdg.is_empty()
        {
            return Some(PathBuf::from(xdg).join("opencode").join("opencode.json"));
        }
        dirs::home_dir().map(|home| home.join(".config").join("opencode").join("opencode.json"))
    }

    /// Loads OpenCode's global config file and returns parsed JSON, or None.
    fn load_global_opencode_config() -> Option<serde_json::Value> {
        let path = Self::global_opencode_config_path()?;
        Self::load_user_config(&path)
    }

    /// Registers discovered user providers on the session proxy so the proxy
    /// can route and track traffic for them. Each provider with a `baseURL`
    /// is registered under the proxy's `/providers/{name}` path prefix; the
    /// generated config points the provider's `baseURL` at that prefix (see
    /// `merge_user_providers_into_config`), so the proxy knows the upstream
    /// from the URL alone and any model the provider serves routes and
    /// tracks correctly without granite-cli knowing its name.
    fn register_user_providers_on_proxy(
        &self,
        proxy_handle: &ProxyHandle,
        user_providers: &serde_json::Map<String, serde_json::Value>,
    ) {
        for (provider_name, provider_entry) in user_providers {
            let Some(options) = provider_entry.get("options").and_then(|o| o.as_object()) else {
                continue;
            };

            let resolved_base_url = options.get("baseURL").map(Self::resolve_env_vars);
            let Some(base_url) = resolved_base_url.as_ref().and_then(|b| b.as_str()) else {
                continue;
            };

            // Skip if baseURL already points at the proxy
            if base_url.contains("127.0.0.1") || base_url.contains("localhost") {
                continue;
            }

            let label = provider_name.to_string();
            if let Err(e) =
                proxy_handle.register_provider(provider_name, base_url.to_string(), label)
            {
                alog_channel!(
                    MessageLevel::Debug3,
                    "failed to register provider '{}' on proxy: {}",
                    provider_name,
                    e
                );
            }
        }
    }

    /// Builds a single provider entry value for use in `discover_env_providers`.
    /// `npm` is the npm package name, `name` is the provider id, `base_url` is
    /// the well-known base URL, and `api_key_env` is the `{env:VAR}` token.
    fn make_env_provider_entry(
        npm: &str,
        name: &str,
        base_url: &str,
        api_key_env: &str,
    ) -> serde_json::Value {
        let mut options = serde_json::Map::new();
        options.insert(
            "baseURL".to_string(),
            serde_json::Value::String(base_url.to_string()),
        );
        options.insert(
            "apiKey".to_string(),
            serde_json::Value::String(api_key_env.to_string()),
        );
        let mut entry = serde_json::Map::new();
        entry.insert(
            "npm".to_string(),
            serde_json::Value::String(npm.to_string()),
        );
        entry.insert(
            "name".to_string(),
            serde_json::Value::String(name.to_string()),
        );
        entry.insert("options".to_string(), serde_json::Value::Object(options));
        serde_json::Value::Object(entry)
    }

    /// Discovers env-based providers by checking for known API key environment
    /// variables. Returns a map of provider name -> provider entry pointing at
    /// the well-known base URL for each provider. These are providers that
    /// OpenCode auto-loads when the corresponding env var is set, but don't
    /// appear explicitly in the user's config files.
    ///
    /// The provider list is derived from OpenCode's own provider registry:
    /// https://github.com/anomalyco/opencode/blob/51f86c853791c41656fb0adcf9413291e4996b87/packages/llm/script/setup-recording-env.ts#L170
    /// This list should be kept in sync with upstream if new providers are added.
    fn discover_env_providers() -> serde_json::Map<String, serde_json::Value> {
        // Each tuple: (map key, npm pkg, provider name, base URL, api-key env token)
        let known: &[(&str, &str, &str, &str, &str)] = &[
            (
                "openai",
                "@openai/openai",
                "openai",
                "https://api.openai.com/v1",
                "{env:OPENAI_API_KEY}",
            ),
            (
                "anthropic",
                "@anthropic-ai/anthropic",
                "anthropic",
                "https://api.anthropic.com",
                "{env:ANTHROPIC_API_KEY}",
            ),
            (
                "google",
                "@google/generative-ai",
                "google",
                "https://generativelanguage.googleapis.com/v1beta",
                "{env:GOOGLE_API_KEY}",
            ),
            (
                "groq",
                "@ai-sdk/openai-compatible",
                "groq",
                "https://api.groq.com/openai/v1",
                "{env:GROQ_API_KEY}",
            ),
            (
                "openrouter",
                "@ai-sdk/openai-compatible",
                "openrouter",
                "https://openrouter.ai/api/v1",
                "{env:OPENROUTER_API_KEY}",
            ),
            (
                "cohere",
                "@ai-sdk/openai-compatible",
                "cohere",
                "https://api.cohere.com/v1",
                "{env:CO_API_KEY}",
            ),
            (
                "mistral",
                "@ai-sdk/openai-compatible",
                "mistral",
                "https://api.mistral.ai/v1",
                "{env:MISTRAL_API_KEY}",
            ),
        ];

        // Extract the env var name from the "{env:VAR}" token (strip "{env:" prefix and "}" suffix)
        let mut providers = serde_json::Map::new();
        for (key, npm, name, base_url, api_key_env) in known {
            let env_var = &api_key_env[5..api_key_env.len() - 1];
            if std::env::var(env_var).is_ok() {
                providers.insert(
                    key.to_string(),
                    Self::make_env_provider_entry(npm, name, base_url, api_key_env),
                );
            }
        }
        providers
    }

    /// Merges user-discovered and env-based providers into the generated config.
    /// For each provider, creates a provider entry with `baseURL` pointing at
    /// the proxy so all traffic flows through it. The proxy knows the real
    /// upstream URL from `register_user_providers_on_proxy` and forwards
    /// requests with usage tracking.
    ///
    /// Granite-cli provider entries (built from bindings) take precedence: if a
    /// user also has a provider with the same name, our granite-cli entry
    /// wins (since it's added to the map after the user entries).
    /// The proxy URL a discovered provider's `baseURL` is rewritten to:
    /// the session proxy's `/providers/{name}` path prefix, from which the
    /// proxy resolves the real upstream registered in
    /// `register_user_providers_on_proxy`.
    fn provider_proxy_url(&self, provider_name: &str) -> Option<String> {
        self.model_proxy.as_ref().map(|handle| {
            format!(
                "{}/providers/{}",
                handle.local_base_url.trim_end_matches('/'),
                provider_name
            )
        })
    }

    fn merge_user_providers_into_config(
        &self,
        user_providers: &serde_json::Map<String, serde_json::Value>,
        env_providers: &serde_json::Map<String, serde_json::Value>,
        granite_providers: &serde_json::Map<String, serde_json::Value>,
    ) -> serde_json::Map<String, serde_json::Value> {
        let mut merged = serde_json::Map::new();

        // Add user-discovered providers (redirected to proxy)
        for (name, entry) in user_providers {
            if let Some(entry_value) = entry.as_object() {
                let mut proxied = entry_value.clone();
                if let Some(options_obj) = proxied
                    .get_mut("options")
                    .and_then(|options| options.as_object_mut())
                    && let Some(real_url) = options_obj.get("baseURL").and_then(|b| b.as_str())
                    && !real_url.contains("127.0.0.1")
                    && !real_url.contains("localhost")
                    && let Some(proxy_url) = self.provider_proxy_url(name)
                {
                    options_obj.insert("baseURL".to_string(), serde_json::Value::String(proxy_url));
                }
                merged.insert(name.clone(), serde_json::Value::Object(proxied));
            }
        }

        // Add env-based providers (redirected to proxy)
        for (name, entry) in env_providers {
            if let Some(entry_value) = entry.as_object() {
                let mut proxied = entry_value.clone();
                if let Some(options_obj) = proxied
                    .get_mut("options")
                    .and_then(|options| options.as_object_mut())
                    && let Some(proxy_url) = self.provider_proxy_url(name)
                {
                    options_obj.insert("baseURL".to_string(), serde_json::Value::String(proxy_url));
                }
                merged.insert(name.clone(), serde_json::Value::Object(proxied));
            }
        }

        // Add granite-cli providers (overrides user providers with same name)
        for (name, entry) in granite_providers {
            merged.insert(name.clone(), entry.clone());
        }

        merged
    }
}

/// The env var an OpenCode provider entry's `apiKey` interpolates from, for
/// the `index`-th distinct provider in `provider_groups()` order. Index `0`
/// (conventionally the main model's provider, when bound) keeps the original
/// unsuffixed name for backwards compatibility; every additional distinct
/// provider (a sub-agent's, when it differs from the main model's) gets its
/// own suffixed var so multiple secrets can be injected into one launch
/// without colliding.
fn provider_api_key_env(index: usize) -> String {
    if index == 0 {
        API_KEY_ENV.to_string()
    } else {
        format!("{API_KEY_ENV}_{index}")
    }
}

/// OpenCode's `baseURL` is the API root the SDK appends operation paths to
/// (e.g. `/chat/completions`), so drop that trailing operation from the
/// binding's full endpoint path and keep the version prefix.
fn opencode_base_url(binding: &AgentModelBinding) -> String {
    let root = binding.base_url.trim_end_matches('/');
    let prefix = binding
        .endpoint_path
        .strip_suffix("/chat/completions")
        .unwrap_or("");
    format!("{root}{prefix}")
}

/// The granite-cli-owned config file this launcher instance writes and points
/// `OPENCODE_CONFIG` at. Lives under the launcher state dir rather than the
/// user's own OpenCode config directory -- it is never read by anything else.
fn opencode_config_path(ctx: &LaunchContext) -> anyhow::Result<PathBuf> {
    Ok(crate::config::Config::launcher_state_dir(&ctx.launcher_id)?.join(CONFIG_FILE))
}

/// Builds the top-level `opencode.json` shape: the main model (if bound)
/// selected via the top-level `model` key (`provider/model`) so it applies
/// uniformly across the TUI, `run`, `attach`, and GitHub Action; a `provider`
/// block with one entry per distinct provider (main model's and/or each
/// sub-agent's, pre-built by the caller via `provider_groups`/
/// `provider_entry`); an `agent` block (if any sub-agents are bound, pre-built
/// via `build_agent_config`); and an `mcp` block (if any MCP servers are
/// bound), using opencode's `McpLocalConfig`/`McpRemoteConfig` shape (see
/// <https://opencode.ai/config.json>).
fn generate_config(
    binding: Option<&AgentModelBinding>,
    providers: serde_json::Map<String, serde_json::Value>,
    agent: serde_json::Map<String, serde_json::Value>,
    mcp_bindings: &[(String, McpBinding)],
) -> serde_json::Value {
    let mut config = serde_json::json!({ "$schema": "https://opencode.ai/config.json" });
    if let Some(binding) = binding {
        config["model"] =
            serde_json::Value::String(format!("{}/{}", binding.provider_name, binding.model_name));
    }
    if !providers.is_empty() {
        config["provider"] = serde_json::Value::Object(providers);
    }
    if !agent.is_empty() {
        config["agent"] = serde_json::Value::Object(agent);
    }
    if !mcp_bindings.is_empty() {
        let mut mcp = serde_json::Map::new();
        for (name, binding) in mcp_bindings {
            mcp.insert(name.clone(), {
                match binding {
                    McpBinding::Stdio {
                        command, args, env, ..
                    } => {
                        let mut full_command = vec![command.clone()];
                        full_command.extend(args.iter().cloned());
                        serde_json::json!({
                            "type": "local",
                            "command": full_command,
                            "environment": env,
                        })
                    }
                    McpBinding::Http { url, headers, .. }
                    | McpBinding::Sse { url, headers, .. } => {
                        serde_json::json!({
                            "type": "remote",
                            "url": url,
                            "headers": headers,
                        })
                    }
                }
            });
        }
        config["mcp"] = serde_json::Value::Object(mcp);
    }
    config
}

fn write_opencode_config(path: &Path, config: &serde_json::Value) -> anyhow::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create {}", parent.display()))?;
    }
    let mut content = serde_json::to_string_pretty(config)?;
    content.push('\n');
    std::fs::write(path, content).with_context(|| format!("Failed to write {}", path.display()))
}

/*-- tests --*/

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::{Named, Secret};
    use crate::utils::ui::base::tests::CaptureUi;

    fn launcher(cfg: serde_json::Value) -> OpenCodeLauncher {
        OpenCodeLauncher::new("opencode", &cfg, &crate::config::Config::default())
    }

    fn binding() -> AgentModelBinding {
        AgentModelBinding {
            api_type: ApiType::OpenAI,
            provider_name: "my-ollama".to_string(),
            base_url: "http://localhost:11434".to_string(),
            model_name: "granite4.1:8b".to_string(),
            endpoint_path: "/v1/chat/completions".to_string(),
            api_key: None,
            verify_ssl: true,
            context_length: Some(131072),
            custom_headers: None,
        }
    }

    fn bound(cfg: serde_json::Value, binding: AgentModelBinding) -> OpenCodeLauncher {
        let mut l = launcher(cfg);
        l.bound_agent_model = Some(binding);
        l
    }

    fn ctx(dry_run: bool) -> LaunchContext {
        LaunchContext {
            launcher_id: "opencode".to_string(),
            working_dir: PathBuf::from("/tmp"),
            base_env: std::collections::HashMap::new(),
            dry_run,
        }
    }

    // -- command resolution ----------------------------------------------------

    #[test]
    fn command_defaults_to_opencode() {
        assert_eq!(launcher(serde_json::json!({})).command(), "opencode");
    }

    #[test]
    fn command_uses_explicit_path_when_set() {
        let l = launcher(serde_json::json!({ "command_path": "/opt/bin/opencode" }));
        assert_eq!(l.command(), "/opt/bin/opencode");
    }

    #[test]
    fn validate_command_err_for_nonexistent_explicit_path() {
        let l = launcher(serde_json::json!({ "command_path": "/no/such/path/opencode" }));
        assert!(l.validate_command().is_err());
    }

    #[test]
    fn validate_command_falls_back_to_path_for_bare_command_name() {
        let l = launcher(serde_json::json!({ "command_path": "ls" }));
        assert!(l.validate_command().is_ok());
    }

    // -- metadata / schema -----------------------------------------------------

    #[test]
    fn metadata_name_is_opencode_cli() {
        let meta = OpenCodeLauncher::metadata();
        assert_eq!(meta.name, "OpenCode CLI");
        assert_eq!(meta.default_command, "opencode");
        assert!(
            meta.supported_capabilities
                .contains(&BindingType::AgentModel)
        );
    }

    #[test]
    fn metadata_supports_sub_agent_binding() {
        let meta = OpenCodeLauncher::metadata();
        assert!(meta.supported_capabilities.contains(&BindingType::SubAgent));
    }

    #[test]
    fn instance_id_round_trips_from_construction() {
        let l = OpenCodeLauncher::new(
            "opencode-local",
            &serde_json::json!({}),
            &crate::config::Config::default(),
        );
        assert_eq!(l.instance_id(), "opencode-local");
    }

    #[test]
    fn config_schema_exposes_only_command_path_and_overrides() {
        use crate::launchers::base::LauncherFactory;
        let mut factory = LauncherFactory::new();
        factory.register::<OpenCodeLauncher>("opencode");
        let schema = factory.config_schema("opencode").unwrap();
        let props = schema
            .get("properties")
            .and_then(|p| p.as_object())
            .unwrap();
        assert!(props.contains_key("command_path"));
        assert!(props.contains_key("provider_overrides"));
        // The OpenCode provider name comes from the binding, never from
        // launcher config.
        assert!(!props.contains_key("provider_name"));
    }

    // -- provider entry --------------------------------------------------------

    #[test]
    fn provider_entry_describes_bound_model() {
        let b = binding();
        let entry = launcher(serde_json::json!({}))
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["npm"], "@ai-sdk/openai-compatible");
        assert_eq!(entry["options"]["baseURL"], "http://localhost:11434/v1");
        assert_eq!(entry["models"]["granite4.1:8b"]["name"], "granite4.1:8b");
        // No output-token data means no `limit` at all: OpenCode requires
        // both `context` and `output` together when `limit` is present.
        assert!(entry["models"]["granite4.1:8b"].get("limit").is_none());
        // No key means no apiKey field at all.
        assert!(entry["options"].get("apiKey").is_none());
    }

    #[test]
    fn provider_entry_describes_multiple_models_for_one_provider() {
        let b = binding();
        let entry = launcher(serde_json::json!({}))
            .provider_entry(&b, &["granite4.1:8b", "granite4.1:3b"], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["models"]["granite4.1:8b"]["name"], "granite4.1:8b");
        assert_eq!(entry["models"]["granite4.1:3b"]["name"], "granite4.1:3b");
    }

    #[test]
    fn provider_entry_interpolates_env_when_key_present() {
        let b = AgentModelBinding {
            api_key: Some(Secret::from("sk-test")),
            ..binding()
        };
        let entry = launcher(serde_json::json!({}))
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(
            entry["options"]["apiKey"],
            "{env:GRANITE_CLI_OPENCODE_API_KEY}"
        );
    }

    #[test]
    fn provider_entry_uses_the_given_api_key_env_name() {
        let b = AgentModelBinding {
            api_key: Some(Secret::from("sk-test")),
            ..binding()
        };
        let entry = launcher(serde_json::json!({}))
            .provider_entry(
                &b,
                &[b.model_name.as_str()],
                "GRANITE_CLI_OPENCODE_API_KEY_1",
            )
            .unwrap();
        assert_eq!(
            entry["options"]["apiKey"],
            "{env:GRANITE_CLI_OPENCODE_API_KEY_1}"
        );
    }

    #[test]
    fn provider_entry_omits_api_key_for_empty_secret() {
        let b = AgentModelBinding {
            api_key: Some(Secret::from("")),
            ..binding()
        };
        let entry = launcher(serde_json::json!({}))
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert!(entry["options"].get("apiKey").is_none());
    }

    #[test]
    fn provider_entry_merges_overrides() {
        let l = launcher(serde_json::json!({
            "provider_overrides": { "headers": { "X-Custom": "1" } }
        }));
        let b = binding();
        let entry = l
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["headers"]["X-Custom"], "1");
        // Generated keys survive the merge.
        assert_eq!(entry["options"]["baseURL"], "http://localhost:11434/v1");
    }

    #[test]
    fn provider_entry_overrides_win_on_conflict() {
        let l = launcher(serde_json::json!({
            "provider_overrides": { "npm": "@ai-sdk/openai" }
        }));
        let b = binding();
        let entry = l
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["npm"], "@ai-sdk/openai");
    }

    #[test]
    fn provider_entry_includes_custom_headers_when_present() {
        let mut headers = std::collections::HashMap::new();
        headers.insert(
            "Helicone-Cache-Enabled".to_string(),
            Secret("true".to_string()),
        );
        headers.insert(
            "Helicone-User-Id".to_string(),
            Secret("opencode".to_string()),
        );
        let b = AgentModelBinding {
            custom_headers: Some(headers),
            ..binding()
        };
        let entry = launcher(serde_json::json!({}))
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(
            entry["options"]["headers"]["Helicone-Cache-Enabled"],
            "true"
        );
        assert_eq!(entry["options"]["headers"]["Helicone-User-Id"], "opencode");
    }

    // -- provider_api_key_env ---------------------------------------------------

    #[test]
    fn provider_api_key_env_keeps_unsuffixed_name_at_index_zero() {
        assert_eq!(provider_api_key_env(0), "GRANITE_CLI_OPENCODE_API_KEY");
    }

    #[test]
    fn provider_api_key_env_suffixes_by_index_beyond_zero() {
        assert_eq!(provider_api_key_env(1), "GRANITE_CLI_OPENCODE_API_KEY_1");
        assert_eq!(provider_api_key_env(2), "GRANITE_CLI_OPENCODE_API_KEY_2");
    }

    // -- provider_groups ---------------------------------------------------------

    fn sub_agent_binding(
        description: &str,
        provider_name: &str,
        model_name: &str,
        tools: Vec<ToolName>,
    ) -> SubAgentBinding {
        SubAgentBinding {
            description: description.to_string(),
            prompt: "You are a helpful sub-agent.".to_string(),
            tools,
            model: AgentModelBinding {
                provider_name: provider_name.to_string(),
                model_name: model_name.to_string(),
                ..binding()
            },
            known_type: None,
        }
    }

    #[test]
    fn provider_groups_is_empty_with_nothing_bound() {
        let l = launcher(serde_json::json!({}));
        assert!(l.provider_groups().is_empty());
    }

    #[test]
    fn provider_groups_includes_main_model_first() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_agent_model = Some(binding());
        let groups = l.provider_groups();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].0.provider_name, "my-ollama");
        assert_eq!(groups[0].1, vec!["granite4.1:8b"]);
    }

    #[test]
    fn provider_groups_gives_a_distinct_provider_its_own_group() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_agent_model = Some(binding());
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "other-provider", "other-model", vec![]),
        )];
        let groups = l.provider_groups();
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[1].0.provider_name, "other-provider");
        assert_eq!(groups[1].1, vec!["other-model"]);
    }

    #[test]
    fn provider_groups_merges_model_names_sharing_a_provider() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_agent_model = Some(binding());
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "my-ollama", "granite4.1:3b", vec![]),
        )];
        let groups = l.provider_groups();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].1, vec!["granite4.1:8b", "granite4.1:3b"]);
    }

    #[test]
    fn provider_groups_dedupes_identical_model_name_for_shared_provider() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_agent_model = Some(binding());
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "my-ollama", "granite4.1:8b", vec![]),
        )];
        let groups = l.provider_groups();
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].1, vec!["granite4.1:8b"]);
    }

    // -- map_tool_name -----------------------------------------------------------

    #[test]
    fn map_tool_name_covers_every_canonical_variant_and_formats_mcp_references() {
        let l = launcher(serde_json::json!({}));
        assert_eq!(
            l.map_tool_name(&ToolName::FileRead),
            Some("read".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::FileWrite),
            Some("write".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::FileEdit),
            Some("edit".to_string())
        );
        assert_eq!(l.map_tool_name(&ToolName::Search), Some("grep".to_string()));
        assert_eq!(
            l.map_tool_name(&ToolName::FileSearch),
            Some("glob".to_string())
        );
        assert_eq!(l.map_tool_name(&ToolName::Shell), Some("bash".to_string()));
        assert_eq!(
            l.map_tool_name(&ToolName::WebFetch),
            Some("webfetch".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::WebSearch),
            Some("websearch".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::Mcp {
                server: "vision".to_string(),
                tool: None,
            }),
            Some("vision_*".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::Mcp {
                server: "vision".to_string(),
                tool: Some("vlm_compare_images".to_string()),
            }),
            Some("vision_vlm_compare_images".to_string())
        );
        assert_eq!(
            l.map_tool_name(&ToolName::Other("SomeRawTool".to_string())),
            Some("SomeRawTool".to_string())
        );
    }

    // -- build_agent_config -------------------------------------------------------

    #[test]
    fn build_agent_config_includes_description_prompt_and_model_but_omits_empty_tools() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "my-ollama", "granite4.1:8b", vec![]),
        )];
        let ui = CaptureUi::default();
        let agent = l.build_agent_config(&ui);
        let entry = &agent["reviewer"];
        assert_eq!(entry["description"], "Reviews code");
        assert_eq!(entry["prompt"], "You are a helpful sub-agent.");
        assert_eq!(entry["model"], "my-ollama/granite4.1:8b");
        assert!(entry.get("tools").is_none());
    }

    #[test]
    fn build_agent_config_denies_by_default_and_allows_only_listed_tools() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding(
                "Reviews code",
                "my-ollama",
                "granite4.1:8b",
                vec![ToolName::FileRead, ToolName::Search],
            ),
        )];
        let ui = CaptureUi::default();
        let agent = l.build_agent_config(&ui);
        assert_eq!(
            agent["reviewer"]["tools"],
            serde_json::json!({ "*": false, "read": true, "grep": true })
        );
    }

    #[test]
    fn build_agent_config_covers_every_bound_sub_agent_by_instance_id() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_sub_agents = vec![
            (
                "reviewer".to_string(),
                sub_agent_binding("Reviews code", "my-ollama", "model-a", vec![]),
            ),
            (
                "summarizer".to_string(),
                sub_agent_binding("Summarizes text", "my-ollama", "model-b", vec![]),
            ),
        ];
        let ui = CaptureUi::default();
        let agent = l.build_agent_config(&ui);
        assert_eq!(agent.len(), 2);
        assert_eq!(agent["reviewer"]["model"], "my-ollama/model-a");
        assert_eq!(agent["summarizer"]["model"], "my-ollama/model-b");
    }

    #[test]
    fn build_agent_config_maps_known_types_onto_opencodes_own_builtin_agent_names() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_sub_agents = vec![(
            "my-explorer".to_string(),
            SubAgentBinding {
                known_type: Some(KnownSubAgent::Explore),
                ..sub_agent_binding("Explores code", "my-ollama", "granite4.1:8b", vec![])
            },
        )];
        let ui = CaptureUi::default();
        let agent = l.build_agent_config(&ui);
        assert!(agent.contains_key("explore"));
        assert!(!agent.contains_key("my-explorer"));
    }

    // -- base url ----------------------------------------------------------

    #[test]
    fn base_url_keeps_version_prefix_and_drops_operation() {
        assert_eq!(opencode_base_url(&binding()), "http://localhost:11434/v1");
    }

    #[test]
    fn base_url_trims_trailing_slash_from_provider_url() {
        let b = AgentModelBinding {
            base_url: "http://localhost:1234/".to_string(),
            ..binding()
        };
        assert_eq!(opencode_base_url(&b), "http://localhost:1234/v1");
    }

    // -- generate_config -----------------------------------------------------

    #[test]
    fn generate_config_nests_entry_under_provider_name_and_sets_default_model() {
        let mut providers = serde_json::Map::new();
        providers.insert(
            "my-ollama".to_string(),
            serde_json::json!({ "npm": "@ai-sdk/openai-compatible" }),
        );
        let config = generate_config(Some(&binding()), providers, serde_json::Map::new(), &[]);
        assert_eq!(config["$schema"], "https://opencode.ai/config.json");
        assert_eq!(config["model"], "my-ollama/granite4.1:8b");
        assert_eq!(
            config["provider"]["my-ollama"]["npm"],
            "@ai-sdk/openai-compatible"
        );
    }

    #[test]
    fn generate_config_writes_mcp_block_without_a_model_binding() {
        let mcp_binding = McpBinding::Http {
            url: "http://127.0.0.1:9999".to_string(),
            headers: Default::default(),
            timeout: None,
        };
        let config = generate_config(
            None,
            serde_json::Map::new(),
            serde_json::Map::new(),
            &[("vision".to_string(), mcp_binding)],
        );
        assert!(config.get("model").is_none());
        assert!(config.get("provider").is_none());
        assert_eq!(config["mcp"]["vision"]["type"], "remote");
        assert_eq!(config["mcp"]["vision"]["url"], "http://127.0.0.1:9999");
    }

    #[test]
    fn generate_config_writes_agent_block_when_sub_agents_present() {
        let mut agent = serde_json::Map::new();
        agent.insert(
            "reviewer".to_string(),
            serde_json::json!({ "description": "Reviews code" }),
        );
        let config = generate_config(None, serde_json::Map::new(), agent, &[]);
        assert!(config.get("model").is_none());
        assert_eq!(config["agent"]["reviewer"]["description"], "Reviews code");
    }

    #[test]
    fn generate_config_omits_agent_key_when_no_sub_agents_bound() {
        let config = generate_config(
            Some(&binding()),
            serde_json::Map::new(),
            serde_json::Map::new(),
            &[],
        );
        assert!(config.get("agent").is_none());
    }

    // -- env overlay -----------------------------------------------------------

    #[tokio::test]
    async fn env_overlay_is_empty_without_a_binding() {
        let overlay = launcher(serde_json::json!({}))
            .env_overlay(&ctx(false))
            .await
            .unwrap();
        assert!(overlay.is_empty());
    }

    #[tokio::test]
    async fn env_overlay_redirects_config_and_exports_api_key() {
        let b = AgentModelBinding {
            api_key: Some(Secret::from("sk-test")),
            ..binding()
        };
        let overlay = bound(serde_json::json!({}), b)
            .env_overlay(&ctx(false))
            .await
            .unwrap();

        let config = overlay
            .iter()
            .find(|b| b.key == "OPENCODE_CONFIG")
            .expect("config redirect");
        assert!(
            Path::new(&config.value).ends_with(
                Path::new("launcher-state")
                    .join("opencode")
                    .join("opencode.json")
            ),
            "{}",
            config.value
        );

        let key = overlay
            .iter()
            .find(|b| b.key == "GRANITE_CLI_OPENCODE_API_KEY")
            .expect("api key");
        assert_eq!(key.value, "sk-test");
    }

    #[tokio::test]
    async fn env_overlay_omits_api_key_when_provider_has_none() {
        let overlay = bound(serde_json::json!({}), binding())
            .env_overlay(&ctx(false))
            .await
            .unwrap();
        assert!(
            !overlay
                .iter()
                .any(|b| b.key == "GRANITE_CLI_OPENCODE_API_KEY")
        );
    }

    #[tokio::test]
    async fn env_overlay_exports_one_api_key_per_distinct_provider_when_sub_agents_present() {
        let main = AgentModelBinding {
            api_key: Some(Secret::from("main-key")),
            ..binding()
        };
        let mut l = bound(serde_json::json!({}), main);
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            SubAgentBinding {
                model: AgentModelBinding {
                    provider_name: "other-provider".to_string(),
                    model_name: "other-model".to_string(),
                    api_key: Some(Secret::from("sub-key")),
                    ..binding()
                },
                ..sub_agent_binding("Reviews code", "other-provider", "other-model", vec![])
            },
        )];

        let overlay = l.env_overlay(&ctx(false)).await.unwrap();

        let main_key = overlay
            .iter()
            .find(|b| b.key == "GRANITE_CLI_OPENCODE_API_KEY")
            .expect("main model's api key");
        assert_eq!(main_key.value, "main-key");

        let sub_key = overlay
            .iter()
            .find(|b| b.key == "GRANITE_CLI_OPENCODE_API_KEY_1")
            .expect("sub-agent's own api key, on its own suffixed env var");
        assert_eq!(sub_key.value, "sub-key");
    }

    #[tokio::test]
    async fn env_overlay_redirects_config_when_only_a_sub_agent_is_bound() {
        let mut l = launcher(serde_json::json!({}));
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "my-ollama", "granite4.1:8b", vec![]),
        )];
        let overlay = l.env_overlay(&ctx(false)).await.unwrap();
        assert!(
            overlay.iter().any(|b| b.key == "OPENCODE_CONFIG"),
            "a sub-agent alone (no main model, no MCP) must still redirect OPENCODE_CONFIG"
        );
    }

    // -- launch ----------------------------------------------------------------

    // Deliberately reads whatever `GRANITE_CLI_HOME` is ambient rather than
    // setting it: env mutation would race the other tests in this binary that
    // point that var at their own tempdirs.
    #[tokio::test]
    async fn dry_run_launch_reports_without_writing_anything() {
        let state_dir = crate::config::Config::launcher_state_dir("opencode").unwrap();
        let existed_before = state_dir.exists();

        let l = bound(serde_json::json!({ "command_path": "ls" }), binding());
        let ui = CaptureUi::default();
        let status = l
            .launch(&["--help".to_string()], &ctx(true), &ui)
            .await
            .unwrap();
        assert!(status.success());

        let infos = ui.infos.borrow();
        assert!(
            infos
                .iter()
                .any(|m| m.contains("Would write OpenCode config")),
            "expected a dry-run notice, got {infos:?}"
        );
        assert!(
            infos
                .iter()
                .any(|m| m.contains(r#""model": "my-ollama/granite4.1:8b""#)),
            "expected the generated config to select the model, got {infos:?}"
        );
        assert!(
            infos.iter().any(|m| m.contains("args: --help")),
            "expected caller args to pass through unmodified, got {infos:?}"
        );
        assert_eq!(
            state_dir.exists(),
            existed_before,
            "dry run must not create {}",
            state_dir.display()
        );
    }

    #[tokio::test]
    async fn launch_without_binding_passes_args_through_unchanged() {
        let l = launcher(serde_json::json!({ "command_path": "ls" }));
        let ui = CaptureUi::default();
        l.launch(&["--version".to_string()], &ctx(true), &ui)
            .await
            .unwrap();

        let infos = ui.infos.borrow();
        assert!(infos.iter().any(|m| m.contains("args: --version")));
        assert!(
            !infos
                .iter()
                .any(|m| m.contains("Would write OpenCode config"))
        );
        // Without a binding there is no generated config, so OpenCode keeps
        // using its own config chain.
        assert!(!infos.iter().any(|m| m.contains(CONFIG_ENV)));
    }

    #[tokio::test]
    async fn dry_run_launch_with_sub_agents_writes_agent_and_provider_blocks() {
        let mut l = bound(serde_json::json!({ "command_path": "ls" }), binding());
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding(
                "Reviews code",
                "other-provider",
                "other-model",
                vec![ToolName::FileRead],
            ),
        )];
        let ui = CaptureUi::default();
        l.launch(&[], &ctx(true), &ui).await.unwrap();

        let infos = ui.infos.borrow();
        let dump = infos.join("\n");
        assert!(dump.contains(r#""reviewer""#), "{dump}");
        assert!(dump.contains(r#""my-ollama/granite4.1:8b""#), "{dump}");
        assert!(dump.contains(r#""other-provider""#), "{dump}");
        // Both providers get their own entry, keyed by provider name.
        assert!(dump.contains(r#""my-ollama": {"#), "{dump}");
        assert!(dump.contains(r#""other-provider": {"#), "{dump}");
    }

    #[tokio::test]
    async fn dry_run_launch_with_only_a_sub_agent_still_writes_a_config() {
        let mut l = launcher(serde_json::json!({ "command_path": "ls" }));
        l.bound_sub_agents = vec![(
            "reviewer".to_string(),
            sub_agent_binding("Reviews code", "my-ollama", "granite4.1:8b", vec![]),
        )];
        let ui = CaptureUi::default();
        l.launch(&[], &ctx(true), &ui).await.unwrap();

        let infos = ui.infos.borrow();
        assert!(
            infos
                .iter()
                .any(|m| m.contains("Would write OpenCode config")),
            "a sub-agent alone (no main model, no MCP) must still trigger config generation, got {infos:?}"
        );
    }

    /// Minimal `Capability` double that always resolves to a fixed
    /// `SubAgentBinding`, mirroring `ClaudeLauncher`'s test of the same name.
    struct FakeSubAgentCapability {
        instance_id: String,
        binding: SubAgentBinding,
    }

    impl crate::registry::Named for FakeSubAgentCapability {
        fn instance_id(&self) -> &str {
            &self.instance_id
        }
    }

    #[async_trait]
    impl Capability for FakeSubAgentCapability {
        fn name(&self) -> &str {
            "Fake Sub-Agent"
        }
        fn description(&self) -> &str {
            "test double"
        }
        fn binding_types(&self) -> HashSet<BindingType> {
            HashSet::from([BindingType::SubAgent])
        }
        async fn bind(
            &self,
            _request: crate::capabilities::BindingRequest,
        ) -> anyhow::Result<Binding> {
            Ok(Binding::SubAgent(self.binding.clone()))
        }
    }

    #[tokio::test]
    async fn bind_capability_pushes_sub_agent_binding() {
        let mut l = launcher(serde_json::json!({}));
        let cap = FakeSubAgentCapability {
            instance_id: "reviewer".to_string(),
            binding: sub_agent_binding("Reviews code", "my-ollama", "granite4.1:8b", vec![]),
        };
        l.bind_capability(&cap).await.unwrap();
        assert_eq!(l.bound_sub_agents.len(), 1);
        assert_eq!(l.bound_sub_agents[0].0, "reviewer");
        assert_eq!(l.bound_sub_agents[0].1.model.model_name, "granite4.1:8b");
    }

    // -- proxy base url --------------------------------------------------------

    #[tokio::test]
    async fn proxy_base_url_returns_proxy_url_when_model_proxy_is_set() {
        let b = binding();
        let server = crate::proxy::ProxyServer::start().unwrap();
        let mut l = launcher(serde_json::json!({}));
        l.model_proxy = Some(server.handle.clone());
        assert_eq!(l.proxy_base_url(&b), server.handle.local_base_url);
        server.shutdown().await;
    }

    #[test]
    fn proxy_base_url_returns_regular_url_when_no_model_proxy() {
        let b = binding();
        let l = launcher(serde_json::json!({}));
        assert_eq!(l.proxy_base_url(&b), opencode_base_url(&b));
    }

    #[tokio::test]
    async fn provider_entry_uses_proxy_url_when_model_proxy_is_active() {
        let server = crate::proxy::ProxyServer::start().unwrap();
        let mut l = launcher(serde_json::json!({}));
        l.model_proxy = Some(server.handle.clone());
        let b = binding();
        let entry = l
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["options"]["baseURL"], server.handle.local_base_url);
        server.shutdown().await;
    }

    #[test]
    fn provider_entry_uses_real_url_when_no_model_proxy() {
        let l = launcher(serde_json::json!({}));
        let b = binding();
        let entry = l
            .provider_entry(&b, &[b.model_name.as_str()], API_KEY_ENV)
            .unwrap();
        assert_eq!(entry["options"]["baseURL"], opencode_base_url(&b));
    }

    #[tokio::test]
    async fn dry_run_launch_with_proxy_redirects_base_url() {
        let server = crate::proxy::ProxyServer::start().unwrap();
        let mut l = bound(serde_json::json!({ "command_path": "ls" }), binding());
        l.model_proxy = Some(server.handle.clone());
        let ui = CaptureUi::default();
        l.launch(&[], &ctx(true), &ui).await.unwrap();

        let dump = ui.infos.borrow().join("\n");
        assert!(dump.contains(&server.handle.local_base_url), "{dump}");
        server.shutdown().await;
    }

    // -- JSONC parsing -----------------------------------------------------------

    #[test]
    fn strip_jsonc_comments_strips_line_comments() {
        let input = r#"{ "key": "value" // trailing comment }"#;
        let result = OpenCodeLauncher::strip_jsonc_comments(input);
        assert!(
            !result.contains("//"),
            "line comments should be stripped: {result}"
        );
        assert!(result.contains("\"value\""), "value should remain");
    }

    #[test]
    fn strip_jsonc_comments_strips_block_comments() {
        let input = r#"{ "key": "value" /* block comment */ }"#;
        let result = OpenCodeLauncher::strip_jsonc_comments(input);
        assert!(
            !result.contains("/*"),
            "block comments should be stripped: {result}"
        );
        assert!(result.contains("\"value\""));
    }

    #[test]
    fn strip_jsonc_comments_preserves_comments_in_strings() {
        let input = r#"{ "key": "// not a comment" }"#;
        let result = OpenCodeLauncher::strip_jsonc_comments(input);
        assert!(result.contains("// not a comment"));
    }

    #[test]
    fn strip_jsonc_comments_handles_multiline_block_comments() {
        let input = r#"{
            "key": "value" /*
                multiline
                comment
            */
        }"#;
        let result = OpenCodeLauncher::strip_jsonc_comments(input);
        assert!(!result.contains("multiline"));
        assert!(result.contains("\"value\""));
    }

    // -- env var resolution ------------------------------------------------------

    #[test]
    fn resolve_env_vars_resolves_string_placeholders() {
        unsafe {
            std::env::set_var("TEST_VAR_123", "resolved_value");
        }
        let input = serde_json::json!({ "url": "{env:TEST_VAR_123}" });
        let result = OpenCodeLauncher::resolve_env_vars(&input);
        assert_eq!(result["url"], "resolved_value");
        unsafe {
            std::env::remove_var("TEST_VAR_123");
        }
    }

    #[test]
    fn resolve_env_vars_uses_empty_string_for_unset_vars() {
        unsafe {
            std::env::remove_var("NONEXISTENT_VAR_XYZ");
        }
        let input = serde_json::json!({ "url": "{env:NONEXISTENT_VAR_XYZ}" });
        let result = OpenCodeLauncher::resolve_env_vars(&input);
        assert_eq!(result["url"], "");
    }

    #[test]
    fn resolve_env_vars_leaves_non_placeholder_strings_untouched() {
        let input = serde_json::json!({ "url": "https://example.com" });
        let result = OpenCodeLauncher::resolve_env_vars(&input);
        assert_eq!(result["url"], "https://example.com");
    }

    #[test]
    fn resolve_env_vars_recurses_into_objects() {
        unsafe {
            std::env::set_var("TEST_URL_456", "https://resolved.com/v1");
        }
        let input = serde_json::json!({
            "provider": {
                "options": {
                    "baseURL": "{env:TEST_URL_456}"
                }
            }
        });
        let result = OpenCodeLauncher::resolve_env_vars(&input);
        assert_eq!(
            result["provider"]["options"]["baseURL"],
            "https://resolved.com/v1"
        );
        unsafe {
            std::env::remove_var("TEST_URL_456");
        }
    }

    #[test]
    fn resolve_env_vars_recurses_into_arrays() {
        let input = serde_json::json!([1, "{env:HOME}", true]);
        let result = OpenCodeLauncher::resolve_env_vars(&input);
        assert_eq!(result[0], 1);
        assert_eq!(result[1], std::env::var("HOME").unwrap_or_default());
        assert_eq!(result[2], true);
    }

    // -- env providers discovery -------------------------------------------------

    #[test]
    fn discover_env_providers_returns_empty_when_no_keys_set() {
        // Save original values
        let saved = [
            ("OPENAI_API_KEY", std::env::var("OPENAI_API_KEY").ok()),
            ("ANTHROPIC_API_KEY", std::env::var("ANTHROPIC_API_KEY").ok()),
            ("GOOGLE_API_KEY", std::env::var("GOOGLE_API_KEY").ok()),
        ];
        // Clear the env vars
        for (key, _) in &saved {
            unsafe {
                std::env::remove_var(key);
            }
        }

        let providers = OpenCodeLauncher::discover_env_providers();
        assert!(
            !providers.contains_key("openai"),
            "openai should not be discovered"
        );
        assert!(
            !providers.contains_key("anthropic"),
            "anthropic should not be discovered"
        );
        assert!(
            !providers.contains_key("google"),
            "google should not be discovered"
        );

        // Restore original values
        for (key, orig) in &saved {
            if let Some(val) = orig {
                unsafe {
                    std::env::set_var(key, val);
                }
            }
        }
    }

    // -- user config discovery ---------------------------------------------------

    #[test]
    fn extract_providers_returns_none_for_missing_provider_key() {
        let config = serde_json::json!({ "model": "openai/gpt-4o" });
        assert!(OpenCodeLauncher::extract_providers(&config).is_none());
    }

    #[test]
    fn extract_providers_returns_none_for_non_object_provider() {
        let config = serde_json::json!({ "provider": "invalid" });
        assert!(OpenCodeLauncher::extract_providers(&config).is_none());
    }

    #[tokio::test]
    async fn merge_user_providers_rewrites_base_urls_to_provider_paths() {
        let server = crate::proxy::ProxyServer::start().unwrap();
        let mut l = launcher(serde_json::json!({}));
        l.model_proxy = Some(server.handle.clone());

        let user: serde_json::Map<String, serde_json::Value> = serde_json::json!({
            "openrouter": {
                "npm": "@ai-sdk/openai-compatible",
                "options": {
                    "baseURL": "https://openrouter.ai/api/v1",
                    "apiKey": "{env:OPENROUTER_API_KEY}"
                }
            },
            "local-vllm": {
                "options": { "baseURL": "http://localhost:8000/v1" }
            },
            "my-ollama": {
                "options": { "baseURL": "https://should-be.overridden" }
            }
        })
        .as_object()
        .unwrap()
        .clone();
        let env: serde_json::Map<String, serde_json::Value> = serde_json::json!({
            "anthropic": {
                "options": { "baseURL": "https://api.anthropic.com" }
            }
        })
        .as_object()
        .unwrap()
        .clone();
        let granite: serde_json::Map<String, serde_json::Value> = serde_json::json!({
            "my-ollama": { "options": { "baseURL": "granite-entry" } }
        })
        .as_object()
        .unwrap()
        .clone();

        let merged = l.merge_user_providers_into_config(&user, &env, &granite);

        let proxy = server
            .handle
            .local_base_url
            .trim_end_matches('/')
            .to_string();
        assert_eq!(
            merged["openrouter"]["options"]["baseURL"],
            format!("{proxy}/providers/openrouter")
        );
        assert_eq!(
            merged["openrouter"]["options"]["apiKey"],
            "{env:OPENROUTER_API_KEY}"
        );
        assert_eq!(
            merged["anthropic"]["options"]["baseURL"],
            format!("{proxy}/providers/anthropic")
        );
        assert_eq!(
            merged["local-vllm"]["options"]["baseURL"],
            "http://localhost:8000/v1"
        );
        assert_eq!(merged["my-ollama"]["options"]["baseURL"], "granite-entry");

        server.shutdown().await;
    }

    #[test]
    fn extract_providers_returns_some_for_valid_provider_object() {
        let config = serde_json::json!({
            "provider": {
                "openai": { "name": "openai", "options": {} }
            }
        });
        let providers = OpenCodeLauncher::extract_providers(&config);
        assert!(providers.is_some());
        let providers = providers.unwrap();
        assert!(providers.contains_key("openai"));
    }
}