merlion-agent 0.1.3

Merlion Agent CLI
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
use std::io::{IsTerminal, Write};
use std::sync::Arc;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use merlion_config::{Config, FallbackChain, ModelConfig, Wire};
use merlion_core::{
    Agent, AgentEvent, AgentOptions, Curator, LlmClient, Message, ToolApprover, ToolRegistry,
};
use merlion_llm::{
    AnthropicClient, BedrockClient, FallbackLlmClient, GeminiClient, OpenAiClient, VertexClient,
};
use merlion_mcp::{
    make_exposed_name, McpClient, McpProxyTool, McpRegistry, ServerEntry, StdioTransport,
    TransportSpec,
};
use merlion_memory::MemoryStore;
use merlion_session::SessionDB;
use merlion_skills::SkillSet;
use merlion_tools::skill_tools::SkillToolsConfig;
use tokio::sync::mpsc;

mod approver;
mod auth_cmd;
mod backup_cmd;
mod completion;
mod curator_cmd;
mod fallback_cmd;
mod gateway_service;
mod logs;
mod setup;
mod skills_cmd;
mod tools_cmd;
mod tui;

#[derive(Debug, Parser)]
#[command(
    name = "merlion",
    version,
    about = "Merlion Agent — Rust port of hermes-agent"
)]
struct Cli {
    /// One-shot mode: run a single prompt and print ONLY the final response
    /// text to stdout. No banner, no spinner, no tool previews. Tools and
    /// approval auto-bypass. Designed for shell pipelines:
    ///   `git diff | merlion -z "review this"`
    /// Reads stdin and appends to the prompt when stdin is not a TTY.
    #[arg(short = 'z', long = "oneshot", value_name = "PROMPT", global = true)]
    oneshot: Option<String>,

    /// Resume the most recently-active session (works with `chat`, `-z`, or
    /// no subcommand).
    #[arg(short = 'c', long = "continue", global = true)]
    continue_recent: bool,

    /// Resume a specific session by ID. Mutually exclusive with `--continue`.
    #[arg(long = "resume", value_name = "SESSION_ID", global = true)]
    resume_id: Option<String>,

    /// Per-invocation model override. Format: `provider:model` or just `model`
    /// (uses configured provider). Wins over `~/.merlion/config.yaml`.
    /// Example: `merlion -z "x" -m anthropic:claude-sonnet-4`.
    #[arg(short = 'm', long = "model", value_name = "MODEL", global = true)]
    model_override: Option<String>,

    /// Per-invocation provider override (e.g. `openrouter`, `anthropic`).
    /// Combine with `-m` to override both. Defaults pulled from
    /// `~/.merlion/config.yaml` apply when omitted.
    #[arg(long = "provider", value_name = "PROVIDER", global = true)]
    provider_override: Option<String>,

    /// Preload one or more skills into the system prompt for this invocation.
    /// Repeat the flag or comma-separate: `-s code-review,test-driven`.
    #[arg(
        short = 's',
        long = "skills",
        value_name = "SKILLS",
        global = true,
        value_delimiter = ','
    )]
    preload_skills: Vec<String>,

    /// Bypass every approval prompt. Equivalent to `MERLION_AUTO_APPROVE=1`.
    /// Use at your own risk — the agent can run any tool without asking.
    #[arg(long = "yolo", global = true)]
    yolo: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Start an interactive chat (default when no subcommand is given).
    Chat {
        /// Resume a specific session id instead of starting a new one.
        #[arg(long)]
        session: Option<String>,
        /// Force the ratatui-based TUI even when stdout is not a TTY.
        #[arg(long)]
        tui: bool,
        /// Force the plain line-based REPL even when stdout is a TTY.
        #[arg(long)]
        no_tui: bool,
    },
    /// Print or set the active model. `merlion model openai:gpt-4o-mini`
    Model {
        /// New `provider:model` to switch to. Omit to print the current setting.
        id: Option<String>,
    },
    /// Show or edit the merged config.
    Config {
        #[command(subcommand)]
        action: Option<ConfigAction>,
    },
    /// Diagnose configuration and credentials. Alias: `status`.
    #[command(alias = "status")]
    Doctor,
    /// Interactive first-run wizard. Walks you through picking a provider,
    /// model, API key, and optional system prompt; writes ~/.merlion/config.yaml
    /// and ~/.merlion/.env.
    Setup,
    /// Print version info (same as `--version`).
    Version,
    /// Emit a shell-completion script to stdout.
    /// Example: `merlion completion zsh >> ~/.zshrc`
    Completion {
        /// Target shell: bash, zsh, fish, powershell, or elvish.
        shell: clap_complete::Shell,
    },
    /// List or search past sessions.
    Sessions {
        #[command(subcommand)]
        action: Option<SessionsAction>,
    },
    /// Manage MCP (Model Context Protocol) servers.
    Mcp {
        #[command(subcommand)]
        action: McpAction,
    },
    /// Run the messaging gateway (Telegram + Discord + Slack).
    Gateway {
        #[command(subcommand)]
        action: GatewayAction,
    },
    /// Manage scheduled jobs.
    Cron {
        #[command(subcommand)]
        action: CronAction,
    },
    /// Check for a newer merlion release on GitHub. Pass --apply to actually
    /// download and swap the binary (Unix only).
    Update {
        /// Download the latest tarball and replace the running binary. The
        /// running process exits after a successful swap.
        #[arg(long)]
        apply: bool,
    },
    /// Tail merlion's on-disk log files in `~/.merlion/logs/`.
    Logs {
        /// Follow the file like `tail -F` (Unix only).
        #[arg(short, long)]
        follow: bool,
        /// Show errors.log (WARN+) instead of agent.log (INFO+).
        #[arg(long)]
        errors: bool,
        /// Only show entries newer than this duration. e.g. `1h`, `10m`.
        #[arg(long)]
        since: Option<String>,
        /// How many lines from the tail to show. Default 50.
        #[arg(short = 'n', long, default_value_t = 50)]
        lines: usize,
    },
    /// Manage user-installed skills under `~/.merlion/skills/`.
    Skills {
        #[command(subcommand)]
        action: skills_cmd::SkillsAction,
    },
    /// Inspect available tools.
    Tools {
        #[command(subcommand)]
        action: tools_cmd::ToolsAction,
    },
    /// Inspect / pause / nudge the memory curator.
    Curator {
        #[command(subcommand)]
        action: curator_cmd::CuratorAction,
    },
    /// Manage the fallback provider chain — tried in order when the
    /// primary returns 429/5xx.
    Fallback {
        #[command(subcommand)]
        action: fallback_cmd::FallbackAction,
    },
    /// Manage pooled API credentials in `~/.merlion/auth.yaml`.
    Auth {
        #[command(subcommand)]
        action: auth_cmd::AuthAction,
    },
    /// Archive `~/.merlion/` to a tar.gz for transfer or rollback.
    Backup(backup_cmd::BackupArgs),
    /// Restore a tar.gz previously produced by `merlion backup`.
    Import(backup_cmd::ImportArgs),
}

#[derive(Debug, Subcommand)]
enum GatewayAction {
    /// Run the gateway in the foreground. Reads TELEGRAM_BOT_TOKEN,
    /// DISCORD_BOT_TOKEN, SLACK_APP_TOKEN+SLACK_BOT_TOKEN, and
    /// MERLION_GATEWAY_ALLOW_* from the environment. Stays in the
    /// foreground until interrupted — this is what the installed service
    /// runs under the hood.
    Run,
    /// Install the gateway as a background service. Writes a launchd
    /// LaunchAgent (macOS) or systemd --user unit (Linux), then bootstraps
    /// it so it starts at login and respawns on failure.
    Install,
    /// Stop and remove the installed background service.
    Uninstall,
    /// Start the installed background service (no-op if already running).
    Start,
    /// Stop the installed background service.
    Stop,
    /// Restart the installed background service.
    Restart,
    /// Tail `~/.merlion/logs/gateway.log` (or `gateway.error.log` with
    /// `--errors`). Add `-f` to follow live output.
    Logs {
        /// Follow new log lines (like `tail -f`).
        #[arg(short, long)]
        follow: bool,
        /// Show the stderr log instead of the stdout log.
        #[arg(long)]
        errors: bool,
        /// How many lines to print before following / exiting.
        #[arg(short = 'n', long, default_value_t = 50)]
        lines: usize,
    },
    /// Print env-var configuration *and* the background service state.
    Status,
}

#[derive(Debug, Subcommand)]
enum CronAction {
    /// List configured jobs.
    List,
    /// Add a job: `merlion cron add daily-summary "0 0 9 * * *" "summarize my inbox"`.
    Add {
        name: String,
        schedule: String,
        prompt: String,
        #[arg(long, default_value = "cli")]
        destination: String,
    },
    /// Remove a job.
    Remove { name: String },
    /// Run a job once immediately (does not affect the schedule).
    Run { name: String },
    /// Run the scheduler in the foreground; fires jobs as they come due.
    Daemon,
}

#[derive(Debug, Subcommand)]
enum McpAction {
    /// List configured servers and their enabled state.
    List,
    /// Add a stdio server: `merlion mcp add fs -- npx -y @mcp/fs /tmp`.
    Add {
        /// Logical name (used to prefix the exposed tool names).
        name: String,
        /// Command + args, separated from the name by `--`.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, required = true)]
        command: Vec<String>,
    },
    /// Add an HTTP server: `merlion mcp add-http my-srv https://mcp.example.com/`.
    AddHttp {
        name: String,
        url: String,
        /// Env var to read the bearer token from. Optional.
        #[arg(long)]
        bearer_env: Option<String>,
    },
    /// Remove a configured server.
    Remove { name: String },
    /// Enable a previously-disabled server.
    Enable { name: String },
    /// Disable a server without removing it.
    Disable { name: String },
    /// Connect to a server, run the initialize handshake, list its tools.
    Test { name: String },
    /// Run the OAuth2 PKCE flow against an HTTP server and cache the token
    /// in `~/.merlion/mcp-tokens.yaml`.
    Oauth {
        name: String,
        /// Repeatable; defaults to none if omitted.
        #[arg(long)]
        scope: Vec<String>,
    },
}

#[derive(Debug, Subcommand)]
enum ConfigAction {
    /// Print the merged config as YAML.
    Show,
    /// Print the path to the user config file.
    Path,
}

#[derive(Debug, Subcommand)]
enum SessionsAction {
    /// List recent sessions.
    List {
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// FTS5 search across all message content.
    Search { query: String },
}

#[tokio::main]
async fn main() -> Result<()> {
    let _guard = logs::init_with_files()?;

    let cli = Cli::parse();
    let mut cfg = merlion_config::load().context("loading config")?;

    // --yolo flips the env var that ConsoleApprover reads at construction
    // time. Set it before anything else so subcommands see the bypass.
    if cli.yolo {
        std::env::set_var("MERLION_AUTO_APPROVE", "1");
    }

    apply_model_override(&mut cfg, cli.model_override.as_deref());
    apply_provider_override(&mut cfg, cli.provider_override.as_deref());

    // --resume and --continue are mutually exclusive at the CLI surface.
    if cli.resume_id.is_some() && cli.continue_recent {
        anyhow::bail!("--resume and --continue are mutually exclusive");
    }

    // -z/--oneshot short-circuits everything else: ignore the subcommand
    // (if any), run a single agent turn, print the assistant's final text
    // to stdout, exit.
    if let Some(prompt) = cli.oneshot.clone() {
        let resume = cli.resume_id.clone().or_else(|| {
            cli.continue_recent
                .then(|| most_recent_session_id().ok())
                .flatten()
        });
        return oneshot_cmd(cfg, prompt, resume, cli.preload_skills.clone()).await;
    }

    // --resume <ID> or --continue (most-recent) → optional session id fed
    // into chat(). --resume wins over --continue if both were somehow set
    // (mutual exclusion was already enforced above).
    let resume_session = if let Some(id) = cli.resume_id.clone() {
        Some(id)
    } else if cli.continue_recent {
        Some(most_recent_session_id()?)
    } else {
        None
    };

    match cli.command.unwrap_or(Command::Chat {
        session: resume_session.clone(),
        tui: false,
        no_tui: false,
    }) {
        Command::Chat {
            session,
            tui,
            no_tui,
        } => {
            let session = session.or(resume_session);
            chat(cfg, session, tui, no_tui).await
        }
        Command::Model { id } => model_cmd(cfg, id),
        Command::Config { action } => config_cmd(cfg, action),
        Command::Doctor => doctor(cfg),
        Command::Setup => setup::run().await,
        Command::Version => {
            println!("merlion-agent {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        Command::Sessions { action } => sessions_cmd(action),
        Command::Mcp { action } => mcp_cmd(action).await,
        Command::Gateway { action } => gateway_cmd(cfg, action).await,
        Command::Cron { action } => cron_cmd(cfg, action).await,
        Command::Update { apply } => update_cmd(apply).await,
        Command::Completion { shell } => {
            completion::emit::<Cli>(shell, "merlion", &mut std::io::stdout());
            Ok(())
        }
        Command::Logs {
            follow,
            errors,
            since,
            lines,
        } => {
            logs::run(logs::LogsArgs {
                follow,
                errors,
                since,
                lines,
            })
            .await
        }
        Command::Skills { action } => skills_cmd::run(action).await,
        Command::Tools { action } => tools_cmd::run(action).await,
        Command::Curator { action } => curator_cmd::run(action).await,
        Command::Fallback { action } => fallback_cmd::run(action).await,
        Command::Auth { action } => auth_cmd::run(action).await,
        Command::Backup(args) => backup_cmd::run_backup(args).await,
        Command::Import(args) => backup_cmd::run_import(args).await,
    }
}

/// Wrap a primary LLM client with a [`FallbackLlmClient`] when the user
/// has configured a non-empty fallback chain in `~/.merlion/fallback.yaml`.
/// Failures to build any individual fallback client are logged and skipped —
/// a broken fallback entry should not prevent chat/-z from starting.
fn wrap_with_fallback(primary: Arc<dyn LlmClient>, cfg: &Config) -> Arc<dyn LlmClient> {
    let chain_cfg = match FallbackChain::load() {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(error = %e, "failed to load fallback chain; using primary only");
            return primary;
        }
    };
    if chain_cfg.chain.is_empty() {
        return primary;
    }
    let mut clients: Vec<Arc<dyn LlmClient>> = Vec::new();
    let mut names: Vec<String> = vec![cfg.model.id.clone()];
    for entry in &chain_cfg.chain {
        let entry_cfg = Config {
            model: ModelConfig {
                id: entry.clone(),
                base_url: None,
                api_key_env: None,
                temperature: cfg.model.temperature,
                max_tokens: cfg.model.max_tokens,
            },
            system_prompt: cfg.system_prompt.clone(),
            max_iterations: cfg.max_iterations,
        };
        let provider = match entry_cfg.resolve_provider() {
            Ok(p) => p,
            Err(e) => {
                tracing::warn!(entry = %entry, error = %e, "skipping invalid fallback entry");
                continue;
            }
        };
        let api_key = std::env::var(&provider.api_key_env).ok();
        let built: Result<Arc<dyn LlmClient>> = (|| -> Result<Arc<dyn LlmClient>> {
            let c: Arc<dyn LlmClient> = match provider.wire {
                Wire::OpenAi => Arc::new(OpenAiClient::new(provider.base_url.clone(), api_key)?),
                Wire::Anthropic => {
                    Arc::new(AnthropicClient::new(provider.base_url.clone(), api_key)?)
                }
                Wire::Gemini => Arc::new(GeminiClient::new(provider.base_url.clone(), api_key)?),
                Wire::Bedrock => Arc::new(BedrockClient::from_env()?),
                Wire::Vertex => Arc::new(VertexClient::from_env()?),
            };
            Ok(c)
        })();
        match built {
            Ok(c) => {
                clients.push(c);
                names.push(entry.clone());
            }
            Err(e) => {
                tracing::warn!(entry = %entry, error = %e, "failed to build fallback client; skipping");
            }
        }
    }
    if clients.is_empty() {
        return primary;
    }
    Arc::new(FallbackLlmClient::new(primary, clients, names))
}

fn most_recent_session_id() -> Result<String> {
    let db = SessionDB::open_default()?;
    let rows = db.list_sessions(1)?;
    rows.into_iter()
        .next()
        .map(|r| r.id)
        .ok_or_else(|| anyhow::anyhow!("no sessions to continue — start one with `merlion`"))
}

/// Apply -m/--model override to `cfg.model.id`. Accepts either the full
/// `provider:model` form (replaces both) or a bare model name (keeps the
/// configured provider). Mutates in place.
fn apply_model_override(cfg: &mut Config, override_val: Option<&str>) {
    let Some(val) = override_val else { return };
    if val.contains(':') {
        cfg.model.id = val.to_string();
    } else {
        // Keep provider prefix from the current id; replace the model part.
        if let Some((provider, _)) = cfg.model.id.split_once(':') {
            cfg.model.id = format!("{provider}:{val}");
        } else {
            cfg.model.id = val.to_string();
        }
    }
}

/// Apply --provider override. Replaces only the provider prefix and keeps
/// the configured model name. `merlion -m claude-sonnet-4 --provider openrouter`
/// becomes id = `openrouter:claude-sonnet-4`.
fn apply_provider_override(cfg: &mut Config, override_val: Option<&str>) {
    let Some(provider) = override_val else { return };
    let model_part = cfg
        .model
        .id
        .split_once(':')
        .map(|(_, m)| m.to_string())
        .unwrap_or_else(|| cfg.model.id.clone());
    cfg.model.id = format!("{provider}:{model_part}");
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod cli_override_tests {
    use super::*;
    use merlion_config::{Config, ModelConfig};

    fn cfg_with(id: &str) -> Config {
        Config {
            model: ModelConfig {
                id: id.into(),
                base_url: None,
                api_key_env: None,
                temperature: None,
                max_tokens: None,
            },
            system_prompt: None,
            max_iterations: 32,
        }
    }

    #[test]
    fn model_override_full_form_replaces_both() {
        let mut c = cfg_with("openai:gpt-4o-mini");
        apply_model_override(&mut c, Some("anthropic:claude-sonnet-4"));
        assert_eq!(c.model.id, "anthropic:claude-sonnet-4");
    }

    #[test]
    fn model_override_bare_keeps_provider() {
        let mut c = cfg_with("openai:gpt-4o-mini");
        apply_model_override(&mut c, Some("gpt-4o"));
        assert_eq!(c.model.id, "openai:gpt-4o");
    }

    #[test]
    fn provider_override_replaces_prefix() {
        let mut c = cfg_with("openai:gpt-4o-mini");
        apply_provider_override(&mut c, Some("openrouter"));
        assert_eq!(c.model.id, "openrouter:gpt-4o-mini");
    }

    #[test]
    fn provider_override_no_op_when_none() {
        let mut c = cfg_with("openai:gpt-4o-mini");
        apply_provider_override(&mut c, None);
        assert_eq!(c.model.id, "openai:gpt-4o-mini");
    }
}

async fn update_cmd(apply: bool) -> Result<()> {
    let api = "https://api.github.com/repos/MerlionOS/merlion-agent/releases/latest";
    let client = reqwest::Client::builder()
        .user_agent(concat!("merlion/", env!("CARGO_PKG_VERSION")))
        .build()?;
    let resp = client.get(api).send().await?;
    if !resp.status().is_success() {
        anyhow::bail!(
            "github releases api {}: {}",
            resp.status(),
            resp.text().await.unwrap_or_default()
        );
    }
    let body: serde_json::Value = resp.json().await?;
    let latest = body
        .get("tag_name")
        .and_then(|v| v.as_str())
        .unwrap_or("(unknown)");
    let current_full = format!("v{}", env!("CARGO_PKG_VERSION"));
    println!("installed:  {current_full}");
    println!("latest tag: {latest}");
    if latest == current_full {
        println!("already up to date.");
        return Ok(());
    }

    if !apply {
        println!();
        println!("To upgrade:");
        println!("  merlion update --apply        # download + swap the binary (Unix)");
        println!(
            "  cargo binstall merlion-agent --version {}",
            latest.trim_start_matches('v')
        );
        println!("  brew upgrade merlion-agent    # if installed via Homebrew");
        println!(
            "  curl -fsSL https://raw.githubusercontent.com/MerlionOS/merlion-agent/main/scripts/install.sh | bash"
        );
        return Ok(());
    }

    // --apply path: download tarball, extract, swap.
    if cfg!(windows) {
        anyhow::bail!(
            "`merlion update --apply` is unix-only for now; on Windows please run the installer manually"
        );
    }
    let target = detect_target_triple().context("could not infer this binary's target triple")?;
    let assets = body
        .get("assets")
        .and_then(|a| a.as_array())
        .cloned()
        .unwrap_or_default();
    let asset_name = format!("merlion-{target}.tar.gz");
    let asset = assets
        .iter()
        .find(|a| a.get("name").and_then(|n| n.as_str()) == Some(&asset_name))
        .ok_or_else(|| {
            anyhow::anyhow!(
                "no release asset named `{asset_name}` on tag {latest}; available: {:?}",
                assets
                    .iter()
                    .filter_map(|a| a.get("name").and_then(|n| n.as_str()))
                    .collect::<Vec<_>>()
            )
        })?;
    let url = asset
        .get("browser_download_url")
        .and_then(|u| u.as_str())
        .ok_or_else(|| anyhow::anyhow!("asset missing browser_download_url"))?;

    println!("downloading {url}");
    let tarball = client
        .get(url)
        .send()
        .await?
        .error_for_status()?
        .bytes()
        .await?;

    let tmp = tempfile::tempdir().context("create temp dir")?;
    let tar_path = tmp.path().join(&asset_name);
    std::fs::write(&tar_path, &tarball).context("write tarball")?;
    println!("extracting…");
    let status = std::process::Command::new("tar")
        .arg("-xzf")
        .arg(&tar_path)
        .current_dir(tmp.path())
        .status()
        .context("tar -xzf failed (is `tar` installed?)")?;
    if !status.success() {
        anyhow::bail!("tar -xzf exited with {status}");
    }

    let extracted = tmp.path().join(format!("merlion-{target}")).join("merlion");
    if !extracted.exists() {
        anyhow::bail!(
            "extracted layout unexpected — expected {} to exist",
            extracted.display()
        );
    }

    let current_exe = std::env::current_exe().context("current_exe")?;
    println!(
        "replacing {}{}",
        current_exe.display(),
        extracted.display()
    );
    // rename across filesystems can fail; fall back to copy+remove.
    if std::fs::rename(&extracted, &current_exe).is_err() {
        std::fs::copy(&extracted, &current_exe).context("copy new binary into place")?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&current_exe)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&current_exe, perms)?;
    }
    println!("upgraded to {latest}. Restart any running merlion processes.");
    Ok(())
}

/// Best-effort detection of `cargo` target triple for this binary. Used by
/// `merlion update --apply` to pick the right release tarball.
fn detect_target_triple() -> Option<String> {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    match (os, arch) {
        ("linux", "x86_64") => Some("x86_64-unknown-linux-gnu".into()),
        ("linux", "aarch64") => Some("aarch64-unknown-linux-gnu".into()),
        ("macos", "x86_64") => Some("x86_64-apple-darwin".into()),
        ("macos", "aarch64") => Some("aarch64-apple-darwin".into()),
        _ => None,
    }
}

fn model_cmd(mut cfg: Config, id: Option<String>) -> Result<()> {
    match id {
        None => {
            println!("{}", cfg.model.id);
        }
        Some(new_id) => {
            cfg.model.id = new_id;
            let path = merlion_config::save(&cfg)?;
            println!("Set model = {} ({})", cfg.model.id, path.display());
        }
    }
    Ok(())
}

fn config_cmd(cfg: Config, action: Option<ConfigAction>) -> Result<()> {
    match action.unwrap_or(ConfigAction::Show) {
        ConfigAction::Show => {
            print!("{}", serde_yaml::to_string(&cfg)?);
        }
        ConfigAction::Path => {
            let home = merlion_config::merlion_home();
            println!("{}", home.join("config.yaml").display());
        }
    }
    Ok(())
}

fn doctor(cfg: Config) -> Result<()> {
    use std::process::Command;

    println!("merlion-agent {}", env!("CARGO_PKG_VERSION"));
    let home = merlion_config::merlion_home();
    println!("home:    {}", home.display());

    // Core config
    println!("\n— config —");
    println!("model:        {}", cfg.model.id);
    let provider = cfg.resolve_provider()?;
    println!("base_url:     {}", provider.base_url);
    println!("api key env:  {}", provider.api_key_env);
    let has_key = std::env::var(&provider.api_key_env).is_ok();
    println!(
        "api key:      {}",
        if has_key {
            "found".into()
        } else {
            format!("MISSING ({})", provider.api_key_env)
        }
    );

    // External tools merlion shells out to
    println!("\n— external tools —");
    for tool in ["rg", "grep", "git", "bash", "curl"] {
        let found = Command::new("which")
            .arg(tool)
            .output()
            .ok()
            .filter(|o| o.status.success());
        match found {
            Some(o) => {
                let path = String::from_utf8_lossy(&o.stdout).trim().to_string();
                println!("{:<6} {}", tool, path);
            }
            None => println!("{:<6} MISSING", tool),
        }
    }

    // Stores
    println!("\n— stores —");
    let session_db = home.join("sessions.db");
    println!(
        "sessions.db   {}",
        if session_db.exists() {
            "ok"
        } else {
            "(none yet)"
        }
    );
    let mem_dir = home.join("memory");
    println!(
        "memory/       {}",
        if mem_dir.exists() { "ok" } else { "(none yet)" }
    );
    let skills_dir = home.join("skills");
    let bundled_skills = std::env::current_dir().ok().map(|p| p.join("skills"));
    println!(
        "skills/       user={} bundled={}",
        if skills_dir.exists() { "ok" } else { "none" },
        bundled_skills
            .as_ref()
            .filter(|p| p.exists())
            .map(|_| "ok")
            .unwrap_or("none"),
    );

    // MCP
    println!("\n— mcp servers —");
    match merlion_mcp::McpRegistry::load_default() {
        Ok(reg) if reg.servers.is_empty() => {
            println!("(none configured — `merlion mcp add`)");
        }
        Ok(reg) => {
            for (name, entry) in &reg.servers {
                let status = if entry.enabled {
                    "enabled "
                } else {
                    "disabled"
                };
                println!("{status}  {name}");
            }
        }
        Err(e) => println!("(error loading mcp.yaml: {e})"),
    }

    // Gateway env
    println!("\n— gateway —");
    for (label, var) in [
        ("Telegram token", "TELEGRAM_BOT_TOKEN"),
        ("Discord token", "DISCORD_BOT_TOKEN"),
        ("Slack app token", "SLACK_APP_TOKEN"),
        ("Slack bot token", "SLACK_BOT_TOKEN"),
    ] {
        let set = std::env::var(var).is_ok();
        println!(
            "{:<18} {}",
            format!("{label}:"),
            if set { "set" } else { "MISSING" }
        );
    }
    match gateway_service::service_status() {
        Ok(gateway_service::ServiceState::NotInstalled) => {
            println!("service:           not installed");
        }
        Ok(gateway_service::ServiceState::Stopped { .. }) => {
            println!("service:           installed, stopped");
        }
        Ok(gateway_service::ServiceState::Running { pid, .. }) => match pid {
            Some(p) => println!("service:           running (pid {p})"),
            None => println!("service:           running"),
        },
        Ok(gateway_service::ServiceState::Unknown { detail, .. }) => {
            println!("service:           unknown ({detail})");
        }
        Err(_) => {}
    }

    // Cron
    println!("\n— cron —");
    match merlion_cron::CronRegistry::load_default() {
        Ok(reg) if reg.jobs.is_empty() => println!("(no jobs scheduled)"),
        Ok(reg) => {
            for j in &reg.jobs {
                let status = if j.enabled { "enabled " } else { "disabled" };
                println!("{status}  {}  ({})", j.name, j.schedule);
            }
        }
        Err(e) => println!("(error loading cron.yaml: {e})"),
    }

    Ok(())
}

fn sessions_cmd(action: Option<SessionsAction>) -> Result<()> {
    let db = SessionDB::open_default()?;
    match action.unwrap_or(SessionsAction::List { limit: 20 }) {
        SessionsAction::List { limit } => {
            for row in db.list_sessions(limit)? {
                println!(
                    "{}  msgs={:<4}  {}  {}",
                    row.id,
                    row.message_count,
                    row.updated_at.format("%Y-%m-%d %H:%M"),
                    row.title.unwrap_or_else(|| "(untitled)".into())
                );
            }
        }
        SessionsAction::Search { query } => {
            for (sid, snip) in db.search(&query, 20)? {
                println!("{sid}\t{snip}");
            }
        }
    }
    Ok(())
}

async fn mcp_cmd(action: McpAction) -> Result<()> {
    let path = McpRegistry::default_path();
    let mut reg =
        McpRegistry::load(&path).map_err(|e| anyhow::anyhow!("loading {}: {e}", path.display()))?;
    match action {
        McpAction::List => {
            if reg.servers.is_empty() {
                println!("(no MCP servers configured — see `merlion mcp add --help`)");
                return Ok(());
            }
            for (name, entry) in &reg.servers {
                let status = if entry.enabled {
                    "enabled "
                } else {
                    "disabled"
                };
                match &entry.transport {
                    TransportSpec::Stdio { command, args, .. } => {
                        let argline = args.to_vec().join(" ");
                        println!("{status}  {name}\t stdio: {command} {argline}");
                    }
                    TransportSpec::Http {
                        url,
                        bearer_env,
                        oauth_client_id: _,
                    } => {
                        let auth = bearer_env.as_deref().unwrap_or("(none)");
                        println!("{status}  {name}\t http:  {url} (auth env: {auth})");
                    }
                }
            }
        }
        McpAction::Add { name, command } => {
            if command.is_empty() {
                anyhow::bail!(
                    "missing command — usage: `merlion mcp add <name> -- <cmd> <args...>`"
                );
            }
            let program = command[0].clone();
            let args: Vec<String> = command.into_iter().skip(1).collect();
            reg.add(&name, ServerEntry::stdio(program, args));
            reg.save(&path)
                .map_err(|e| anyhow::anyhow!("writing {}: {e}", path.display()))?;
            println!("added MCP server `{name}` to {}", path.display());
        }
        McpAction::AddHttp {
            name,
            url,
            bearer_env,
        } => {
            let mut entry = ServerEntry::http(url.clone());
            if let TransportSpec::Http { bearer_env: be, .. } = &mut entry.transport {
                *be = bearer_env;
            }
            reg.add(&name, entry);
            reg.save(&path)
                .map_err(|e| anyhow::anyhow!("writing {}: {e}", path.display()))?;
            println!(
                "added HTTP MCP server `{name}` ({url}) to {}",
                path.display()
            );
        }
        McpAction::Remove { name } => match reg.remove(&name) {
            Some(_) => {
                reg.save(&path)
                    .map_err(|e| anyhow::anyhow!("writing {}: {e}", path.display()))?;
                println!("removed `{name}`");
            }
            None => println!("(no server named `{name}`)"),
        },
        McpAction::Enable { name } => {
            toggle_server(&mut reg, &name, true)?;
            reg.save(&path)
                .map_err(|e| anyhow::anyhow!("writing {}: {e}", path.display()))?;
            println!("enabled `{name}`");
        }
        McpAction::Disable { name } => {
            toggle_server(&mut reg, &name, false)?;
            reg.save(&path)
                .map_err(|e| anyhow::anyhow!("writing {}: {e}", path.display()))?;
            println!("disabled `{name}`");
        }
        McpAction::Test { name } => {
            let entry = reg.servers.get(&name).ok_or_else(|| {
                anyhow::anyhow!("no server named `{name}` (try `merlion mcp list`)")
            })?;
            let client = connect_server(&name, entry).await?;
            let info = client.initialize().await.context("initialize handshake")?;
            let server_name = info
                .server_info
                .as_ref()
                .map(|s| s.name.as_str())
                .unwrap_or("(unknown)");
            println!(
                "ok — server `{server_name}` (protocol {})",
                info.protocol_version
            );
            let tools = client.list_tools().await.context("list_tools")?;
            if tools.is_empty() {
                println!("(server exposes no tools)");
            } else {
                println!("{} tool(s):", tools.len());
                for t in tools {
                    let desc = t.description.as_deref().unwrap_or("");
                    println!("  - {}{desc}", t.name);
                }
            }
            let _ = client.close().await;
        }
        McpAction::Oauth { name, scope } => {
            use merlion_mcp::{OauthFlow, TokenStore};
            let entry = reg.servers.get(&name).ok_or_else(|| {
                anyhow::anyhow!("no server named `{name}` (try `merlion mcp list`)")
            })?;
            let (url, client_id) = match &entry.transport {
                TransportSpec::Http {
                    url,
                    oauth_client_id,
                    ..
                } => (url.clone(), oauth_client_id.clone()),
                TransportSpec::Stdio { .. } => {
                    anyhow::bail!(
                        "server `{name}` is stdio — OAuth applies to HTTP transports only"
                    );
                }
            };
            let flow = OauthFlow {
                server_url: url,
                static_client_id: client_id,
                scopes: scope,
            };
            let tokens = flow
                .authorize()
                .await
                .map_err(|e| anyhow::anyhow!("oauth flow: {e}"))?;
            let store_path = TokenStore::default_path();
            let mut store = TokenStore::load(&store_path)
                .map_err(|e| anyhow::anyhow!("load token store: {e}"))?;
            let expires = tokens.expires_at;
            store.set(name.clone(), tokens);
            store
                .save(&store_path)
                .map_err(|e| anyhow::anyhow!("save token store: {e}"))?;
            println!(
                "saved token for `{name}` to {} (expires_at: {:?})",
                store_path.display(),
                expires
            );
        }
    }
    Ok(())
}

fn toggle_server(reg: &mut McpRegistry, name: &str, enabled: bool) -> Result<()> {
    let entry = reg
        .servers
        .get_mut(name)
        .ok_or_else(|| anyhow::anyhow!("no server named `{name}` (try `merlion mcp list`)"))?;
    entry.enabled = enabled;
    Ok(())
}

/// Connect to one configured server, list its tools, and register a
/// `McpProxyTool` for each into the given registry. Returns the live
/// [`McpClient`] so the caller can keep it alive for the duration of the
/// session (dropping it would kill the child process).
async fn autoload_server(
    server_name: &str,
    entry: &ServerEntry,
    tools: &mut ToolRegistry,
) -> Result<Arc<McpClient>> {
    let client = Arc::new(connect_server(server_name, entry).await?);
    client
        .initialize()
        .await
        .map_err(|e| anyhow::anyhow!("initialize: {e}"))?;
    let remote_tools = client
        .list_tools()
        .await
        .map_err(|e| anyhow::anyhow!("list_tools: {e}"))?;
    for t in remote_tools {
        let exposed = make_exposed_name(server_name, &t.name);
        let proxy = McpProxyTool::new(client.clone(), exposed, t);
        tools.register_arc(Arc::new(proxy));
    }
    Ok(client)
}

async fn connect_server(server_name: &str, entry: &ServerEntry) -> Result<McpClient> {
    use merlion_mcp::{HttpTransport, TokenStore};
    let transport: Box<dyn merlion_mcp::Transport> = match &entry.transport {
        TransportSpec::Stdio { command, args, env } => {
            let env_vec: Vec<(String, String)> =
                env.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
            let t = StdioTransport::spawn(command, args, &env_vec)
                .await
                .map_err(|e| anyhow::anyhow!("spawn `{command}`: {e}"))?;
            Box::new(t)
        }
        TransportSpec::Http {
            url,
            bearer_env,
            oauth_client_id: _,
        } => {
            let mut t = HttpTransport::new(url.clone())
                .map_err(|e| anyhow::anyhow!("http transport `{url}`: {e}"))?;
            // Prefer a cached OAuth token if one exists for this server.
            let store = TokenStore::load(&TokenStore::default_path()).ok();
            if let Some(tok) = store.as_ref().and_then(|s| s.get(server_name)) {
                t = t.with_bearer(tok.access_token.clone());
            } else if let Some(env_var) = bearer_env.as_deref() {
                match std::env::var(env_var) {
                    Ok(tok) => t = t.with_bearer(tok),
                    Err(_) => {
                        eprintln!(
                            "warning: bearer env `{env_var}` not set; mcp `{url}` will go unauth"
                        );
                    }
                }
            }
            Box::new(t)
        }
    };
    Ok(McpClient::new(transport))
}

async fn gateway_cmd(cfg: Config, action: GatewayAction) -> Result<()> {
    match action {
        GatewayAction::Status => {
            let tg_tok = std::env::var("TELEGRAM_BOT_TOKEN").is_ok();
            let dc_tok = std::env::var("DISCORD_BOT_TOKEN").is_ok();
            let sk_app = std::env::var("SLACK_APP_TOKEN").is_ok();
            let sk_bot = std::env::var("SLACK_BOT_TOKEN").is_ok();
            let tg_allow = std::env::var("MERLION_GATEWAY_ALLOW_TELEGRAM").is_ok();
            let dc_allow = std::env::var("MERLION_GATEWAY_ALLOW_DISCORD").is_ok();
            let sk_allow = std::env::var("MERLION_GATEWAY_ALLOW_SLACK").is_ok();
            let allow_all = std::env::var("MERLION_GATEWAY_ALLOW_ALL").is_ok();
            println!("Telegram:");
            println!("  TELEGRAM_BOT_TOKEN               {}", yes_no(tg_tok));
            println!(
                "  MERLION_GATEWAY_ALLOW_TELEGRAM   {}",
                yes_no(tg_allow || allow_all)
            );
            println!("Discord:");
            println!("  DISCORD_BOT_TOKEN                {}", yes_no(dc_tok));
            println!(
                "  MERLION_GATEWAY_ALLOW_DISCORD    {}",
                yes_no(dc_allow || allow_all)
            );
            println!("Slack:");
            println!("  SLACK_APP_TOKEN                  {}", yes_no(sk_app));
            println!("  SLACK_BOT_TOKEN                  {}", yes_no(sk_bot));
            println!(
                "  MERLION_GATEWAY_ALLOW_SLACK      {}",
                yes_no(sk_allow || allow_all)
            );
            println!();
            println!("Set `MERLION_GATEWAY_ALLOW_ALL=1` to admit any user (development only).");
            print_service_status();
            Ok(())
        }
        GatewayAction::Run => start_gateways(cfg).await,
        GatewayAction::Install => gateway_service::install(),
        GatewayAction::Uninstall => gateway_service::uninstall(),
        GatewayAction::Start => gateway_service::start(),
        GatewayAction::Stop => gateway_service::stop(),
        GatewayAction::Restart => gateway_service::restart(),
        GatewayAction::Logs {
            follow,
            errors,
            lines,
        } => gateway_logs(follow, errors, lines).await,
    }
}

fn print_service_status() {
    println!();
    println!("— service —");
    match gateway_service::service_status() {
        Ok(gateway_service::ServiceState::NotInstalled) => {
            println!(
                "not installed. Run `merlion gateway install` to set up a background service,"
            );
            println!("or `merlion gateway run` to stay in the foreground.");
        }
        Ok(gateway_service::ServiceState::Stopped { unit_path }) => {
            println!("installed at {}", unit_path.display());
            println!("state: stopped. Start with `merlion gateway start`.");
        }
        Ok(gateway_service::ServiceState::Running {
            unit_path,
            pid,
            last_exit,
        }) => {
            println!("installed at {}", unit_path.display());
            print!("state: running");
            if let Some(p) = pid {
                print!(" (pid {p})");
            }
            if let Some(c) = last_exit {
                print!(", last exit {c}");
            }
            println!();
        }
        Ok(gateway_service::ServiceState::Unknown { unit_path, detail }) => {
            println!("installed at {}", unit_path.display());
            println!("state: unknown — {detail}");
        }
        Err(e) => {
            println!("(could not inspect service state: {e})");
        }
    }
    let home = merlion_config::merlion_home();
    println!(
        "logs:  {} and {}",
        home.join("logs/gateway.log").display(),
        home.join("logs/gateway.error.log").display(),
    );
}

async fn gateway_logs(follow: bool, errors: bool, lines: usize) -> Result<()> {
    let home = merlion_config::merlion_home();
    let path = if errors {
        home.join("logs/gateway.error.log")
    } else {
        home.join("logs/gateway.log")
    };
    if !path.exists() {
        println!("(no log file at {} yet)", path.display());
        return Ok(());
    }
    // Shell out to `tail` — portable enough on macOS + Linux and avoids
    // reimplementing follow-mode in Rust just for one command.
    let mut cmd = tokio::process::Command::new("tail");
    cmd.arg("-n").arg(lines.to_string());
    if follow {
        cmd.arg("-f");
    }
    cmd.arg(&path);
    let status = cmd
        .status()
        .await
        .with_context(|| format!("spawning tail on {}", path.display()))?;
    if !status.success() && !follow {
        return Err(anyhow::anyhow!("tail exited with {status}"));
    }
    Ok(())
}

fn yes_no(b: bool) -> &'static str {
    if b {
        "set"
    } else {
        "MISSING"
    }
}

/// Start every gateway whose env-var config is present. Each gateway gets a
/// dedicated [`Dispatcher`] instance — they share the underlying [`Agent`]
/// and `SessionDB` (sessions are keyed on `(platform, user_id)` so they
/// can't collide), but the message-routing channels are per-platform.
async fn start_gateways(cfg: Config) -> Result<()> {
    use merlion_gateway::{Allowlist, DiscordGateway, Gateway, SlackGateway, TelegramGateway};
    use std::sync::Arc;
    use tokio::sync::Mutex;

    let provider = cfg.resolve_provider()?;
    let api_key = std::env::var(&provider.api_key_env).ok();
    let llm: Arc<dyn LlmClient> = match provider.wire {
        Wire::OpenAi => Arc::new(OpenAiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Anthropic => Arc::new(AnthropicClient::new(provider.base_url.clone(), api_key)?),
        Wire::Gemini => Arc::new(GeminiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Bedrock => Arc::new(BedrockClient::from_env()?),
        Wire::Vertex => Arc::new(VertexClient::from_env()?),
    };
    let llm = wrap_with_fallback(llm, &cfg);

    let mut tools = ToolRegistry::new();
    merlion_tools::register_defaults(&mut tools);

    let options = AgentOptions {
        model: provider.model.clone(),
        temperature: cfg.model.temperature,
        max_tokens: cfg.model.max_tokens,
        max_iterations: cfg.max_iterations,
        ..AgentOptions::default()
    };
    let approver: Arc<dyn ToolApprover> = Arc::new(merlion_core::AllowAllApprover);
    let agent = Arc::new(Agent::new(llm, tools, options).with_approver(approver));

    let db = Arc::new(Mutex::new(SessionDB::open_default()?));
    let allowlist = Allowlist::from_env();
    let system_prompt = cfg.system_prompt.clone().unwrap_or_else(|| {
        "You are Merlion, a coding agent reachable over messaging platforms. \
         Reply succinctly; messaging UIs don't render tool output. \
         Use the `memory` tool to remember durable facts."
            .into()
    });

    let mut tasks: Vec<tokio::task::JoinHandle<()>> = Vec::new();
    let mut started: Vec<&'static str> = Vec::new();

    if std::env::var("TELEGRAM_BOT_TOKEN").is_ok() {
        let (tx, rx, dispatcher_task) = spawn_dispatcher(&agent, &db, &system_prompt, &allowlist);
        tasks.push(dispatcher_task);
        let gw = Arc::new(TelegramGateway::from_env()?);
        let name = gw.name();
        started.push(name);
        tasks.push(tokio::spawn(async move {
            if let Err(e) = gw.run(tx, rx).await {
                eprintln!("telegram gateway exited: {e}");
            }
        }));
    }
    if std::env::var("DISCORD_BOT_TOKEN").is_ok() {
        let (tx, rx, dispatcher_task) = spawn_dispatcher(&agent, &db, &system_prompt, &allowlist);
        tasks.push(dispatcher_task);
        let gw = Arc::new(DiscordGateway::from_env()?);
        let name = gw.name();
        started.push(name);
        tasks.push(tokio::spawn(async move {
            if let Err(e) = gw.run(tx, rx).await {
                eprintln!("discord gateway exited: {e}");
            }
        }));
    }
    if std::env::var("SLACK_APP_TOKEN").is_ok() && std::env::var("SLACK_BOT_TOKEN").is_ok() {
        let (tx, rx, dispatcher_task) = spawn_dispatcher(&agent, &db, &system_prompt, &allowlist);
        tasks.push(dispatcher_task);
        let gw = Arc::new(SlackGateway::from_env()?);
        let name = gw.name();
        started.push(name);
        tasks.push(tokio::spawn(async move {
            if let Err(e) = gw.run(tx, rx).await {
                eprintln!("slack gateway exited: {e}");
            }
        }));
    }

    if started.is_empty() {
        anyhow::bail!(
            "no gateway env vars detected. Set TELEGRAM_BOT_TOKEN, DISCORD_BOT_TOKEN, or \
             SLACK_APP_TOKEN+SLACK_BOT_TOKEN. See `merlion gateway status`."
        );
    }
    println!("gateway started: {}", started.join(", "));

    // Wait for any task to exit; the rest will get cleaned up on drop.
    if !tasks.is_empty() {
        let _ = futures::future::select_all(tasks).await;
    }
    Ok(())
}

fn spawn_dispatcher(
    agent: &std::sync::Arc<Agent>,
    db: &std::sync::Arc<tokio::sync::Mutex<SessionDB>>,
    system_prompt: &str,
    allowlist: &merlion_gateway::Allowlist,
) -> (
    tokio::sync::mpsc::Sender<merlion_gateway::IncomingMessage>,
    tokio::sync::mpsc::Receiver<merlion_gateway::OutgoingMessage>,
    tokio::task::JoinHandle<()>,
) {
    use std::sync::Arc;
    use tokio::sync::mpsc;
    let (incoming_tx, incoming_rx) = mpsc::channel(64);
    let (outgoing_tx, outgoing_rx) = mpsc::channel(64);
    let dispatcher = Arc::new(merlion_gateway::Dispatcher::new(
        agent.clone(),
        db.clone(),
        system_prompt.to_string(),
        allowlist.clone(),
    ));
    let task = tokio::spawn(async move {
        if let Err(e) = dispatcher.run(incoming_rx, outgoing_tx).await {
            eprintln!("dispatcher exited: {e}");
        }
    });
    (incoming_tx, outgoing_rx, task)
}

async fn cron_cmd(cfg: Config, action: CronAction) -> Result<()> {
    use merlion_cron::{CronRegistry, Job};
    let path = CronRegistry::default_path();
    let mut reg = CronRegistry::load(&path).map_err(|e| anyhow::anyhow!("loading cron: {e}"))?;
    match action {
        CronAction::List => {
            if reg.jobs.is_empty() {
                println!("(no jobs configured)");
                return Ok(());
            }
            for j in &reg.jobs {
                let status = if j.enabled { "enabled " } else { "disabled" };
                println!(
                    "{status}  {}\t{}\t{}\n  prompt: {}",
                    j.name, j.schedule, j.destination, j.prompt
                );
            }
            Ok(())
        }
        CronAction::Add {
            name,
            schedule,
            prompt,
            destination,
        } => {
            let job = Job {
                name: name.clone(),
                schedule,
                prompt,
                enabled: true,
                destination,
            };
            reg.add(job).map_err(|e| anyhow::anyhow!("add: {e}"))?;
            reg.save(&path).map_err(|e| anyhow::anyhow!("save: {e}"))?;
            println!("added cron job `{name}`");
            Ok(())
        }
        CronAction::Remove { name } => {
            if reg.remove(&name).is_some() {
                reg.save(&path).map_err(|e| anyhow::anyhow!("save: {e}"))?;
                println!("removed `{name}`");
            } else {
                println!("(no job named `{name}`)");
            }
            Ok(())
        }
        CronAction::Run { name } => {
            use merlion_cron::scheduler::JobRunner;
            let job = reg
                .get(&name)
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("no job named `{name}`"))?;
            let runner = build_cli_runner(cfg).await?;
            runner.run_job(&job).await;
            Ok(())
        }
        CronAction::Daemon => {
            let runner = build_cli_runner(cfg).await?;
            let scheduler = merlion_cron::Scheduler::new(reg, std::sync::Arc::new(runner));
            scheduler
                .run()
                .await
                .map_err(|e| anyhow::anyhow!("scheduler: {e}"))?;
            Ok(())
        }
    }
}

/// Build a cron JobRunner that constructs an Agent from `cfg`, runs the
/// prompt, and prints the response to stdout. (Destination-aware delivery
/// is a Phase 5.6 follow-up.)
async fn build_cli_runner(cfg: Config) -> Result<CliJobRunner> {
    let provider = cfg.resolve_provider()?;
    let api_key = std::env::var(&provider.api_key_env).ok();
    let llm: Arc<dyn LlmClient> = match provider.wire {
        Wire::OpenAi => Arc::new(OpenAiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Anthropic => Arc::new(AnthropicClient::new(provider.base_url.clone(), api_key)?),
        Wire::Gemini => Arc::new(GeminiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Bedrock => Arc::new(BedrockClient::from_env()?),
        Wire::Vertex => Arc::new(VertexClient::from_env()?),
    };
    let llm = wrap_with_fallback(llm, &cfg);
    let mut tools = ToolRegistry::new();
    merlion_tools::register_defaults(&mut tools);
    let options = AgentOptions {
        model: provider.model.clone(),
        max_iterations: cfg.max_iterations,
        ..AgentOptions::default()
    };
    let approver: Arc<dyn ToolApprover> = Arc::new(merlion_core::AllowAllApprover);
    let agent = Agent::new(llm, tools, options).with_approver(approver);
    let system_prompt = cfg
        .system_prompt
        .clone()
        .unwrap_or_else(|| "You are Merlion, running a scheduled task non-interactively.".into());
    Ok(CliJobRunner {
        agent: Arc::new(agent),
        system_prompt,
    })
}

struct CliJobRunner {
    agent: Arc<Agent>,
    system_prompt: String,
}

#[async_trait::async_trait]
impl merlion_cron::scheduler::JobRunner for CliJobRunner {
    async fn run_job(&self, job: &merlion_cron::Job) {
        let mut messages = vec![
            Message::system(&self.system_prompt),
            Message::user(&job.prompt),
        ];
        let (tx, mut rx) = tokio::sync::mpsc::channel::<AgentEvent>(64);
        let agent = self.agent.clone();
        let task = tokio::spawn(async move {
            let _ = agent.run(&mut messages, tx).await;
            messages
        });
        let mut reply = String::new();
        while let Some(ev) = rx.recv().await {
            if let AgentEvent::AssistantMessage(m) = ev {
                if let Some(c) = m.content {
                    reply.push_str(&c);
                }
            }
        }
        let _ = task.await;

        if reply.trim().is_empty() {
            reply = "(merlion produced no text reply)".into();
        }
        let when = chrono::Utc::now().to_rfc3339();

        match deliver_cron_result(&job.destination, &job.name, &reply).await {
            Ok(true) => {
                tracing::info!(job = %job.name, dest = %job.destination, "cron result delivered");
            }
            Ok(false) | Err(_) => {
                // Fall back to stdout if delivery failed or destination is "cli".
                println!("[cron {}] @ {when}{reply}", job.name);
            }
        }
    }
}

/// Push the cron result to its configured destination. Returns Ok(true) if
/// a non-CLI destination accepted the message, Ok(false) for the "cli"
/// destination (caller prints to stdout), or Err on transport failure.
///
/// Supported destinations:
/// - `cli` — print to stdout (the default).
/// - `telegram:<chat_id>` — POST sendMessage with TELEGRAM_BOT_TOKEN.
/// - `discord:<channel_id>` — POST messages with DISCORD_BOT_TOKEN.
async fn deliver_cron_result(destination: &str, job_name: &str, reply: &str) -> Result<bool> {
    let prefix = format!("[cron {job_name}]\n");
    let body = format!("{prefix}{reply}");
    if destination == "cli" {
        return Ok(false);
    }
    if let Some(chat_id) = destination.strip_prefix("telegram:") {
        let token = std::env::var("TELEGRAM_BOT_TOKEN")
            .context("TELEGRAM_BOT_TOKEN not set; cannot deliver to telegram")?;
        let url = format!("https://api.telegram.org/bot{token}/sendMessage");
        let resp = reqwest::Client::new()
            .post(&url)
            .json(&serde_json::json!({"chat_id": chat_id, "text": body}))
            .send()
            .await?;
        if !resp.status().is_success() {
            anyhow::bail!(
                "telegram sendMessage {}: {}",
                resp.status(),
                resp.text().await.unwrap_or_default()
            );
        }
        Ok(true)
    } else if let Some(channel_id) = destination.strip_prefix("discord:") {
        let token = std::env::var("DISCORD_BOT_TOKEN")
            .context("DISCORD_BOT_TOKEN not set; cannot deliver to discord")?;
        let url = format!("https://discord.com/api/v10/channels/{channel_id}/messages");
        let resp = reqwest::Client::new()
            .post(&url)
            .header("Authorization", format!("Bot {token}"))
            .json(&serde_json::json!({"content": body}))
            .send()
            .await?;
        if !resp.status().is_success() {
            anyhow::bail!(
                "discord postMessage {}: {}",
                resp.status(),
                resp.text().await.unwrap_or_default()
            );
        }
        Ok(true)
    } else {
        anyhow::bail!(
            "unknown cron destination `{destination}` — use `cli`, `telegram:<chat_id>`, or `discord:<channel_id>`"
        )
    }
}

/// Script-friendly one-shot mode: `merlion -z "prompt"`. Reads stdin (if
/// not a TTY) and appends to the prompt — enables shell pipelines like
/// `git diff | merlion -z "review this"`. Prints ONLY the final assistant
/// text to stdout (no banner, no spinner, no tool previews). Exits 0 on
/// success, non-zero if the agent loop errored.
async fn oneshot_cmd(
    cfg: Config,
    prompt: String,
    resume_id: Option<String>,
    preload_skills: Vec<String>,
) -> Result<()> {
    use std::io::Read as _;

    // Read piped stdin if any.
    let mut full_prompt = prompt;
    if !std::io::stdin().is_terminal() {
        let mut stdin = String::new();
        std::io::stdin().read_to_string(&mut stdin)?;
        if !stdin.trim().is_empty() {
            full_prompt.push_str("\n\n---\n");
            full_prompt.push_str(&stdin);
        }
    }

    let provider = cfg.resolve_provider()?;
    let api_key = std::env::var(&provider.api_key_env).ok();
    let llm: Arc<dyn LlmClient> = match provider.wire {
        Wire::OpenAi => Arc::new(OpenAiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Anthropic => Arc::new(AnthropicClient::new(provider.base_url.clone(), api_key)?),
        Wire::Gemini => Arc::new(GeminiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Bedrock => Arc::new(BedrockClient::from_env()?),
        Wire::Vertex => Arc::new(VertexClient::from_env()?),
    };
    let llm = wrap_with_fallback(llm, &cfg);

    let mut tools = ToolRegistry::new();
    merlion_tools::register_defaults(&mut tools);
    let memory_store = Arc::new(MemoryStore::open(
        merlion_config::merlion_home().join("memory"),
    )?);
    merlion_tools::register_memory(&mut tools, memory_store.clone());

    let options = AgentOptions {
        model: provider.model.clone(),
        temperature: cfg.model.temperature,
        max_tokens: cfg.model.max_tokens,
        max_iterations: cfg.max_iterations,
        ..AgentOptions::default()
    };
    // -z mode is for scripts; bypass approval prompts.
    let approver: Arc<dyn ToolApprover> = Arc::new(merlion_core::AllowAllApprover);
    let agent = Agent::new(llm, tools, options).with_approver(approver);

    // Load or initialize the conversation.
    let db = SessionDB::open_default()?;
    let session_id = if let Some(id) = resume_id {
        id
    } else {
        let id = uuid::Uuid::new_v4().to_string();
        db.create_session(&id, None)?;
        id
    };
    let mut messages = db.load_messages(&session_id)?;
    if messages.is_empty() {
        let sys = Message::system(default_oneshot_system_prompt(&cfg));
        db.append_message(&session_id, &sys)?;
        messages.push(sys);
    }

    // Preload requested skills as additional system messages before the
    // user's prompt. Each skill's body becomes its own system turn.
    if !preload_skills.is_empty() {
        let skill_set = SkillSet::load_default().unwrap_or_default();
        for name in &preload_skills {
            match skill_set.get(name) {
                Some(skill) => {
                    let m = Message::system(format!(
                        "[preloaded skill: {}]\n{}",
                        skill.name, skill.body
                    ));
                    db.append_message(&session_id, &m)?;
                    messages.push(m);
                }
                None => eprintln!("warning: skill `{name}` not found; skipping"),
            }
        }
    }

    let user_msg = Message::user(full_prompt);
    db.append_message(&session_id, &user_msg)?;
    messages.push(user_msg);

    // Run the agent. Drain events, concatenate assistant text.
    let (tx, mut rx) = mpsc::channel::<AgentEvent>(64);
    let mut snapshot = messages.clone();
    let run_fut = async {
        let res = agent.run(&mut snapshot, tx).await;
        (res, snapshot)
    };
    let render_fut = async {
        let mut buf = String::new();
        while let Some(ev) = rx.recv().await {
            if let AgentEvent::AssistantMessage(m) = ev {
                if let Some(c) = m.content {
                    if !c.is_empty() {
                        buf.push_str(&c);
                    }
                }
            }
        }
        buf
    };
    let ((res, new_messages), reply) = tokio::join!(run_fut, render_fut);

    for m in new_messages.iter().skip(messages.len()) {
        db.append_message(&session_id, m)?;
    }
    if let Err(e) = res {
        eprintln!("error: {e}");
        std::process::exit(1);
    }
    print!("{}", reply);
    if !reply.ends_with('\n') {
        println!();
    }
    Ok(())
}

fn default_oneshot_system_prompt(cfg: &Config) -> String {
    cfg.system_prompt.clone().unwrap_or_else(|| {
        "You are Merlion in script mode. Be concise. Output only the answer — \
         no preambles, no closing pleasantries. Tools and approval are auto-\
         bypassed."
            .into()
    })
}

async fn chat(cfg: Config, resume: Option<String>, want_tui: bool, no_tui: bool) -> Result<()> {
    let provider = cfg.resolve_provider()?;
    let api_key = std::env::var(&provider.api_key_env).ok();
    if api_key.is_none() {
        eprintln!(
            "warning: env var `{}` is not set — requests will be sent without an Authorization header.",
            provider.api_key_env
        );
    }
    let client: Arc<dyn LlmClient> = match provider.wire {
        Wire::OpenAi => Arc::new(OpenAiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Anthropic => Arc::new(AnthropicClient::new(provider.base_url.clone(), api_key)?),
        Wire::Gemini => Arc::new(GeminiClient::new(provider.base_url.clone(), api_key)?),
        Wire::Bedrock => Arc::new(BedrockClient::from_env()?),
        Wire::Vertex => Arc::new(VertexClient::from_env()?),
    };
    let client = wrap_with_fallback(client, &cfg);

    let home = merlion_config::merlion_home();
    let memory_store = Arc::new(MemoryStore::open(home.join("memory"))?);
    let skills_dir = home.join("skills");
    std::fs::create_dir_all(&skills_dir).ok();
    let bundled_skills_dir = std::env::current_dir().ok().map(|p| p.join("skills"));
    let skill_roots: Vec<std::path::PathBuf> = bundled_skills_dir
        .into_iter()
        .filter(|p| p.exists())
        .chain(std::iter::once(skills_dir.clone()))
        .collect();
    let skills = SkillSet::load(&skill_roots).unwrap_or_else(|e| {
        eprintln!("warning: failed to load skills: {e}");
        SkillSet::load(std::slice::from_ref(&skills_dir)).unwrap_or_default()
    });
    let skill_cfg = SkillToolsConfig::new(skills_dir.clone());

    let mut tools = ToolRegistry::new();
    merlion_tools::register_defaults(&mut tools);
    merlion_tools::register_memory(&mut tools, memory_store.clone());
    merlion_tools::register_skill_tools(&mut tools, skill_cfg);
    let task_tool = merlion_tools::register_task_tool(&mut tools);

    // Connect to configured MCP servers and inject their tools. Connection
    // failures are logged, not fatal — one broken server shouldn't take down
    // the agent.
    let mut mcp_clients: Vec<Arc<McpClient>> = Vec::new();
    let mcp_registry = McpRegistry::load_default().unwrap_or_else(|e| {
        eprintln!("warning: could not load MCP registry: {e}");
        McpRegistry::default()
    });
    for (server_name, entry) in mcp_registry.enabled_servers() {
        match autoload_server(server_name, entry, &mut tools).await {
            Ok(client) => mcp_clients.push(client),
            Err(e) => eprintln!("warning: MCP server `{server_name}` failed to load: {e}"),
        }
    }

    let options = AgentOptions {
        model: provider.model.clone(),
        temperature: cfg.model.temperature,
        max_tokens: cfg.model.max_tokens,
        max_iterations: cfg.max_iterations,
        ..AgentOptions::default()
    };

    let approver: Arc<dyn ToolApprover> = Arc::new(approver::ConsoleApprover::new());
    let agent = Arc::new(Agent::new(client, tools, options).with_approver(approver));
    task_tool.install_agent(&agent);
    let mut curator = Curator::default();

    let db = SessionDB::open_default()?;
    let session_id = match resume {
        Some(id) => id,
        None => {
            let id = uuid::Uuid::new_v4().to_string();
            db.create_session(&id, None)?;
            id
        }
    };
    let mut messages = db.load_messages(&session_id)?;
    if messages.is_empty() {
        let prompt = build_initial_system_prompt(&cfg, &memory_store, &skills);
        let m = Message::system(prompt);
        db.append_message(&session_id, &m)?;
        messages.push(m);
    }

    let is_tty = std::io::stdout().is_terminal();
    let use_tui = if want_tui {
        true
    } else if no_tui {
        false
    } else {
        is_tty
    };
    if use_tui {
        return tui::run(
            &cfg,
            &agent,
            &mut messages,
            &session_id,
            &skills,
            &memory_store,
            &db,
            &mut curator,
        )
        .await;
    }

    println!(
        "merlion — model {} · session {} · {} skills · {} memories · {} MCP server(s)",
        provider.model,
        &session_id[..8],
        skills.len(),
        memory_store.list().map(|v| v.len()).unwrap_or(0),
        mcp_clients.len(),
    );
    println!("Type your message, blank line to end, /exit to quit, /help for commands.");

    let mut rl = rustyline::DefaultEditor::new()?;
    loop {
        let input = match rl.readline("you> ") {
            Ok(line) => line,
            Err(rustyline::error::ReadlineError::Eof)
            | Err(rustyline::error::ReadlineError::Interrupted) => {
                break;
            }
            Err(e) => return Err(e.into()),
        };
        let trimmed = input.trim();
        if trimmed.is_empty() {
            continue;
        }
        let _ = rl.add_history_entry(trimmed);
        match trimmed {
            "/exit" | "/quit" => break,
            "/help" => {
                println!("/exit         — leave the session");
                println!("/new          — start a fresh session");
                println!("/share        — mint a join key to continue this session from a messaging platform");
                println!("/usage        — print message count");
                println!("/model        — print active model");
                println!("/skills       — list available skills");
                println!("/memory       — list memories");
                println!("/<skill-name> — invoke a skill (prepends its body as a turn)");
                continue;
            }
            "/share" => {
                let path = merlion_gateway::JoinKeyStore::default_path();
                let mut store = merlion_gateway::JoinKeyStore::load(&path).unwrap_or_default();
                store.gc();
                let key = store.mint(session_id.clone(), 600);
                if let Err(e) = store.save(&path) {
                    eprintln!(
                        "warning: failed to persist join key to {}: {e}",
                        path.display()
                    );
                }
                println!("Join key: {key}");
                println!("Send `/join {key}` from Telegram/Discord/Slack within 10 minutes to");
                println!("continue this conversation on that platform.");
                continue;
            }
            "/usage" => {
                println!("messages: {}", messages.len());
                continue;
            }
            "/model" => {
                println!("{}", provider.model);
                continue;
            }
            "/skills" => {
                print!("{}", skills.help_index());
                if !skills.help_index().ends_with('\n') {
                    println!();
                }
                continue;
            }
            "/memory" => {
                match memory_store.list() {
                    Ok(rows) if rows.is_empty() => println!("(no memories saved)"),
                    Ok(rows) => {
                        for r in rows {
                            println!("{}{}", r.name, r.hook);
                        }
                    }
                    Err(e) => eprintln!("error: {e}"),
                }
                continue;
            }
            "/new" => {
                let new_id = uuid::Uuid::new_v4().to_string();
                db.create_session(&new_id, None)?;
                println!("new session: {new_id}");
                messages.clear();
                let m = Message::system(build_initial_system_prompt(&cfg, &memory_store, &skills));
                db.append_message(&new_id, &m)?;
                messages.push(m);
                continue;
            }
            _ => {}
        }

        // Slash-command skill invocation: /<skill-name> or /<skill-name> <extra text>.
        let user_text = if let Some(rest) = trimmed.strip_prefix('/') {
            let (name, extra) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
            match skills.get(name) {
                Some(skill) => {
                    println!("\x1b[2m(invoking skill `{}`)\x1b[0m", skill.name);
                    let extra = extra.trim();
                    if extra.is_empty() {
                        skill.body.clone()
                    } else {
                        format!("{}\n\n---\nUser-supplied arguments: {extra}", skill.body)
                    }
                }
                None => {
                    eprintln!("unknown slash command: /{name} (try /help)");
                    continue;
                }
            }
        } else {
            trimmed.to_string()
        };

        curator.record_user_turn();
        let user_text = if let Some(nudge) = curator.nudge_if_due() {
            format!("<system-reminder>{nudge}</system-reminder>\n\n{user_text}")
        } else {
            user_text
        };

        let user_msg = Message::user(user_text);
        db.append_message(&session_id, &user_msg)?;
        messages.push(user_msg);

        let (tx, mut rx) = mpsc::channel::<AgentEvent>(64);
        let mut snapshot = messages.clone();
        let agent_ref = &agent;

        let run_fut = async {
            let res = agent_ref.run(&mut snapshot, tx).await;
            (res, snapshot)
        };
        let render_fut = async {
            print!("merlion> ");
            std::io::stdout().flush().ok();
            while let Some(ev) = rx.recv().await {
                match ev {
                    AgentEvent::AssistantDelta(s) => {
                        print!("{s}");
                        std::io::stdout().flush().ok();
                    }
                    AgentEvent::AssistantMessage(_) => {
                        println!();
                    }
                    AgentEvent::ToolCallStart {
                        name, arguments, ..
                    } => {
                        let preview = preview_args(&arguments);
                        println!("\x1b[2m· tool {name} {preview}\x1b[0m");
                    }
                    AgentEvent::ToolCallFinish {
                        is_error, content, ..
                    } => {
                        let head = content
                            .lines()
                            .next()
                            .unwrap_or("")
                            .chars()
                            .take(120)
                            .collect::<String>();
                        let tag = if is_error { "ERR" } else { "ok" };
                        println!("\x1b[2m  ↪ {tag}: {head}\x1b[0m");
                        print!("merlion> ");
                        std::io::stdout().flush().ok();
                    }
                    AgentEvent::IterationBudgetExhausted => {
                        println!("\n[iteration budget exhausted]");
                    }
                    AgentEvent::Done => {}
                    AgentEvent::Usage(_) => {}
                }
            }
        };

        let ((res, new_messages), _) = tokio::join!(run_fut, render_fut);

        for m in new_messages.iter().skip(messages.len()) {
            db.append_message(&session_id, m)?;
        }
        messages = new_messages;

        if let Err(e) = res {
            eprintln!("error: {e}");
        }
    }

    Ok(())
}

fn preview_args(v: &serde_json::Value) -> String {
    let s = v.to_string();
    let max = 80;
    if s.len() <= max {
        s
    } else {
        format!("{}", &s[..max])
    }
}

const DEFAULT_SYSTEM_PROMPT: &str =
    "You are Merlion, a coding agent. You have access to tools: bash, read, write, edit, ls, \
     grep, glob, web_fetch, memory, skill_create, skill_update. Prefer small, verifiable steps. \
     Use the `memory` tool to remember durable facts about the user, their project, or their \
     preferences — these persist across sessions. Create a skill with `skill_create` when you \
     discover a repeatable workflow worth naming. When you finish, stop calling tools and reply \
     in plain text.";

fn build_initial_system_prompt(cfg: &Config, memory: &MemoryStore, skills: &SkillSet) -> String {
    let base = cfg
        .system_prompt
        .as_deref()
        .unwrap_or(DEFAULT_SYSTEM_PROMPT);
    let mut out = String::from(base);
    let mem_block = memory.render_context_block(2048).unwrap_or_default();
    if !mem_block.trim().is_empty() {
        out.push_str("\n\n");
        out.push_str(&mem_block);
    }
    if !skills.is_empty() {
        out.push_str("\n\n# Available skills\n");
        out.push_str(
            "The user can invoke any of these with `/<name>` and you will see the skill body \
             appended to their next message. You can also reference them when suggesting next \
             steps.\n",
        );
        out.push_str(&skills.help_index());
    }
    out
}