1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
//! MatrixCode CLI - Full Implementation with REPL
mod display;
use anyhow::Result;
use clap::{Parser, Subcommand};
use display::{print_response_border, print_thinking_border};
use matrixcode_core::{
AgentEvent, Config, SessionManager, agent::AgentBuilder, cancel::CancellationToken,
create_provider_with_headers, infer_provider_type, memory::MemoryStorage, providers::Provider,
tools::all_tools_with_skills,
};
use matrixcode_tui::{TuiApp, restore_terminal, setup_terminal};
use std::path::{Path, PathBuf};
use std::sync::Arc;
// Handle /init commands for project overview generation
// Note: For async operations, we return a special command that will be handled in the agent task
fn handle_init_command(cmd: &str, project_path: Option<&Path>) -> InitCommandResult {
let parts: Vec<&str> = cmd.split_whitespace().collect();
let subcmd = parts.get(1).copied().unwrap_or("");
match subcmd {
"" => {
// /init without subcommand - generate project overview
InitCommandResult::GenerateOverview
}
"status" => {
// Show current project overview status
let path = project_path
.map(|p| p.to_path_buf())
.or_else(|| std::env::current_dir().ok())
.unwrap_or_default();
let overview_path = path.join(matrixcode_core::overview::OVERVIEW_FILENAME);
let matrix_dir = path.join(matrixcode_core::overview::MATRIXCODE_DIR);
let has_overview = overview_path.exists();
let has_memory = matrix_dir.join("memory.json").exists();
let has_session = matrix_dir.join("session.json").exists();
let overview_info = if has_overview {
if let Ok(content) = std::fs::read_to_string(&overview_path) {
let lines = content.lines().count();
format!("✓ exists ({} lines)", lines)
} else {
"✓ exists".into()
}
} else {
"❌ not found (use /init to generate)".into()
};
InitCommandResult::Message(format!(
"📊 Project: {}\n Overview: {}\n Memory: {}\n Session: {}",
path.display(),
overview_info,
if has_memory { "✓ exists" } else { "❌ none" },
if has_session {
"✓ exists"
} else {
"❌ none"
}
))
}
"clear" | "reset" => {
// Clear project overview
let path = project_path
.map(|p| p.to_path_buf())
.or_else(|| std::env::current_dir().ok())
.unwrap_or_default();
let overview_path = path.join(matrixcode_core::overview::OVERVIEW_FILENAME);
let matrix_dir = path.join(matrixcode_core::overview::MATRIXCODE_DIR);
let mut reset_msg = String::new();
if overview_path.exists() {
match std::fs::remove_file(&overview_path) {
Ok(_) => reset_msg.push_str(&format!(
"✓ Removed overview: {}\n",
overview_path.display()
)),
Err(e) => reset_msg.push_str(&format!("❌ Failed to remove overview: {}\n", e)),
}
}
if matrix_dir.exists() {
match std::fs::remove_dir_all(&matrix_dir) {
Ok(_) => reset_msg
.push_str(&format!("✓ Removed config dir: {}\n", matrix_dir.display())),
Err(e) => {
reset_msg.push_str(&format!("❌ Failed to remove config dir: {}\n", e))
}
}
}
if reset_msg.is_empty() {
InitCommandResult::Message("⚠️ No project configuration found to reset.".into())
} else {
reset_msg.push_str("\nRun '/init' to regenerate project overview");
InitCommandResult::Message(reset_msg)
}
}
_ => InitCommandResult::Message(
"Unknown init command. Use: /init, /init status, /init reset".into(),
),
}
}
/// Result of handling an init command
enum InitCommandResult {
/// A simple message to display
Message(String),
/// Request to generate project overview (async operation)
GenerateOverview,
}
#[derive(Parser)]
#[command(name = "matrixcode")]
#[command(about = "AI Code Agent with multi-model support")]
#[command(version)]
struct Cli {
/// Run mode
#[arg(short, long, default_value = "terminal")]
mode: String,
/// Continue last session
#[arg(short, long)]
continue_session: bool,
/// Resume session (interactive selection)
#[arg(short = 'r', long)]
resume: bool,
/// Resume specific session by ID (non-interactive)
#[arg(long)]
resume_id: Option<String>,
/// List sessions
#[arg(long)]
list_sessions: bool,
/// Extra skills directory
#[arg(long)]
skills_dir: Option<PathBuf>,
/// Think mode
#[arg(long, default_value = "true")]
think: bool,
/// Max tokens
#[arg(long, default_value = "16384")]
max_tokens: u32,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Start chat session
Chat {
/// Input content
#[arg(short, long)]
message: Option<String>,
},
/// Quick action
QuickAction {
/// Action type
#[arg(short, long)]
action: String,
/// Target file
#[arg(short, long)]
file: Option<String>,
},
/// Create new session
NewSession,
/// Show session history
History,
/// Show status
Status,
}
/// Get default model name for anthropic provider.
fn default_model() -> String {
"claude-sonnet-4-20250514".to_string()
}
/// Get default base URL for anthropic provider.
fn default_base_url() -> String {
"https://api.anthropic.com".to_string()
}
/// Resolve provider type from config, env, or model name.
fn resolve_provider(config: &Config, model: &str) -> matrixcode_core::providers::ProviderType {
// Try config first, then env var, then infer from model
let provider_str = config
.provider
.as_ref()
.cloned()
.or_else(|| std::env::var("PROVIDER").ok());
provider_str
.map(|p| match p.to_lowercase().as_str() {
"openai" => matrixcode_core::providers::ProviderType::OpenAI,
_ => matrixcode_core::providers::ProviderType::Anthropic,
})
.unwrap_or_else(|| infer_provider_type(model))
}
/// Resolve model from config, env, or default.
fn resolve_model(config: &Config) -> String {
config
.model
.clone()
.or_else(|| std::env::var("ANTHROPIC_MODEL").ok())
.unwrap_or_else(default_model)
}
/// Resolve base URL from config, env, or default.
fn resolve_base_url(config: &Config) -> String {
config
.base_url
.clone()
.or_else(|| std::env::var("ANTHROPIC_BASE_URL").ok())
.unwrap_or_else(default_base_url)
}
/// Resolve model with optional override, then config, env, or default.
fn resolve_model_with_override(override_model: Option<String>, config: &Config) -> String {
override_model
.or(config.model.clone())
.or_else(|| std::env::var("ANTHROPIC_MODEL").ok())
.unwrap_or_else(default_model)
}
/// Get model name with source annotation for status display.
fn model_with_source(config: &Config) -> String {
if let Some(model) = &config.model {
format!("{} (config)", model)
} else if let Ok(model) = std::env::var("ANTHROPIC_MODEL") {
format!("{} (env)", model)
} else {
format!("{} (default)", default_model())
}
}
fn main() -> Result<()> {
// Load .env file for development (silently ignore if not found)
let _ = dotenvy::from_path(".env");
let _ = dotenvy::from_path("packages/cli/.env");
let cli = Cli::parse();
// Handle list sessions
if cli.list_sessions {
list_sessions();
return Ok(());
}
// Handle interactive resume (-r)
if cli.resume {
return interactive_resume();
}
// Daemon mode doesn't require subcommand
if cli.mode == "daemon" {
return run_daemon_mode();
}
match cli.mode.as_str() {
"terminal" | "tui" => run_terminal_mode(cli),
"service" | "json" => run_service_mode(cli),
_ => {
eprintln!("Unknown mode: {}", cli.mode);
std::process::exit(1);
}
}
}
/// Interactive session resume - list sessions and let user select
fn interactive_resume() -> Result<()> {
use std::io::{self, Write};
let mgr = SessionManager::new()?;
let sessions = mgr.list_sessions();
if sessions.is_empty() {
println!("No sessions found.");
println!("\nTip: Use 'matrixcode' to start a new session.");
return Ok(());
}
println!("📚 Sessions:\n");
for (i, session) in sessions.iter().enumerate() {
let project = session
.project_path
.as_deref()
.map(|p| p.split('/').next_back().unwrap_or(p))
.unwrap_or("unknown");
let is_current = mgr.has_current() && mgr.current_id() == Some(session.id.as_str());
println!(
" {}. {} - {} ({} msgs, {} tokens) {}",
i + 1,
session.short_id(),
project,
session.message_count,
session.total_output_tokens,
if is_current { "[current]" } else { "" }
);
}
println!(
"\nSelect session to resume (1-{}), or 'q' to quit:",
sessions.len()
);
print!("> ");
io::stdout().flush()?;
// Simple stdin read
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let selection = input.trim().to_string();
// Debug output
eprintln!("DEBUG: selection = '{}'", selection);
if matches!(selection.as_str(), "q" | "quit" | "exit" | "") {
println!("Cancelled.");
return Ok(());
}
// Try to parse as number
if let Ok(num) = selection.parse::<usize>()
&& num > 0
&& num <= sessions.len()
{
let session = &sessions[num - 1];
println!("\n✓ Resuming session: {}", session.short_id());
println!(
" Project: {}",
session.project_path.as_deref().unwrap_or("unknown")
);
println!(" Messages: {}", session.message_count);
println!("\nStarting matrixcode with resumed session...\n");
// Run terminal mode with the selected session
let cli = Cli {
mode: "terminal".to_string(),
continue_session: false,
resume: false,
resume_id: Some(session.id.clone()),
list_sessions: false,
skills_dir: None,
think: true,
max_tokens: 16384,
command: None,
};
return run_terminal_mode(cli);
}
// Try to match by short_id or full id
for session in sessions.iter() {
if session.short_id() == selection || session.id == selection || session.id.starts_with(&selection)
{
println!("\n✓ Resuming session: {}", session.short_id());
println!(
" Project: {}",
session.project_path.as_deref().unwrap_or("unknown")
);
println!(" Messages: {}", session.message_count);
println!("\nStarting matrixcode with resumed session...\n");
let cli = Cli {
mode: "terminal".to_string(),
continue_session: false,
resume: false,
resume_id: Some(session.id.clone()),
list_sessions: false,
skills_dir: None,
think: true,
max_tokens: 16384,
command: None,
};
return run_terminal_mode(cli);
}
}
println!("Unknown session: {}", selection);
Ok(())
}
/// Load skills from directories (MatrixCode only)
fn load_skills(extra_dirs: &[PathBuf]) -> Vec<matrixcode_core::skills::Skill> {
use matrixcode_core::skills::discover_skills;
use std::path::PathBuf;
// Build list of skill directories to search (in priority order)
// Multi-level search: global → project config → project root
let mut roots: Vec<PathBuf> = Vec::new();
// 1. User's global skills directory (~/.matrix/skills)
if let Some(home) = dirs::home_dir() {
roots.push(home.join(".matrix").join("skills"));
}
// 2. Project-local skills directories (multiple locations)
if let Ok(cwd) = std::env::current_dir() {
// 2a. Project config directory (.matrix/skills)
roots.push(cwd.join(".matrix").join("skills"));
// 2b. Project root directory (skills/)
roots.push(cwd.join("skills"));
}
// 3. Extra directories from CLI option (--skills-dir)
roots.extend(extra_dirs.iter().cloned());
// Discover and load skills
discover_skills(&roots)
}
/// List sessions
fn list_sessions() {
use matrixcode_core::session::SessionManager;
let mgr = SessionManager::new().ok();
if let Some(mgr) = mgr {
let sessions = mgr.list_sessions();
if sessions.is_empty() {
println!("No sessions found.");
println!("\nTip: Use 'matrixcode' to start a new session.");
} else {
println!("Sessions:\n");
for (i, session) in sessions.iter().enumerate() {
let status = if mgr.has_current() && mgr.current_id() == Some(session.id.as_str()) {
" [current]"
} else {
""
};
let project = session.project_path.as_deref().unwrap_or("unknown");
println!(
" {}. {} ({}){}",
i + 1,
session.short_id(),
project,
status
);
}
println!("\nTotal: {} sessions", sessions.len());
println!("\nResume: matrixcode --resume <id>");
}
} else {
println!("No session manager available.");
println!("Sessions directory: ~/.matrix/sessions/");
}
}
/// Terminal mode with TUI
fn run_terminal_mode(cli: Cli) -> Result<()> {
// Load config
let config = Config::load();
// Get API configuration
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.ok_or_else(|| {
anyhow::anyhow!(
"No API key found. Set ANTHROPIC_AUTH_TOKEN or configure in ~/.matrix/config.json"
)
})?;
let model = resolve_model(&config);
let base_url = resolve_base_url(&config);
// Load skills
let skills_dirs: Vec<PathBuf> = cli.skills_dir.iter().cloned().collect();
let skills = load_skills(&skills_dirs);
// Handle single command without TUI
if let Some(cmd) = cli.command {
handle_command(cmd, &skills);
return Ok(());
}
// Setup tokio runtime
let rt = tokio::runtime::Runtime::new()?;
// Create channels for Agent communication
let (event_tx, event_rx) = tokio::sync::mpsc::channel(100);
let (task_tx, mut task_rx) = tokio::sync::mpsc::channel::<String>(10);
let (ask_tx, ask_rx) = tokio::sync::mpsc::channel::<String>(1);
// Create cancellation token
let cancel_token = CancellationToken::new();
// Load session BEFORE spawning agent task so TUI can also display restored messages
let project_path = std::env::current_dir().ok();
let (full_messages, api_messages, session_mgr_state, session_metadata) = {
let mut mgr = SessionManager::new().ok();
let mut full = Vec::new();
let mut api = Vec::new();
let mut metadata = None;
if let Some(ref mut mgr) = mgr {
if cli.continue_session || cli.resume_id.is_some() {
let session = if let Some(ref query) = cli.resume_id {
mgr.resume(query, project_path.as_deref()).ok().flatten()
} else {
mgr.continue_last(project_path.as_deref()).ok().flatten()
};
if let Some(s) = session {
// Full messages for TUI display
full = s.full_messages.clone();
// API messages (compressed if available) for Agent
api = s.api_messages().to_vec();
metadata = Some(s.metadata.clone());
}
} else {
let _ = mgr.start_new(project_path.as_deref());
}
}
(full, api, mgr, metadata)
};
// Clone things needed in the agent task
let agent_cancel = cancel_token.clone();
let agent_event_tx = event_tx.clone();
let agent_api_key = api_key.clone();
let agent_model = model.clone();
let agent_base_url = base_url.clone();
let agent_think = cli.think;
let agent_max_tokens = cli.max_tokens;
let agent_restored_messages = api_messages.clone(); // Agent uses compressed messages
let agent_project_path = project_path.clone();
let agent_approve_mode = config
.approve_mode
.as_ref()
.map(|m| matrixcode_core::approval::ApproveMode::parse(m))
.unwrap_or(matrixcode_core::approval::ApproveMode::Ask);
// Provider from config, or infer from model name
let agent_provider = config
.provider
.as_ref()
.map(|p| match p.as_str() {
"openai" => matrixcode_core::providers::ProviderType::OpenAI,
_ => matrixcode_core::providers::ProviderType::Anthropic,
})
.unwrap_or_else(|| infer_provider_type(&agent_model));
// Create shared approve mode atomic - accessible by both agent and TUI
let shared_approve_mode =
std::sync::Arc::new(std::sync::atomic::AtomicU8::new(agent_approve_mode.to_u8()));
// Read fast_model config for keyword extraction
let agent_fast_model = config
.fast_model
.clone()
.or_else(|| std::env::var("ANTHROPIC_DEFAULT_HAIKU_MODEL").ok());
// Extra headers from config
let agent_extra_headers = config.extra_headers.clone();
// Clone skills for agent task
let agent_skills = skills.clone();
let agent_shared_approve_mode = shared_approve_mode.clone();
// Spawn Agent task with real Agent
let agent_task = rt.spawn(async move {
// Create provider using factory
let provider = match create_provider_with_headers(
agent_provider,
agent_api_key.clone(),
agent_model.clone(),
Some(agent_base_url.clone()),
agent_extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Failed to create provider: {}", e),
Some("provider_error".to_string()),
None,
)).await;
return;
}
};
// Create fast provider for keyword extraction
let fast_provider: Option<Box<dyn Provider>> = agent_fast_model.as_ref().and_then(|fast_model| {
let fast_type = infer_provider_type(fast_model);
create_provider_with_headers(
fast_type,
agent_api_key.clone(),
fast_model.clone(),
Some(agent_base_url.clone()),
agent_extra_headers.clone(),
).ok()
});
// Load memory
let project_path_ref = agent_project_path.as_deref();
let mut memory_storage = matrixcode_core::memory::MemoryStorage::new(project_path_ref).ok();
let memory = memory_storage.as_ref()
.and_then(|ms| ms.load_combined().ok());
// Send MemoryLoaded event if we have entries
if let Some(ref mem) = memory
&& !mem.entries.is_empty() {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::MemoryLoaded,
matrixcode_core::EventData::Memory {
summary: mem.generate_prompt_summary(10),
entries_count: mem.entries.len(),
},
)).await;
}
// Initial memory summary (static, will be updated dynamically before each turn)
let initial_memory_summary = memory.as_ref()
.map(|mem| mem.generate_prompt_summary(20))
.unwrap_or_default();
// Load project overview (MATRIX.md)
let project_overview = project_path_ref
.and_then(|path| matrixcode_core::overview::ProjectOverview::load(path).ok().flatten());
// Log overview loading
if let Some(ref overview) = project_overview {
matrixcode_core::debug::debug_log().log("overview", &format!("Loaded project overview: {} chars", overview.content.len()));
}
// Build system prompt with memory, project overview and skills
let system_prompt = matrixcode_core::prompt::build_system_prompt(
&matrixcode_core::prompt::PromptProfile::Default,
&agent_skills,
project_overview.as_ref().map(|o| o.content.as_str()),
if initial_memory_summary.is_empty() { None } else { Some(&initial_memory_summary) },
);
// Build agent with external event sender
let mut agent = AgentBuilder::new(provider)
.system_prompt(system_prompt)
.model_name(agent_model.clone())
.max_tokens(agent_max_tokens)
.think(agent_think)
.tools(all_tools_with_skills(Arc::new(agent_skills.clone())))
.event_tx(agent_event_tx.clone())
.approve_mode(agent_approve_mode)
.build();
// Use the shared approve mode so TUI can update it in real-time
agent.set_approve_mode_shared(agent_shared_approve_mode);
// Restore messages from pre-loaded session
if !agent_restored_messages.is_empty() {
agent.set_messages(agent_restored_messages);
}
// Re-open session manager inside the task for saving
let mut session_mgr = session_mgr_state;
// Set cancel token
agent.set_cancel_token(agent_cancel.clone());
agent.set_ask_channel(ask_rx);
// Turn counter for periodic cleanup
let mut turn_count: usize = 0;
// Auto-analyze project structure on first run if no memories exist
if let Some(ref project_path) = agent_project_path
&& let Some(ref mut ms) = memory_storage {
let memory_file = project_path.join(".matrix/memory.json");
if !memory_file.exists() {
// First time in this project - analyze structure
let count = matrixcode_core::memory::generate_project_structure_memories(
project_path.as_path(),
ms
);
if count > 0 {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("🧠 自动分析项目结构,创建 {} 条记忆", count),
None,
)).await;
}
}
}
log::info!("Agent task: entering receive loop");
while let Some(msg) = task_rx.recv().await {
log::info!("Agent task: received message (len={})", msg.len());
// Make msg mutable for skill activation transformation
let mut msg = msg;
// Check cancellation
if agent_cancel.is_cancelled() {
agent_event_tx.send(AgentEvent::error(
"Operation interrupted by user".to_string(),
Some("interrupted".to_string()),
None,
)).await.ok();
agent_cancel.reset();
continue;
}
// Handle /init commands
if msg.starts_with("/init") {
let result = handle_init_command(&msg, agent_project_path.as_deref());
match result {
InitCommandResult::Message(msg) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: msg,
percentage: None,
},
)).await;
}
InitCommandResult::GenerateOverview => {
// Generate project overview using AI
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: "🔄 Generating project overview...".into(),
percentage: Some(10),
},
)).await;
if let Some(ref path) = agent_project_path {
// Create a new provider for overview generation
let overview_provider = match create_provider_with_headers(
agent_provider,
agent_api_key.clone(),
agent_model.clone(),
Some(agent_base_url.clone()),
agent_extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Failed to create provider for overview: {}", e),
Some("provider_error".to_string()),
None,
)).await;
continue;
}
};
match matrixcode_core::overview::ProjectOverview::generate_with_ai(path.as_path(), overview_provider.as_ref()).await {
Ok(overview) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: format!("✓ Project overview generated: {}", overview.path.display()),
percentage: Some(100),
},
)).await;
// Log overview content for debug
matrixcode_core::debug::debug_log().log("overview", &format!("Generated overview with {} chars", overview.content.len()));
}
Err(e) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Failed to generate overview: {}", e),
Some("overview_error".into()),
None,
)).await;
}
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
String::from("No project path set. Cannot generate overview."),
Some("no_project".into()),
None,
)).await;
}
}
}
continue;
}
// Handle /skills commands
if msg == "/skills" || msg.starts_with("/skills ") {
let parts: Vec<&str> = msg.split_whitespace().collect();
let subcmd = parts.get(1).copied().unwrap_or("");
let response = if subcmd.is_empty() || subcmd == "list" {
// List all available skills
if agent_skills.is_empty() {
"📚 No skills loaded.\n\nSkills directories searched (in order):\n 1. ~/.matrix/skills (MatrixCode global)\n 2. .matrix/skills (Project local)\n 3. --skills-dir (CLI option)\n\nTo add a skill, create a .md file with frontmatter:\n---\nname: my-skill\ndescription: My skill description\n---\nSkill content here...".to_string()
} else {
let mut info = format!("📚 Loaded skills ({}):\n\n", agent_skills.len());
for skill in &agent_skills {
// Show skill name, description, and source
info.push_str(&format!("• {}: {}\n", skill.name, skill.description));
}
info.push_str("\nUsage: `/skills <name>` to view skill content.");
info.push_str("\n `/skills reload` to re-scan directories.");
info
}
} else if subcmd == "reload" {
// Reload skills from directories
let skills_dirs: Vec<PathBuf> = Vec::new();
let new_skills = load_skills(&skills_dirs);
let count = new_skills.len();
// Note: we can't actually update agent_skills in the async task,
// but we can show the reload result
format!("🔄 Skills reloaded: {} skill(s) found.\n\nNote: Restart MatrixCode to use new skills.", count)
} else {
// Show specific skill content
let skill_name = subcmd;
if let Some(skill) = agent_skills.iter().find(|s| s.name == skill_name) {
let files = matrixcode_core::skills::list_skill_files(&skill.dir);
let files_info = if files.len() > 1 {
format!("\n\n📁 Associated files:\n{}", files.iter().map(|f| format!(" - {}", f)).collect::<Vec<_>>().join("\n"))
} else {
String::new()
};
format!("📚 Skill: {}\n\n{}\n{}\n\nSource: {}",
skill.name,
skill.body,
files_info,
skill.source_file.display()
)
} else {
// Try to suggest similar skill names
let similar: Vec<_> = agent_skills.iter()
.filter(|s| s.name.contains(skill_name) || skill_name.contains(&s.name))
.map(|s| s.name.as_str())
.collect();
if similar.is_empty() {
format!("❌ Skill '{}' not found.\n\nUse `/skills` to see available skills.", skill_name)
} else {
format!("❌ Skill '{}' not found.\n\nSimilar skills: {}", skill_name, similar.join(", "))
}
}
};
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: response,
percentage: None,
},
)).await;
continue;
}
// Handle /skill_name form (direct skill invocation)
if msg.starts_with("/") && !msg.starts_with("/skills")
&& !msg.starts_with("/compact") && !msg.starts_with("/compress")
&& !msg.starts_with("/help") && !msg.starts_with("/init")
&& !msg.starts_with("/memory") && !msg.starts_with("/overview")
&& !msg.starts_with("/save") && !msg.starts_with("/sessions")
&& !msg.starts_with("/resume") && !msg.starts_with("/loop")
&& !msg.starts_with("/exit") && !msg.starts_with("/quit")
&& !msg.starts_with("/clear") && !msg.starts_with("/debug")
&& !msg.starts_with("/status") && !msg.starts_with("/new")
&& !msg.starts_with("/load") && !msg.starts_with("/mode")
&& !msg.starts_with("/model") && !msg.starts_with("/retry")
&& !msg.starts_with("/history") && !msg.starts_with("/cron")
&& msg != "/"
{
// Try to match skill name
let skill_name = msg.trim_start_matches('/');
// Debug: log skill lookup
matrixcode_core::debug::debug_log().log("skill",
&format!("Looking for skill '{}' in {} available skills", skill_name, agent_skills.len()));
for sk in &agent_skills {
matrixcode_core::debug::debug_log().log("skill", &format!(" - available: {}", sk.name));
}
if let Some(skill) = agent_skills.iter().find(|s| s.name == skill_name) {
// Build skill activation message
let files = matrixcode_core::skills::list_skill_files(&skill.dir);
let files_info = if files.len() > 1 {
format!("\n\n📁 Associated files (use `read` tool to explore):\n{}",
files.iter().map(|f| format!(" - {}", f)).collect::<Vec<_>>().join("\n"))
} else {
String::new()
};
// Create user message that activates the skill
let skill_activation = format!(
"使用 skill '{}' 来处理当前任务。\n\n---\n{}\n---\n{}\n\n请按照上述 skill 指导开始执行。",
skill.name,
skill.body,
files_info
);
// Send to agent for execution (not just display)
msg = skill_activation;
// Log skill activation
matrixcode_core::debug::debug_log().log("skill", &format!("Activated skill: {}", skill.name));
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: format!("🎯 Activating skill: {}", skill.name),
percentage: None,
},
)).await;
// Continue to normal agent processing with modified message
} else {
// Debug: skill not found
matrixcode_core::debug::debug_log().log("skill", &format!("Skill '{}' not found", skill_name));
}
}
if msg == "/compact" || msg == "/compress" {
// Manual compression request
let original_tokens = matrixcode_core::compress::estimate_total_tokens(agent.get_messages());
if original_tokens > 100 {
// Send compression triggered event
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::CompressionTriggered,
matrixcode_core::EventData::Progress {
message: format!("Compressing {} tokens...", original_tokens),
percentage: None,
},
)).await;
// Perform compression
match matrixcode_core::compress::compress_messages(
agent.get_messages(),
matrixcode_core::compress::CompressionStrategy::SlidingWindow,
&matrixcode_core::compress::CompressionConfig::default(),
) {
Ok(compressed) => {
let compressed_tokens = matrixcode_core::compress::estimate_total_tokens(&compressed);
agent.set_messages(compressed);
let ratio = compressed_tokens as f32 / original_tokens as f32;
// Send completion event
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::CompressionCompleted,
matrixcode_core::EventData::Compression {
original_tokens: original_tokens as u64,
compressed_tokens: compressed_tokens as u64,
ratio,
},
)).await;
// Debug log
matrixcode_core::debug_compress!(original_tokens as u32, compressed_tokens, ratio);
}
Err(e) => {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Compression failed: {}", e),
None,
None,
)).await;
}
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"Context too small, no need to compress",
None,
)).await;
}
continue;
}
if let Some(mode) = msg.strip_prefix("/mode:") {
let new_mode = match mode {
"ask" => matrixcode_core::approval::ApproveMode::Ask,
"auto" => matrixcode_core::approval::ApproveMode::Auto,
"strict" => matrixcode_core::approval::ApproveMode::Strict,
_ => continue,
};
agent.set_approve_mode(new_mode);
continue;
}
// Handle /new command - create new session
if msg == "/new" {
if let Some(ref mut mgr) = session_mgr {
let project_path = std::env::current_dir().ok();
mgr.start_new(project_path.as_deref()).ok();
agent.clear_history();
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::session_ended()).await;
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"✓ New session created",
None,
)).await;
}
continue;
}
// Handle /memory command
if msg == "/memory" || msg.starts_with("/memory ") {
let parts: Vec<&str> = msg.split_whitespace().collect();
let subcmd = parts.get(1).copied().unwrap_or("");
if let Some(ref mut ms) = memory_storage {
let response = match subcmd {
"" | "list" => {
// List all memories with better formatting
if let Ok(mem) = ms.load_combined() {
if mem.entries.is_empty() {
"📝 No memories stored yet.\n\nMemories are auto-detected from AI responses.\nUse '/memory analyze' to scan project structure.".to_string()
} else {
let stats = mem.generate_statistics();
let mut info = stats.format_summary();
info.push_str("\n\n📋 Recent entries:\n");
for (i, entry) in mem.entries.iter().enumerate().take(10) {
let content_preview: String = entry.content.chars().take(80).collect();
let content_preview = content_preview.trim_end_matches('\n');
let importance_marker = if entry.importance >= 80.0 { "⭐" } else { "" };
let manual_marker = if entry.is_manual { "📝" } else { "" };
info.push_str(&format!("{}. {}{}{} {} {}\n",
i + 1,
entry.category.icon(),
importance_marker,
manual_marker,
content_preview,
entry.category.display_name()));
}
if mem.entries.len() > 10 {
info.push_str(&format!("\n... and {} more entries", mem.entries.len() - 10));
}
info.push_str("\n\nCommands: stats, search <query>, add <content>, forget <id>, analyze, merge");
info
}
} else {
"❌ Failed to load memories".to_string()
}
}
"stats" => {
// Show detailed memory stats
if let Ok(mem) = ms.load_combined() {
let stats = mem.generate_statistics();
stats.format_summary()
} else {
"❌ Failed to get memory stats".to_string()
}
}
"search" => {
// Search memories by query
let query = parts.get(2..).map(|p| p.join(" ")).unwrap_or_default();
if query.is_empty() {
"Usage: /memory search <query>".to_string()
} else if let Ok(mem) = ms.load_combined() {
let results = mem.search_with_limit(&query, Some(10));
if results.is_empty() {
format!("No memories found for '{}'", query)
} else {
let mut info = format!("🔍 Search results for '{}':\n\n", query);
for (i, entry) in results.iter().enumerate() {
info.push_str(&format!("{}. {} {} (重要性: {:.0})\n {}\n",
i + 1,
entry.category.icon(),
entry.category.display_name(),
entry.importance,
entry.content.chars().take(100).collect::<String>().trim_end_matches('\n')));
}
info
}
} else {
"❌ Failed to search memories".to_string()
}
}
"add" => {
// Add manual memory
let content = parts.get(2..).map(|p| p.join(" ")).unwrap_or_default();
if content.is_empty() {
"Usage: /memory add <content>".to_string()
} else if let Ok(mut mem) = ms.load_global() {
// Infer category from content
let category = matrixcode_core::memory::infer_category_from_content(&content);
let entry = matrixcode_core::memory::MemoryEntry::manual(category, content.clone());
mem.add(entry);
if ms.save_global(&mem).is_ok() {
format!("✓ Added memory: {} {}\n {}", category.icon(), category.display_name(), content)
} else {
"❌ Failed to save memory".to_string()
}
} else {
"❌ Failed to add memory".to_string()
}
}
"forget" | "delete" | "remove" => {
// Delete memory by index or ID
let target = parts.get(2).copied().unwrap_or("");
if target.is_empty() {
"Usage: /memory forget <index|id>".to_string()
} else if let Ok(mut mem) = ms.load_combined() {
// Try to parse as index first
let removed = if let Ok(idx) = target.parse::<usize>() {
if idx > 0 && idx <= mem.entries.len() {
let entry = mem.entries.remove(idx - 1);
Some(entry.content)
} else {
None
}
} else {
// Try to remove by ID (partial match)
mem.remove(target).then_some(target.to_string())
};
if let Some(content) = removed {
// Save to appropriate storage
if ms.save_global(&mem).is_err() {
// Try project storage if global failed
if let Err(e) = ms.save_project(&mem) {
log::warn!("Failed to save project memory: {}", e);
}
}
format!("✓ Removed memory: {}", content.chars().take(50).collect::<String>())
} else {
format!("❌ Memory not found: {}", target)
}
} else {
"❌ Failed to delete memory".to_string()
}
}
"analyze" => {
// Analyze project structure and create memories
if let Some(ref project_path) = agent_project_path {
let count = matrixcode_core::memory::generate_project_structure_memories(
project_path.as_path(),
ms
);
if count > 0 {
format!("✓ Generated {} structure memories from project analysis", count)
} else {
"No new structure memories generated (may already exist)".to_string()
}
} else {
"❌ No project path available for analysis".to_string()
}
}
"merge" => {
// Execute smart merge
if let Ok(mut mem) = ms.load_combined() {
let count = mem.smart_merge();
if count > 0 {
if let Err(e) = ms.save_global(&mem) {
log::warn!("Failed to save merged memories: {}", e);
}
format!("✓ Merged {} similar memories", count)
} else {
"No similar memories found to merge".to_string()
}
} else {
"❌ Failed to merge memories".to_string()
}
}
"clear" => {
// Clear all memories (with confirmation)
if let Ok(mut mem) = ms.load_global() {
let count = mem.entries.len();
mem.entries.clear();
if let Err(e) = ms.save_global(&mem) {
log::warn!("Failed to clear memories: {}", e);
}
format!("✓ Cleared {} memories", count)
} else {
"❌ Failed to clear memories".to_string()
}
}
"help" => {
"📝 Memory commands:\n\
list - Show all memories\n\
stats - Show detailed statistics\n\
search - Search memories by query\n\
add - Add manual memory\n\
forget - Delete memory by index\n\
analyze - Scan project structure\n\
merge - Merge similar memories\n\
clear - Clear all memories".to_string()
}
_ => {
"Unknown memory command. Use '/memory help' for available commands.".to_string()
}
};
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
response,
None,
)).await;
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"❌ Memory storage not available",
None,
)).await;
}
continue;
}
// Handle /overview command
if msg == "/overview" || msg.starts_with("/overview ") {
let parts: Vec<&str> = msg.split_whitespace().collect();
let subcmd = parts.get(1).copied().unwrap_or("");
let cwd = std::env::current_dir().unwrap_or_default();
let overview_path = cwd.join(matrixcode_core::overview::OVERVIEW_FILENAME);
let response = match subcmd {
"" | "show" => {
// Show current overview
if overview_path.exists() {
let content = std::fs::read_to_string(&overview_path).unwrap_or_default();
let lines = content.lines().count();
format!("📄 Project Overview ({} lines):\n\n{}", lines,
content.chars().take(2000).collect::<String>())
} else {
"❌ No overview found. Run '/init' to generate one.".to_string()
}
}
"regenerate" | "gen" => {
// Trigger overview regeneration (handled by /init)
"Use '/init' to regenerate project overview".to_string()
}
"path" => {
format!("Overview path: {}", overview_path.display())
}
_ => {
"Unknown overview command. Use: show, regenerate, path".to_string()
}
};
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
response,
None,
)).await;
continue;
}
// Handle /save command
if msg == "/save" || msg.starts_with("/save ") {
let parts: Vec<&str> = msg.split_whitespace().collect();
let name = parts.get(1).copied();
if let Some(ref mut mgr) = session_mgr {
let messages = agent.get_messages();
mgr.set_messages(messages.to_vec());
// Save with optional name
if let Some(n) = name {
// Rename then save
if let Err(e) = mgr.rename_current(n) {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Failed to rename session: {}", e),
None,
None,
)).await;
}
}
if let Err(e) = mgr.save_current() {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Failed to save session: {}", e),
None,
None,
)).await;
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
if let Some(ref name) = name {
format!("✓ Session saved as '{}'", name)
} else {
"✓ Session saved".to_string()
},
None,
)).await;
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"❌ Session manager not available",
None,
)).await;
}
continue;
}
// Handle /sessions command
if msg == "/sessions" || msg == "/resume" {
if let Some(ref mgr) = session_mgr {
let sessions = mgr.list_sessions();
if sessions.is_empty() {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"No saved sessions found",
None,
)).await;
} else {
let mut info = format!("📚 Sessions ({}):\n\n", sessions.len());
for session in sessions.iter().take(10) {
let project = session.project_path.as_deref()
.map(|p| p.split('/').next_back().unwrap_or(p))
.unwrap_or("unknown");
info.push_str(&format!("• {} - {} ({} msgs, {} out)\n",
session.short_id(),
project,
session.message_count,
session.total_output_tokens));
}
if sessions.len() > 10 {
info.push_str(&format!("\n... and {} more sessions", sessions.len() - 10));
}
info.push_str("\n\nUse '/load <id>' to resume a session");
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
info,
None,
)).await;
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"❌ Session manager not available",
None,
)).await;
}
continue;
}
// Handle /load command
if msg.starts_with("/load ") {
let session_id = msg.strip_prefix("/load ").unwrap_or("");
if let Some(ref mut mgr) = session_mgr {
// Use resume to load session
let project_path = std::env::current_dir().ok();
if mgr.resume(session_id, project_path.as_deref()).is_ok() {
if let Some(msgs) = mgr.messages() {
let messages = msgs.to_vec();
agent.set_messages(messages.clone());
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("✓ Session '{}' loaded ({} messages)", session_id, messages.len()),
None,
)).await;
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("❌ Session '{}' not found", session_id),
None,
)).await;
}
} else {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
"❌ Session manager not available",
None,
)).await;
}
continue;
}
// Dynamic memory retrieval: update memory summary based on current context
// This uses AI keyword extraction with fast_provider if available
if let Some(ref mem) = memory {
let context_keywords = if let Some(ref fp) = fast_provider {
// Use AI-enhanced keyword extraction
matrixcode_core::memory::extract_keywords_hybrid(&msg, Some(fp.as_ref())).await
} else {
// Fallback to rule-based extraction
matrixcode_core::memory::extract_context_keywords(&msg)
};
// Generate context-aware summary using pre-extracted keywords (avoid double extraction)
let contextual_summary = mem.generate_contextual_summary_with_keywords(&context_keywords, 15);
// Update agent's memory summary (will rebuild system prompt internally)
if !contextual_summary.is_empty() {
agent.update_memory_summary(Some(contextual_summary));
// Debug log: keywords extracted
matrixcode_core::debug::debug_log().keywords_extracted(&context_keywords, &msg);
// Send keywords event for TUI display (only in debug mode)
if !context_keywords.is_empty() {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::KeywordsExtracted,
matrixcode_core::EventData::Keywords {
keywords: context_keywords,
source: msg.chars().take(50).collect(),
},
)).await;
}
}
}
// Run agent - events are sent directly via event_tx during run()
// Track turn count for periodic cleanup
turn_count += 1;
match agent.run(msg.clone()).await {
Ok(_) => {
// Auto-save session after each turn
if let Some(ref mut mgr) = session_mgr {
let (input_tokens, output_tokens) = agent.get_token_counts();
let messages = agent.get_messages();
// Save compressed messages for API, full messages are already stored
mgr.set_compressed_messages(messages.to_vec());
mgr.update_stats(input_tokens as u32, output_tokens);
if let Err(e) = mgr.save_current() {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::error(
format!("Session save failed: {}", e),
None,
None,
)).await;
}
// Debug log: session save
matrixcode_core::debug::debug_log().session_save(messages.len(), output_tokens);
}
// Auto-detect and save memories (enhanced)
if let Some(ref mut ms) = memory_storage {
let messages = agent.get_messages();
// 1. Check for user feedback/correction in the user message
let feedback_results = matrixcode_core::memory::detect_feedback_patterns(&msg);
if !feedback_results.is_empty()
&& let Ok(mut mem) = ms.load_combined() {
let feedback_count = feedback_results.len();
for feedback in feedback_results {
matrixcode_core::memory::apply_feedback_to_memory(&mut mem, &feedback);
}
// Save to appropriate storage
if mem.entries.iter().any(|e| e.tags.contains(&"project".to_string())) {
if let Err(e) = ms.save_project(&mem) {
log::warn!("Failed to save project memory: {}", e);
}
} else {
if let Err(e) = ms.save_global(&mem) {
log::warn!("Failed to save global memory: {}", e);
}
}
// Send feedback event
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("🧠 Learned from feedback: {} corrections", feedback_count),
None,
)).await;
}
// 2. Detect from last assistant message using AI (fast model)
if let Some(last_msg) = messages.last() {
let text = match &last_msg.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().filter_map(|b| match b {
matrixcode_core::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
}).collect::<Vec<_>>().join("\n")
}
};
// Use AI extraction with fast provider (smart detection)
// Falls back to rule-based if AI fails or unavailable
let detected = if let Some(ref fp) = fast_provider {
// AI extraction with fast model
let model_name = agent_fast_model.clone().unwrap_or_default();
let extractor = matrixcode_core::memory::AiMemoryExtractor::new(
fp.clone_box(),
model_name,
);
matrixcode_core::memory::detect_memories_smart(
&text, None, Some(&extractor)
).await
} else {
// Fallback to rule-based detection
matrixcode_core::memory::detect_memories_from_text(&text, None)
};
if !detected.is_empty() {
let detected_count = detected.len();
// Save each entry to appropriate storage
for entry in detected {
// Determine if project-specific based on tags or context
let is_project = entry.tags.contains(&"project".to_string())
|| agent_project_path.is_some();
if let Err(e) = ms.add_entry(entry, is_project) {
log::warn!("Failed to add memory entry: {}", e);
}
}
// Debug log: memory save
matrixcode_core::debug_memory!(detected_count, text.len());
// Send event to TUI
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::with_data(
matrixcode_core::EventType::MemoryDetected,
matrixcode_core::EventData::Memory {
summary: format!("检测到 {} 条记忆", detected_count),
entries_count: detected_count,
},
)).await;
}
// 3. Infer preferences from behavior (every 5 turns)
if turn_count.is_multiple_of(5) && messages.len() >= 3
&& let Ok(mut mem) = ms.load_combined() {
let config = matrixcode_core::memory::BehaviorInferenceConfig::default();
let inferred = matrixcode_core::memory::apply_behavior_inferences_to_memory(
messages, &mut mem, Some(&config)
);
if inferred > 0 {
if let Err(e) = ms.save_global(&mem) {
log::warn!("Failed to save inferred preferences: {}", e);
}
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("🧠 推断出 {} 个使用偏好", inferred),
None,
)).await;
}
}
}
// 4. Periodic cleanup (every 10 turns)
if turn_count.is_multiple_of(10)
&& let Ok(mut mem) = ms.load_combined() {
// Apply time decay
mem.apply_time_decay();
// Smart merge
let merged = mem.smart_merge();
// Prune low importance
mem.prune();
// Save
if let Err(e) = ms.save_global(&mem) {
log::warn!("Failed to save memory after maintenance: {}", e);
}
if merged > 0 {
let _ = agent_event_tx.send(matrixcode_core::AgentEvent::progress(
format!("🧠 合并了 {} 条相似记忆", merged),
None,
)).await;
}
}
}
}
Err(e) => {
agent_event_tx.send(AgentEvent::error(
format!("Agent error: {}", e),
Some("agent_error".to_string()),
None,
)).await.ok();
}
}
}
});
// Enter runtime context so tokio channels work in sync code
let _guard = rt.enter();
// Check if debug mode should be enabled from environment
let debug_mode = std::env::var("MATRIXCODE_DEBUG")
.map(|v| v == "1" || v == "true" || v == "verbose")
.unwrap_or(false);
// Setup terminal for TUI
let mut terminal = setup_terminal()?;
// Create App and run it (TUI runs in sync context, but tokio channels are usable)
let mut app = TuiApp::new(task_tx, event_rx, cancel_token.clone())
.with_ask_channel(ask_tx)
.with_shared_approve_mode(shared_approve_mode)
.with_config(&model, cli.think, cli.max_tokens, None)
.with_debug_mode(debug_mode);
// Load restored messages if any (full messages for TUI display)
if !full_messages.is_empty() {
app.load_messages(full_messages);
// Restore token stats from session metadata
if let Some(ref meta) = session_metadata {
app.set_token_stats(
meta.last_input_tokens,
meta.total_output_tokens,
meta.message_count,
);
}
}
let result = app.run(&mut terminal);
// Restore terminal first (so user sees prompt immediately)
restore_terminal()?;
// Cleanup: cancel agent task and wait for completion
cancel_token.cancel();
// Give agent task a short grace period to finish
let cleanup_result = rt.block_on(async {
tokio::time::timeout(tokio::time::Duration::from_millis(500), async {
// Just wait - the task will see cancel_token.cancelled() and exit
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
})
.await
});
if cleanup_result.is_err() {
// Timeout - abort the task
agent_task.abort();
} else {
// Task should have finished gracefully, drop the handle
std::mem::drop(agent_task);
}
result
}
/// Handle single command with actual agent execution
fn handle_command(cmd: Commands, skills: &[matrixcode_core::skills::Skill]) {
// Load config
let config = Config::load();
// Get API configuration
let api_key = config.api_key.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.unwrap_or_else(|| {
eprintln!("❌ No API key found. Set ANTHROPIC_AUTH_TOKEN or configure in ~/.matrix/config.json");
std::process::exit(1);
});
let model = resolve_model(&config);
let base_url = resolve_base_url(&config);
let approve_mode = config
.approve_mode
.as_ref()
.map(|m| matrixcode_core::approval::ApproveMode::parse(m))
.unwrap_or(matrixcode_core::approval::ApproveMode::Ask);
// Create tokio runtime
let rt = match tokio::runtime::Runtime::new() {
Ok(rt) => rt,
Err(e) => {
eprintln!("Failed to create tokio runtime: {}", e);
return;
}
};
rt.block_on(async {
match cmd {
Commands::Chat { message } => {
// Interactive or single-shot chat
if let Some(msg) = message {
// Single-shot chat
// Build system prompt with skills
let system_prompt = matrixcode_core::prompt::build_system_prompt(
&matrixcode_core::prompt::PromptProfile::Default,
skills,
None,
None,
);
// Create provider using factory
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to create provider: {}", e);
return;
}
};
// Build agent with event channel
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(100);
let mut agent = AgentBuilder::new(provider)
.system_prompt(system_prompt)
.model_name(model.clone())
.max_tokens(4096)
.tools(all_tools_with_skills(Arc::new(skills.to_vec())))
.approve_mode(approve_mode)
.event_tx(event_tx)
.build();
// Run agent
let run_future = agent.run(msg);
// Process events while running
let result = tokio::select! {
r = run_future => r,
_ = async {
while let Some(event) = event_rx.recv().await {
// Log events for debug
if event.event_type == matrixcode_core::EventType::Error {
if let Some(data) = &event.data {
eprintln!("⚠️ Error event: {:?}", data);
}
}
}
} => {
Err(anyhow::anyhow!("Event channel closed"))
}
};
match result {
Ok(_) => {
// Get all messages to show thinking first, then result
let messages = agent.get_messages();
// First, show thinking content if any
for msg in messages.iter() {
if msg.role == matrixcode_core::providers::Role::Assistant {
// Check if this is thinking content
let is_thinking = match &msg.content {
matrixcode_core::providers::MessageContent::Text(t) => {
t.contains("<thinking>") || t.starts_with("Let me") || t.starts_with("I need to")
},
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().any(|b| match b {
matrixcode_core::ContentBlock::Thinking { thinking, .. } => !thinking.is_empty(),
_ => false,
})
},
};
if is_thinking {
let text = match &msg.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().filter_map(|b| match b {
matrixcode_core::ContentBlock::Thinking { thinking, .. } => Some(thinking.as_str()),
matrixcode_core::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
}).collect::<Vec<_>>().join("\n")
},
};
print_thinking_border(&text);
}
}
}
// Then show the final assistant message
if let Some(last) = messages.last()
&& last.role == matrixcode_core::providers::Role::Assistant {
let text = match &last.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().filter_map(|b| match b {
matrixcode_core::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
}).collect::<Vec<_>>().join("\n")
},
};
print_response_border("Response", &text);
}
let (input, output) = agent.get_token_counts();
println!();
println!("📊 Tokens: {} in, {} out", input, output);
}
Err(e) => {
eprintln!("❌ Error: {}", e);
}
}
} else {
// No message provided - start interactive mode
println!("Starting interactive chat session...");
println!("Note: For interactive chat, run 'matrixcode' without subcommand.");
}
}
Commands::Status => {
// Show system status (sync)
println!("MatrixCode Status:\n");
println!(" Version: {}", env!("CARGO_PKG_VERSION"));
println!(" Mode: Ready");
// Show configuration
if config.is_api_configured() {
println!(" API: ✓ configured");
} else {
println!(" API: ❌ not configured");
println!(" Set ANTHROPIC_AUTH_TOKEN or configure in ~/.matrix/config.json");
}
println!(" Model: {}", model_with_source(&config));
if let Some(base_url) = &config.base_url {
println!(" Base URL: {}", base_url);
} else if let Ok(url) = std::env::var("ANTHROPIC_BASE_URL") {
println!(" Base URL: {} (from env)", url);
}
// Show approve mode
if let Some(mode) = &config.approve_mode {
println!(" Approve Mode: {}", mode);
} else {
println!(" Approve Mode: ask (default)");
}
// Show sessions
if let Ok(mgr) = SessionManager::new() {
println!(" Sessions: {} (current: {})",
mgr.list_sessions().len(),
if mgr.has_current() { "yes" } else { "no" }
);
}
// Show memory
let project_path = std::env::current_dir().ok();
if let Some(path) = &project_path {
if let Ok(storage) = MemoryStorage::new(Some(path.as_path()))
&& let Ok(mem) = storage.load_combined() {
println!(" Memory: {} entries", mem.entries.len());
}
// Show project overview status
let overview_path = path.join(matrixcode_core::overview::OVERVIEW_FILENAME);
if overview_path.exists() {
if let Ok(metadata) = std::fs::metadata(&overview_path) {
let size = metadata.len();
if let Ok(modified) = metadata.modified() {
let modified_time: chrono::DateTime<chrono::Local> = modified.into();
println!(" Overview: ✓ MATRIX.md ({}, modified: {})",
if size > 1024 { format!("{} KB", size / 1024) } else { format!("{} bytes", size) },
modified_time.format("%Y-%m-%d %H:%M")
);
} else {
println!(" Overview: ✓ MATRIX.md ({})", size);
}
}
} else {
println!(" Overview: ❌ not found (use /init to generate)");
}
}
}
Commands::History => {
// Show session history (sync)
if let Ok(mgr) = SessionManager::new() {
let sessions = mgr.list_sessions();
if sessions.is_empty() {
println!("No session history found.");
} else {
println!("Session History:\n");
for session in sessions {
let project = session.project_path.as_deref().unwrap_or("unknown");
let is_current = mgr.has_current() && mgr.current_id() == Some(session.id.as_str());
println!("Session: {} ({})", session.short_id(), session.id);
println!(" Project: {}", project);
println!(" Created: {}", session.created_at.format("%Y-%m-%d %H:%M"));
println!(" Current: {}", if is_current { "yes" } else { "no" });
println!(" Messages: {}", session.message_count);
println!(" Tokens: {} in, {} out", session.last_input_tokens, session.total_output_tokens);
println!();
}
println!("Total: {} sessions", sessions.len());
println!("\nResume: matrixcode --resume <id>");
}
} else {
println!("Session manager not available.");
}
}
Commands::NewSession => {
// Create new session (sync)
println!("Creating new session...");
if let Ok(mut mgr) = SessionManager::new() {
let project_path = std::env::current_dir().ok();
if mgr.start_new(project_path.as_deref()).is_ok() {
println!("✓ New session created");
if let Some(id) = mgr.current_id() {
println!(" Session ID: {}", id);
}
println!("\nStart chatting with: matrixcode");
} else {
println!("❌ Failed to create new session");
}
} else {
println!("Session manager not available.");
}
}
Commands::QuickAction { action, file } => {
// Execute quick action
println!("⚡ Quick Action: {}", action);
if let Some(f) = &file {
println!(" Target: {}", f);
}
// Build prompt based on action type
let prompt = match action.as_str() {
"explain" => {
if let Some(f) = file {
format!("Please explain the code in {} in detail, including its purpose, structure, and key concepts.", f)
} else {
"Please explain the code in detail.".to_string()
}
}
"fix" => {
if let Some(f) = file {
format!("Please analyze {} for bugs or issues and fix them.", f)
} else {
"Please analyze the code for bugs or issues and fix them.".to_string()
}
}
"refactor" => {
if let Some(f) = file {
format!("Please refactor {} to improve its structure, readability, and maintainability.", f)
} else {
"Please refactor the code to improve its structure.".to_string()
}
}
"test" => {
if let Some(f) = file {
format!("Please write unit tests for the code in {}.", f)
} else {
"Please write unit tests for the code.".to_string()
}
}
"doc" | "document" => {
if let Some(f) = file {
format!("Please add documentation and comments to {}.", f)
} else {
"Please add documentation and comments to the code.".to_string()
}
}
"optimize" => {
if let Some(f) = file {
format!("Please optimize {} for performance and efficiency.", f)
} else {
"Please optimize the code for performance.".to_string()
}
}
"review" => {
if let Some(f) = file {
format!("Please review {} and provide feedback on code quality, potential issues, and improvements.", f)
} else {
"Please review the code and provide feedback.".to_string()
}
}
other => {
if let Some(f) = file {
format!("{}: {}", other, f)
} else {
other.to_string()
}
}
};
// Build system prompt with skills for quick action
let system_prompt = matrixcode_core::prompt::build_system_prompt(
&matrixcode_core::prompt::PromptProfile::Fast, // Fast profile for quick actions
skills,
None,
None,
);
// Create provider using factory
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to create provider: {}", e);
return;
}
};
// Build agent
let mut agent = AgentBuilder::new(provider)
.system_prompt(system_prompt)
.model_name(model.clone())
.max_tokens(4096)
.tools(all_tools_with_skills(Arc::new(skills.to_vec())))
.approve_mode(matrixcode_core::approval::ApproveMode::Auto) // Auto mode for quick actions
.build();
// Run agent
match agent.run(prompt).await {
Ok(_) => {
// Get all messages to show thinking first, then result
let messages = agent.get_messages();
// First, show thinking content if any
for msg in messages.iter() {
if msg.role == matrixcode_core::providers::Role::Assistant {
// Check if this is thinking content
let is_thinking = match &msg.content {
matrixcode_core::providers::MessageContent::Text(t) => {
t.contains("<thinking>") || t.starts_with("Let me") || t.starts_with("I need to")
},
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().any(|b| match b {
matrixcode_core::ContentBlock::Thinking { thinking, .. } => !thinking.is_empty(),
_ => false,
})
},
};
if is_thinking {
let text = match &msg.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().filter_map(|b| match b {
matrixcode_core::ContentBlock::Thinking { thinking, .. } => Some(thinking.as_str()),
matrixcode_core::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
}).collect::<Vec<_>>().join("\n")
},
};
print_thinking_border(&text);
}
}
}
// Then show the final assistant message
if let Some(last) = messages.last()
&& last.role == matrixcode_core::providers::Role::Assistant {
let text = match &last.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks.iter().filter_map(|b| match b {
matrixcode_core::ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
}).collect::<Vec<_>>().join("\n")
},
};
// Skip if this was the thinking message we already showed
print_response_border("Result", &text);
}
let (input, output) = agent.get_token_counts();
println!();
println!("📊 Tokens: {} in, {} out", input, output);
println!("✓ Action completed");
}
Err(e) => {
eprintln!("❌ Error: {}", e);
}
}
}
}
});
}
/// Service mode: pure JSON output
fn run_service_mode(cli: Cli) -> Result<()> {
// Load config for all commands
let config = Config::load();
match cli.command {
Some(Commands::Chat { message }) => {
// For chat command, we run the actual agent
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.ok_or_else(|| anyhow::anyhow!("No API key found"))?;
let model = resolve_model(&config);
let base_url = resolve_base_url(&config);
// Load skills
let skills_dirs: Vec<PathBuf> = cli.skills_dir.iter().cloned().collect();
let skills = load_skills(&skills_dirs);
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async {
// Output session started event
println!("{}", AgentEvent::session_started().to_json()?);
// Create event channel for agent
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(100);
let system_prompt = matrixcode_core::prompt::build_system_prompt(
&matrixcode_core::prompt::PromptProfile::Default,
&skills,
None,
None,
);
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
println!(
"{}",
AgentEvent::error(
format!("Failed to create provider: {}", e),
None,
None,
)
.to_json()?
);
return Ok::<_, anyhow::Error>(());
}
};
let mut agent = AgentBuilder::new(provider)
.system_prompt(system_prompt)
.model_name(model)
.max_tokens(4096)
.tools(all_tools_with_skills(Arc::new(skills.clone())))
.approve_mode(matrixcode_core::approval::ApproveMode::Auto)
.event_tx(event_tx)
.build();
// Run agent and collect events
let run_result = agent.run(message.unwrap_or_default()).await;
// Process events
while let Some(event) = event_rx.recv().await {
match event.event_type {
matrixcode_core::EventType::TextDelta => {
if let Some(_data) = &event.data {
println!("{}", event.to_json()?);
}
}
matrixcode_core::EventType::Error => {
println!("{}", event.to_json()?);
}
matrixcode_core::EventType::SessionEnded => {
break;
}
_ => {}
}
}
match run_result {
Ok(_) => {
let messages = agent.get_messages();
if let Some(last) = messages.last() {
let text = match &last.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks
.iter()
.filter_map(|b| match b {
matrixcode_core::ContentBlock::Text { text } => {
Some(text.as_str())
}
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
};
println!("{}", AgentEvent::text_delta(text).to_json()?);
}
}
Err(e) => {
println!(
"{}",
AgentEvent::error(format!("Agent error: {}", e), None, None)
.to_json()?
);
}
}
println!("{}", AgentEvent::session_ended().to_json()?);
Ok::<_, anyhow::Error>(())
})?;
}
Some(Commands::History) => {
// Output session history as JSON events
println!("{}", AgentEvent::session_started().to_json()?);
if let Ok(mgr) = SessionManager::new() {
let sessions = mgr.list_sessions();
if sessions.is_empty() {
let data = serde_json::json!({
"type": "history",
"sessions": [],
"message": "No sessions found"
});
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
)
.to_json()?
);
} else {
let sessions_json: Vec<serde_json::Value> = sessions.iter().map(|s| {
serde_json::json!({
"id": s.id,
"short_id": s.short_id(),
"project_path": s.project_path,
"created_at": s.created_at.to_rfc3339(),
"message_count": s.message_count,
"input_tokens": s.last_input_tokens,
"output_tokens": s.total_output_tokens,
"is_current": mgr.has_current() && mgr.current_id() == Some(s.id.as_str())
})
}).collect();
let data = serde_json::json!({
"type": "history",
"sessions": sessions_json,
"total": sessions.len()
});
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
)
.to_json()?
);
}
} else {
println!(
"{}",
AgentEvent::error("Session manager not available".to_string(), None, None)
.to_json()?
);
}
println!("{}", AgentEvent::session_ended().to_json()?);
}
Some(Commands::Status) => {
// Output system status as JSON events
println!("{}", AgentEvent::session_started().to_json()?);
let mut status = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"mode": "service",
"api_configured": config.is_api_configured(),
});
status["model"] = serde_json::json!(model_with_source(&config));
if let Some(base_url) = &config.base_url {
status["base_url"] = serde_json::json!(base_url);
}
if let Some(approve_mode) = &config.approve_mode {
status["approve_mode"] = serde_json::json!(approve_mode);
}
// Add session info
if let Ok(mgr) = SessionManager::new() {
status["sessions_count"] = serde_json::json!(mgr.list_sessions().len());
status["has_current_session"] = serde_json::json!(mgr.has_current());
}
// Add memory info
let project_path = std::env::current_dir().ok();
if let Some(path) = &project_path {
if let Ok(storage) = MemoryStorage::new(Some(path.as_path()))
&& let Ok(mem) = storage.load_combined()
{
status["memory_entries"] = serde_json::json!(mem.entries.len());
}
// Add overview status
let overview_path = path.join(matrixcode_core::overview::OVERVIEW_FILENAME);
status["has_overview"] = serde_json::json!(overview_path.exists());
}
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&status)?,
percentage: None,
},
)
.to_json()?
);
println!("{}", AgentEvent::session_ended().to_json()?);
}
Some(Commands::NewSession) => {
// Create new session
println!("{}", AgentEvent::session_started().to_json()?);
if let Ok(mut mgr) = SessionManager::new() {
let project_path = std::env::current_dir().ok();
match mgr.start_new(project_path.as_deref()) {
Ok(_) => {
let data = serde_json::json!({
"success": true,
"session_id": mgr.current_id(),
"message": "New session created"
});
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
)
.to_json()?
);
}
Err(e) => {
println!(
"{}",
AgentEvent::error(
format!("Failed to create session: {}", e),
None,
None
)
.to_json()?
);
}
}
} else {
println!(
"{}",
AgentEvent::error("Session manager not available".to_string(), None, None)
.to_json()?
);
}
println!("{}", AgentEvent::session_ended().to_json()?);
}
Some(Commands::QuickAction { action, file }) => {
// Execute quick action
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.ok_or_else(|| anyhow::anyhow!("No API key found"))?;
let model = resolve_model(&config);
let base_url = resolve_base_url(&config);
// Load skills
let skills_dirs: Vec<PathBuf> = cli.skills_dir.iter().cloned().collect();
let skills = load_skills(&skills_dirs);
// Build prompt based on action type
let prompt = match action.as_str() {
"explain" => {
if let Some(f) = &file {
format!(
"Please explain the code in {} in detail, including its purpose, structure, and key concepts.",
f
)
} else {
"Please explain the code in detail.".to_string()
}
}
"fix" => {
if let Some(f) = &file {
format!("Please analyze {} for bugs or issues and fix them.", f)
} else {
"Please analyze the code for bugs or issues and fix them.".to_string()
}
}
"refactor" => {
if let Some(f) = &file {
format!(
"Please refactor {} to improve its structure, readability, and maintainability.",
f
)
} else {
"Please refactor the code to improve its structure.".to_string()
}
}
"test" => {
if let Some(f) = &file {
format!("Please write unit tests for the code in {}.", f)
} else {
"Please write unit tests for the code.".to_string()
}
}
"doc" | "document" => {
if let Some(f) = &file {
format!("Please add documentation and comments to {}.", f)
} else {
"Please add documentation and comments to the code.".to_string()
}
}
"optimize" => {
if let Some(f) = &file {
format!("Please optimize {} for performance and efficiency.", f)
} else {
"Please optimize the code for performance.".to_string()
}
}
"review" => {
if let Some(f) = &file {
format!(
"Please review {} and provide feedback on code quality, potential issues, and improvements.",
f
)
} else {
"Please review the code and provide feedback.".to_string()
}
}
other => {
if let Some(f) = &file {
format!("{}: {}", other, f)
} else {
other.to_string()
}
}
};
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async {
println!("{}", AgentEvent::session_started().to_json()?);
// Output action start event
let action_data = serde_json::json!({
"action": action,
"file": file,
"status": "started"
});
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&action_data)?,
percentage: Some(0),
},
)
.to_json()?
);
let system_prompt = matrixcode_core::prompt::build_system_prompt(
&matrixcode_core::prompt::PromptProfile::Fast,
&skills,
None,
None,
);
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => {
println!(
"{}",
AgentEvent::error(
format!("Failed to create provider: {}", e),
None,
None,
)
.to_json()?
);
return Ok::<_, anyhow::Error>(());
}
};
let mut agent = AgentBuilder::new(provider)
.system_prompt(system_prompt)
.model_name(model)
.max_tokens(4096)
.tools(all_tools_with_skills(Arc::new(skills.clone())))
.approve_mode(matrixcode_core::approval::ApproveMode::Auto)
.build();
match agent.run(prompt).await {
Ok(_) => {
let messages = agent.get_messages();
if let Some(last) = messages.last() {
let text = match &last.content {
matrixcode_core::providers::MessageContent::Text(t) => t.clone(),
matrixcode_core::providers::MessageContent::Blocks(blocks) => {
blocks
.iter()
.filter_map(|b| match b {
matrixcode_core::ContentBlock::Text { text } => {
Some(text.as_str())
}
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
};
println!("{}", AgentEvent::text_delta(text).to_json()?);
}
let (input, output) = agent.get_token_counts();
let result_data = serde_json::json!({
"action": action,
"file": file,
"status": "completed",
"input_tokens": input,
"output_tokens": output
});
println!(
"{}",
AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&result_data)?,
percentage: Some(100),
},
)
.to_json()?
);
}
Err(e) => {
println!(
"{}",
AgentEvent::error(format!("Quick action failed: {}", e), None, None)
.to_json()?
);
}
}
println!("{}", AgentEvent::session_ended().to_json()?);
Ok::<_, anyhow::Error>(())
})?;
}
None => {
println!(
"{}",
AgentEvent::error("Please specify a command".to_string(), None, None).to_json()?
);
}
}
Ok(())
}
/// Daemon mode: listen on stdin, output to stdout
fn run_daemon_mode() -> Result<()> {
use std::io::{BufRead, Write};
eprintln!("MatrixCode Daemon started (listening on stdin)");
let stdin = std::io::stdin();
let stdout = std::io::stdout();
let mut stdout_lock = stdout.lock();
for line in stdin.lock().lines() {
let line = line?;
if line.is_empty() {
continue;
}
// Parse request
let request: DaemonRequest = match serde_json::from_str(&line) {
Ok(req) => req,
Err(e) => {
let error_event = AgentEvent::error(
format!("Invalid request: {}", e),
Some("parse_error".to_string()),
None,
);
writeln!(stdout_lock, "{}", error_event.to_json()?)?;
writeln!(stdout_lock, "---END---")?;
stdout_lock.flush()?;
continue;
}
};
// Handle request
let events = handle_daemon_request(request)?;
// Output events
for event in events {
writeln!(stdout_lock, "{}", event.to_json()?)?;
}
writeln!(stdout_lock, "---END---")?;
stdout_lock.flush()?;
}
Ok(())
}
/// Daemon request
#[derive(serde::Deserialize)]
struct DaemonRequest {
#[serde(rename = "type")]
request_type: String,
/// Content for chat messages
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<String>,
/// Action type for quick_action (explain, fix, refactor, test, doc, optimize, review)
#[serde(skip_serializing_if = "Option::is_none")]
action: Option<String>,
/// Target file for quick_action
#[serde(skip_serializing_if = "Option::is_none")]
file: Option<String>,
/// Session ID for load_session
#[serde(skip_serializing_if = "Option::is_none")]
session_id: Option<String>,
/// Model override
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
/// Max tokens override
#[serde(skip_serializing_if = "Option::is_none")]
max_tokens: Option<u32>,
}
/// Handle daemon request
fn handle_daemon_request(request: DaemonRequest) -> Result<Vec<AgentEvent>> {
let mut events = Vec::new();
let config = Config::load();
// Load skills for daemon mode
let skills = load_skills(&[]);
events.push(AgentEvent::session_started());
match request.request_type.as_str() {
"chat" => {
// Execute actual chat with agent
if let Some(content) = request.content {
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.ok_or_else(|| anyhow::anyhow!("No API key found"))?;
let model = resolve_model_with_override(request.model.clone(), &config);
let base_url = resolve_base_url(&config);
let max_tokens = request.max_tokens.unwrap_or(4096);
let rt = tokio::runtime::Runtime::new()?;
let result = rt.block_on(async {
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => return Err(e),
};
let mut agent = AgentBuilder::new(provider)
.model_name(model)
.max_tokens(max_tokens)
.tools(all_tools_with_skills(Arc::new(skills.clone())))
.approve_mode(matrixcode_core::approval::ApproveMode::Auto)
.build();
agent.run(content).await
});
match result {
Ok(_) => {
// For daemon mode, we can't easily capture all events,
// so we just return a completion event
events.push(AgentEvent::text_delta("Chat completed".to_string()));
}
Err(e) => {
events.push(AgentEvent::error(format!("Chat failed: {}", e), None, None));
}
}
} else {
events.push(AgentEvent::error(
"No content provided for chat",
None,
None,
));
}
}
"quick_action" => {
// Execute quick action
if let Some(action) = request.action.clone() {
let prompt = build_quick_action_prompt(&action, request.file.as_ref());
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var("ANTHROPIC_AUTH_TOKEN").ok())
.ok_or_else(|| anyhow::anyhow!("No API key found"))?;
let model = resolve_model_with_override(request.model.clone(), &config);
let base_url = resolve_base_url(&config);
events.push(AgentEvent::tool_use_start("action_1", action.clone(), None));
let rt = tokio::runtime::Runtime::new()?;
let result = rt.block_on(async {
let provider = match create_provider_with_headers(
resolve_provider(&config, &model),
api_key,
model.clone(),
Some(base_url),
config.extra_headers.clone(),
) {
Ok(p) => p,
Err(e) => return Err(e),
};
let mut agent = AgentBuilder::new(provider)
.model_name(model)
.max_tokens(4096)
.tools(all_tools_with_skills(Arc::new(skills.clone())))
.approve_mode(matrixcode_core::approval::ApproveMode::Auto)
.build();
agent.run(prompt).await
});
match result {
Ok(_) => {
events.push(AgentEvent::tool_result(
"action_1",
"action",
None,
"Action completed",
false,
));
}
Err(e) => {
events.push(AgentEvent::tool_result(
"action_1",
"action",
None,
format!("Error: {}", e),
true,
));
}
}
} else {
events.push(AgentEvent::error("No action specified", None, None));
}
}
"status" => {
// Return actual system status
let status = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"mode": "daemon",
"api_configured": config.is_api_configured(),
"model": model_with_source(&config),
});
events.push(AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&status)?,
percentage: None,
},
));
}
"history" => {
// Return session history
if let Ok(mgr) = SessionManager::new() {
let sessions = mgr.list_sessions();
let sessions_json: Vec<serde_json::Value> = sessions
.iter()
.map(|s| {
serde_json::json!({
"id": s.id,
"short_id": s.short_id(),
"project_path": s.project_path,
"created_at": s.created_at.to_rfc3339(),
"message_count": s.message_count,
})
})
.collect();
let data = serde_json::json!({
"type": "history",
"sessions": sessions_json,
"total": sessions.len()
});
events.push(AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
));
} else {
events.push(AgentEvent::error(
"Session manager not available",
None,
None,
));
}
}
"new_session" => {
// Create new session
if let Ok(mut mgr) = SessionManager::new() {
let project_path = std::env::current_dir().ok();
match mgr.start_new(project_path.as_deref()) {
Ok(_) => {
let data = serde_json::json!({
"success": true,
"session_id": mgr.current_id(),
"message": "New session created"
});
events.push(AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
));
}
Err(e) => {
events.push(AgentEvent::error(
format!("Failed to create session: {}", e),
None,
None,
));
}
}
} else {
events.push(AgentEvent::error(
"Session manager not available",
None,
None,
));
}
}
"load_session" => {
// Load/resume a session
if let Some(session_id) = request.session_id.clone() {
if let Ok(mut mgr) = SessionManager::new() {
let project_path = std::env::current_dir().ok();
match mgr.resume(&session_id, project_path.as_deref()) {
Ok(Some(session)) => {
let data = serde_json::json!({
"success": true,
"session_id": session.metadata.id,
"message_count": session.messages.len(),
"message": "Session loaded"
});
events.push(AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(&data)?,
percentage: None,
},
));
}
Ok(None) => {
events.push(AgentEvent::error(
format!("Session '{}' not found", session_id),
None,
None,
));
}
Err(e) => {
events.push(AgentEvent::error(
format!("Failed to load session: {}", e),
None,
None,
));
}
}
} else {
events.push(AgentEvent::error(
"Session manager not available",
None,
None,
));
}
} else {
events.push(AgentEvent::error("No session_id provided", None, None));
}
}
"list_sessions" => {
// List all sessions (alias for history)
if let Ok(mgr) = SessionManager::new() {
let sessions = mgr.list_sessions();
let sessions_json: Vec<serde_json::Value> = sessions
.iter()
.map(|s| {
serde_json::json!({
"id": s.id,
"short_id": s.short_id(),
"project": s.project_path.as_deref().unwrap_or("unknown"),
})
})
.collect();
events.push(AgentEvent::with_data(
matrixcode_core::EventType::Progress,
matrixcode_core::EventData::Progress {
message: serde_json::to_string(
&serde_json::json!({ "sessions": sessions_json }),
)?,
percentage: None,
},
));
} else {
events.push(AgentEvent::error(
"Session manager not available",
None,
None,
));
}
}
"ping" => {
// Simple ping/pong for health check
events.push(AgentEvent::text_delta("pong".to_string()));
}
_ => {
events.push(AgentEvent::error(
format!("Unknown request type: {}", request.request_type),
Some("unknown_type".to_string()),
None,
));
}
}
events.push(AgentEvent::session_ended());
Ok(events)
}
/// Build quick action prompt from action type and file
fn build_quick_action_prompt(action: &str, file: Option<&String>) -> String {
match action {
"explain" => {
if let Some(f) = file {
format!(
"Please explain the code in {} in detail, including its purpose, structure, and key concepts.",
f
)
} else {
"Please explain the code in detail.".to_string()
}
}
"fix" => {
if let Some(f) = file {
format!("Please analyze {} for bugs or issues and fix them.", f)
} else {
"Please analyze the code for bugs or issues and fix them.".to_string()
}
}
"refactor" => {
if let Some(f) = file {
format!(
"Please refactor {} to improve its structure, readability, and maintainability.",
f
)
} else {
"Please refactor the code to improve its structure.".to_string()
}
}
"test" => {
if let Some(f) = file {
format!("Please write unit tests for the code in {}.", f)
} else {
"Please write unit tests for the code.".to_string()
}
}
"doc" | "document" => {
if let Some(f) = file {
format!("Please add documentation and comments to {}.", f)
} else {
"Please add documentation and comments to the code.".to_string()
}
}
"optimize" => {
if let Some(f) = file {
format!("Please optimize {} for performance and efficiency.", f)
} else {
"Please optimize the code for performance.".to_string()
}
}
"review" => {
if let Some(f) = file {
format!(
"Please review {} and provide feedback on code quality, potential issues, and improvements.",
f
)
} else {
"Please review the code and provide feedback.".to_string()
}
}
other => {
if let Some(f) = file {
format!("{}: {}", other, f)
} else {
other.to_string()
}
}
}
}