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
//! `recursive` CLI: a thin shell around the kernel.
//!
//! Subcommands:
//! - `run <goal...>`: run the agent once with the given goal.
//! - `repl`: interactive loop, one goal per line.
//! - `tools`: print the registered tool specs as JSON.
mod cli;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use clap::{Parser, Subcommand};
use tokio::io::{AsyncBufReadExt, BufReader};
use tracing::Level;
use recursive::mcp::{JsonRpcRequest, JsonRpcResponse};
use recursive::SessionFile;
use recursive::SessionWriter;
use recursive::{
config::Config,
llm::{AnthropicProvider, LlmProvider, OpenAiProvider},
tools::{ScheduleWakeup, WakeupSlot},
AgentRuntimeBuilder, ChannelSink, CompositeSink, EventSink, FinishReason, NullSink,
PlanningMode, RetryPolicy, SessionPersistenceSink, ToolRegistry,
};
#[derive(Parser, Debug)]
#[command(
name = "recursive",
version,
about = "A minimal self-improving coding agent"
)]
struct Cli {
/// Workspace root the agent can read/write within.
#[arg(long, env = "RECURSIVE_WORKSPACE")]
workspace: Option<PathBuf>,
/// LLM model identifier (e.g., deepseek-chat, gpt-4o-mini, claude-sonnet-4-20250514).
#[arg(long, short = 'm')]
model: Option<String>,
/// API key for the LLM provider.
#[arg(long, short = 'k', hide_env_values = true)]
api_key: Option<String>,
/// Base URL for the LLM API endpoint.
#[arg(long)]
api_base: Option<String>,
/// LLM provider protocol type.
#[arg(long, value_parser = ["openai", "anthropic"])]
provider: Option<String>,
/// Maximum agent loop iterations per goal.
#[arg(long, env = "RECURSIVE_MAX_STEPS")]
max_steps: Option<usize>,
/// Stop when total transcript content reaches this many characters.
#[arg(long, env = "RECURSIVE_MAX_TRANSCRIPT_CHARS")]
max_transcript_chars: Option<usize>,
/// Path to a system prompt file (overrides default).
#[arg(long, env = "RECURSIVE_SYSTEM_PROMPT_FILE")]
system_prompt_file: Option<PathBuf>,
/// Path to MCP server config JSON file.
#[arg(long, env = "RECURSIVE_MCP_CONFIG")]
mcp_config: Option<PathBuf>,
/// Log level: error|warn|info|debug|trace.
#[arg(long, default_value = "info")]
log: String,
/// Persist the full transcript to <path> as JSON when the run finishes.
#[arg(long, env = "RECURSIVE_TRANSCRIPT_OUT")]
transcript_out: Option<PathBuf>,
/// Emit StepEvents as newline-delimited JSON on stdout instead of the
/// human-readable trace. Pipeable to jq or other downstream tooling.
#[arg(long, env = "RECURSIVE_JSON")]
json: bool,
/// Enable token-by-token streaming. Deltas are printed live on stderr.
#[arg(long, env = "RECURSIVE_STREAM")]
stream: bool,
/// Enable tool timing hook that prints tool call durations to stderr.
#[arg(long)]
hook_timing: bool,
/// Run in headless mode: interactive tools go through external hooks
/// instead of waiting for terminal input. If no hook approves the call,
/// the tool is auto-denied. Also set via RECURSIVE_HEADLESS=1.
#[arg(long = "headless", short = 'H', env = "RECURSIVE_HEADLESS")]
headless: bool,
/// Path to write a session file for non-success finishes (budget exceeded,
/// stuck, transcript limit). The session can be resumed later with `resume`.
#[arg(long, env = "RECURSIVE_SESSION_OUT")]
session_out: Option<PathBuf>,
/// Disable live session recording. By default every run is persisted
/// as JSONL under .recursive/sessions/<slug>/<session-id>/.
/// Set this flag (or RECURSIVE_NO_SESSION=1) to skip persistence.
#[arg(long = "no-session", env = "RECURSIVE_NO_SESSION")]
no_session: bool,
/// Continue the most recent conversation in the current workspace.
/// Equivalent to `recursive resume` without arguments (picks the latest session).
#[arg(short = 'c', long = "continue")]
continue_session: bool,
/// Display name for this session (shown in the /resume picker and sessions list).
#[arg(short = 'n', long = "name")]
name: Option<String>,
/// Reasoning effort level: low (no extended thinking), normal (default), high (max budget).
/// Currently effective for Anthropic models that support extended thinking.
#[arg(long = "effort", value_parser = ["low", "normal", "high"])]
effort: Option<String>,
/// Append text to the default system prompt instead of replacing it entirely.
/// Useful for adding per-run instructions without discarding built-in guidance.
#[arg(long = "append-system-prompt")]
append_system_prompt: Option<String>,
/// Permission mode for tool execution.
/// - default: prompt as configured (respect config.headless)
/// - plan: buffer all tool calls and present a plan before executing (like --plan-first)
/// - auto: approve all tool calls without prompting (headless, use in trusted envs)
#[arg(long = "permission-mode", value_parser = ["default", "plan", "auto"])]
permission_mode: Option<String>,
/// Enable plan-first mode: agent proposes a plan, user confirms before execution.
/// Equivalent to --permission-mode=plan. Kept for backward compatibility.
#[arg(long = "plan-first")]
plan_first: bool,
/// Start WeChat iLink daemon alongside the TUI (or in headless mode with `weixin-daemon`).
/// On first run, a QR code is displayed for login.
#[cfg(feature = "weixin")]
#[arg(long = "weixin", env = "RECURSIVE_WEIXIN")]
weixin: bool,
/// Override the iLink API base URL (e.g. when using an ilink-hub proxy).
#[cfg(feature = "weixin")]
#[arg(long = "weixin-base-url", env = "RECURSIVE_WEIXIN_BASE_URL")]
weixin_base_url: Option<String>,
/// Path to store WeChat bot credentials (default: ~/.recursive/<workspace>/weixin_creds.json).
#[cfg(feature = "weixin")]
#[arg(long = "weixin-cred-path")]
weixin_cred_path: Option<PathBuf>,
/// Path to external pricing YAML file. If provided, pricing from this file
/// takes precedence over hardcoded values. Models not in the file fall back
/// to hardcoded rates.
#[arg(long, env = "RECURSIVE_PRICING_FILE")]
pricing_file: Option<PathBuf>,
#[command(subcommand)]
cmd: Option<Cmd>,
/// Run a one-shot prompt (non-interactive). Like `recursive run` but shorter.
#[arg(short = 'p', long = "print")]
prompt: Option<String>,
}
#[derive(Subcommand, Debug)]
enum Cmd {
/// Run the agent once with the given goal (concatenated).
Run {
#[arg(trailing_var_arg = true, required = true)]
goal: Vec<String>,
},
/// Interactive multi-turn REPL (default when no command is given).
Repl,
/// Run as a headless WeChat daemon — no TUI, agent driven by WeChat messages.
#[cfg(feature = "weixin")]
WeixinDaemon,
/// Start as an MCP server (stdio transport).
Serve {
/// Workspace path for tool sandboxing.
#[arg(long, default_value = ".")]
workspace: PathBuf,
},
/// Start the HTTP API server.
#[cfg(feature = "http")]
Http {
/// Address to bind (e.g. 127.0.0.1:3000).
#[arg(long, default_value = "127.0.0.1:3000")]
addr: String,
},
/// Interactive setup wizard — configure provider, model, and API key.
/// Non-interactive: pass all three of `--provider` / `--model` / `--api-key`
/// to skip the prompts and write the config directly. With only some set,
/// the missing fields are still prompted for.
Init {
/// Provider preset id from providers.toml (e.g. "deepseek", "anthropic").
/// Writes `provider.preset` to the config so the runtime can resolve
/// api_base / model / type from the catalog.
#[arg(long)]
provider: Option<String>,
/// Model name. Defaults to the preset's `default_model`.
#[arg(long, short = 'm')]
model: Option<String>,
/// API key. If omitted, falls back to the preset's `key_env` env var,
/// then prompts.
#[arg(long, short = 'k', hide_env_values = true)]
api_key: Option<String>,
},
/// Print registered tool specs as JSON (sanity check).
Tools,
/// Pretty-print a previously saved transcript JSON file, or resume a
/// run from a saved transcript when `--resume-from N <goal>` is given.
Replay {
/// Path to the transcript JSON file (as written by --transcript-out).
path: PathBuf,
/// Take the first N messages of the saved transcript as seed
/// context for a new run. Requires a trailing <goal>.
#[arg(long)]
resume_from: Option<usize>,
/// Goal for the resumed run. Required when --resume-from is given;
/// ignored otherwise.
#[arg(trailing_var_arg = true)]
goal: Vec<String>,
/// Print only the last N messages of the transcript.
/// Ignored when --resume-from is given.
#[arg(long)]
tail: Option<usize>,
/// Print only the first N messages of the transcript.
/// Mutually exclusive with --tail. Ignored when --resume-from is given.
#[arg(long)]
head: Option<usize>,
},
/// Resume a run from a saved session.
///
/// **Goal 151**: prefer specifying a session ID (or substring)
/// recorded under `~/.recursive/.../sessions/`. Without an
/// argument, the most-recent active or interrupted session in
/// the current workspace is resumed.
Resume {
/// Session ID or unique substring. If omitted, resumes the
/// most-recent active/interrupted session in this workspace.
session: Option<String>,
/// Escape hatch: resume from an explicit JSONL session
/// directory path (not a legacy `.json` file). Mutually
/// exclusive with the positional argument.
#[arg(long, conflicts_with = "session")]
from_file: Option<PathBuf>,
/// How to handle orphan tool calls detected on resume
/// (tool_calls in the last assistant message with no matching
/// tool result). Choices: ask (default on TTY), skip, redo, abort.
/// On non-TTY (CI) the default is abort.
#[arg(long, value_name = "POLICY")]
orphans: Option<String>,
},
/// List or inspect saved sessions.
Sessions {
#[command(subcommand)]
cmd: SessionCmd,
},
/// View or modify configuration.
Config {
#[command(subcommand)]
cmd: ConfigCmd,
},
/// Run the agent in loop mode: agent self-schedules wakeups until it stops.
Loop {
/// Initial goal to start the loop with.
#[arg(trailing_var_arg = true, required = true)]
goal: Vec<String>,
},
/// Migrate legacy in-tree state (sessions, shadow-git, scratchpad)
/// from `<workspace>/.recursive/` to the per-user data dir at
/// `~/.recursive/workspaces/<hash>/`.
Migrate {
/// Show what would be moved without changing anything.
#[arg(long)]
dry_run: bool,
},
}
#[derive(Subcommand, Debug)]
enum SessionCmd {
/// List all session files in the workspace's session directory.
List,
/// Show details of a specific session (by path or session ID).
Show {
/// Path to the session JSON file, or a session ID to search for.
session: String,
},
/// Delete a session file or session directory.
Delete {
/// Path to the session JSON file, or a session ID to search for.
session: String,
/// Skip confirmation prompt.
#[arg(long, short = 'f')]
force: bool,
},
/// Export a session as portable JSON.
Export {
/// Session directory path or session ID.
session: String,
/// Output file (default: stdout).
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Rewind a session to the start of turn N, restoring only files
/// this session touched in turns >= N. Sibling sessions' files are
/// untouched. Conflicts (a touched file modified externally since
/// our last snapshot) abort unless --force is given.
Rewind {
/// Session directory path or session ID.
session: String,
/// Turn index to rewind to. The start state of this turn is
/// what gets restored; the turn itself and all later turns
/// are dropped.
#[arg(long)]
to_turn: usize,
/// Skip conflict detection and overwrite externally-modified files.
#[arg(long)]
force: bool,
/// Print the plan but don't apply it.
#[arg(long)]
dry_run: bool,
},
/// Convert a legacy `.json` session file (written by
/// `--session-out`) into the JSONL session directory format
/// so it can be resumed by ID. One-shot migration utility.
MigrateLegacy {
/// Path to the legacy `.json` session file.
path: PathBuf,
},
}
#[derive(Subcommand, Debug)]
enum ConfigCmd {
/// Display the effective configuration (API keys are masked).
Show,
/// Set a config value in ~/.recursive/config.toml.
Set {
/// Config key (e.g., provider.model, agent.max_steps).
key: String,
/// Value to set.
value: String,
},
/// Print the config file path.
Path,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
init_logging(&cli.log)?;
if cli.session_out.is_some() {
eprintln!(
"warning: --session-out writes the legacy .json format, which is no longer\n\
used for resume. Your session is automatically being persisted as JSONL\n\
under the user data dir; use `recursive resume <id>` to resume.\n\
This flag will be removed in a future release."
);
}
let mut config = Config::from_env().context("loading config")?;
if let Some(ws) = cli.workspace {
config.workspace = ws;
}
if let Some(n) = cli.max_steps {
config.max_steps = n;
}
if let Some(m) = cli.model {
config.model = m;
}
if let Some(k) = cli.api_key {
config.api_key = Some(k);
}
if let Some(b) = cli.api_base {
config.api_base = b;
}
if let Some(p) = cli.provider {
config.provider_type = p;
}
if cli.headless {
config.headless = true;
}
if let Some(p) = cli.system_prompt_file {
config.system_prompt = std::fs::read_to_string(&p)
.with_context(|| format!("reading system prompt: {}", p.display()))?;
}
// --append-system-prompt: tack additional text onto whatever system prompt is active.
if let Some(extra) = &cli.append_system_prompt {
config.system_prompt.push('\n');
config.system_prompt.push_str(extra);
}
// --permission-mode / --plan-first: resolve to the canonical plan_first bool.
let effective_plan_first =
cli.plan_first || matches!(cli.permission_mode.as_deref(), Some("plan"));
if matches!(cli.permission_mode.as_deref(), Some("auto")) {
config.headless = true;
}
// --effort: map to thinking_budget (low=0 disables, normal=default, high=max).
if let Some(effort) = &cli.effort {
config.thinking_budget = match effort.as_str() {
"low" => Some(0),
"high" => Some(16000),
_ => None, // "normal" → leave as default
};
}
// --name: optional display name for the session.
if let Some(name) = cli.name {
config.session_name = Some(name);
}
// Determine effective command:
// - Explicit subcommand → use it
// - `-c/--continue` → resume the latest session (like `recursive resume`)
// - `-p "goal"` → one-shot run (like `claude -p`)
// - Nothing → TUI (if compiled in), else REPL
let effective_cmd = match cli.cmd {
Some(cmd) => cmd,
None => {
if cli.continue_session {
Cmd::Resume {
session: None,
from_file: None,
orphans: None,
}
} else if let Some(prompt) = cli.prompt {
Cmd::Run { goal: vec![prompt] }
} else {
#[cfg(all(feature = "tui", feature = "weixin"))]
if cli.weixin {
return run_tui_with_weixin(
cli.weixin_base_url.clone(),
cli.weixin_cred_path.clone(),
config.workspace.clone(),
)
.await;
}
#[cfg(feature = "tui")]
{
return recursive::tui::run().await.map_err(Into::into);
}
#[cfg(not(feature = "tui"))]
Cmd::Repl
}
}
};
// Warn about legacy in-tree state for commands that interact with
// the workspace. The Migrate command itself shouldn't double-warn.
if !matches!(effective_cmd, Cmd::Migrate { .. }) {
let legacy = recursive::legacy_paths_in_workspace(&config.workspace);
if !legacy.is_empty() {
eprintln!(
"warning: legacy in-tree state detected at {}/.recursive/:",
config.workspace.display()
);
for p in &legacy {
eprintln!(" {}", p.display());
}
eprintln!("hint: run `recursive migrate` to move it under ~/.recursive");
}
}
match effective_cmd {
#[cfg(feature = "weixin")]
Cmd::WeixinDaemon => {
return run_weixin_headless_daemon(
config,
cli.mcp_config,
cli.weixin_base_url,
cli.weixin_cred_path,
)
.await;
}
Cmd::Tools => {
let tools = cli::builder::build_tools(&config).await;
let specs = tools.specs();
println!("{}", serde_json::to_string_pretty(&specs)?);
Ok(())
}
Cmd::Serve { workspace } => {
let workspace = std::fs::canonicalize(&workspace)?;
config.workspace = workspace;
run_mcp_server_stdio(config, cli.mcp_config).await
}
#[cfg(feature = "http")]
Cmd::Http { addr } => {
if let Err(msg) = config.validate_for_agent() {
eprintln!("{msg}");
std::process::exit(1);
}
let tools = cli::builder::build_tools(&config).await;
let tool_infos: Vec<recursive::http::ToolInfo> = tools
.specs()
.into_iter()
.map(|spec| recursive::http::ToolInfo {
name: spec.name,
description: spec.description,
parameters: spec.parameters,
})
.collect();
// Build the LLM provider from config
let api_key = config.require_api_key()?;
let retry = RetryPolicy {
max_retries: config.retry_max,
initial_backoff: Duration::from_secs(config.retry_initial_backoff_secs),
max_backoff: Duration::from_secs(config.retry_max_backoff_secs),
};
let provider: Arc<dyn recursive::llm::LlmProvider> = match config.provider_type.as_str()
{
"anthropic" => {
let anthropic_retry = recursive::llm::RetryPolicy {
max_retries: config.retry_max,
initial_backoff: Duration::from_secs(config.retry_initial_backoff_secs),
max_backoff: Duration::from_secs(config.retry_max_backoff_secs),
};
let anthropic =
AnthropicProvider::new(&config.api_base, api_key, &config.model)
.with_temperature(config.temperature)
.with_retry_policy(anthropic_retry);
Arc::new(anthropic)
}
_ => {
let openai = OpenAiProvider::new(&config.api_base, api_key, &config.model)
.with_temperature(config.temperature)
.with_retry_policy(retry);
Arc::new(openai)
}
};
// Goal-169: build the slash command list from built-in TUI commands +
// workspace skill files. Guarded by the `tui` feature since
// CommandRegistry lives in the tui module.
#[cfg(feature = "tui")]
let slash_commands: Vec<recursive::http::SlashCommandInfo> = {
let registry = recursive::tui::commands::CommandRegistry::default_set();
let mut cmds: Vec<recursive::http::SlashCommandInfo> = registry
.commands()
.iter()
.map(|c| recursive::http::SlashCommandInfo {
name: c.name.to_string(),
description: c.summary.to_string(),
source: "builtin".to_string(),
aliases: c.aliases.iter().map(|a| a.to_string()).collect(),
argument_hint: String::new(),
})
.collect();
let workspace = std::env::current_dir().unwrap_or_default();
let skills = recursive::tui::skill_commands::SkillCommandLoader::load(&workspace);
for skill in skills {
cmds.push(recursive::http::SlashCommandInfo {
name: skill.name.clone(),
description: skill.description.clone(),
source: "skill".to_string(),
aliases: skill.aliases.clone(),
argument_hint: skill.argument_hint.clone(),
});
}
cmds
};
#[cfg(not(feature = "tui"))]
let slash_commands: Vec<recursive::http::SlashCommandInfo> = Vec::new();
let state = recursive::http::AppState {
tools: tool_infos,
tool_registry: tools,
config: config.clone(),
provider,
sessions: std::sync::Arc::new(tokio::sync::RwLock::new(
std::collections::HashMap::new(),
)),
event_channels: std::sync::Arc::new(tokio::sync::RwLock::new(
std::collections::HashMap::new(),
)),
metrics: std::sync::Arc::new(recursive::http::Metrics::default()),
slash_commands: std::sync::Arc::new(slash_commands),
};
let router = recursive::http::build_router(state);
let listener = tokio::net::TcpListener::bind(&addr).await?;
eprintln!("Recursive HTTP API listening on {addr}");
let shutdown = shutdown_signal();
axum::serve(listener, router)
.with_graceful_shutdown(async move { shutdown.cancelled().await })
.await?;
eprintln!("shutdown: HTTP server stopped gracefully");
Ok(())
}
Cmd::Init {
provider,
model,
api_key,
} => cli::init::run_init(provider, model, api_key).await,
Cmd::Run { goal } => {
let shutdown = shutdown_signal();
run_once(
config,
goal.join(" "),
cli.max_transcript_chars,
cli.transcript_out,
cli.session_out,
cli.json,
cli.stream,
effective_plan_first,
cli.mcp_config,
cli.hook_timing,
!cli.no_session,
shutdown,
)
.await
}
Cmd::Repl => {
repl(
config,
cli.max_transcript_chars,
cli.json,
effective_plan_first,
cli.mcp_config,
cli.stream,
cli.hook_timing,
)
.await
}
Cmd::Loop { goal } => {
let shutdown = shutdown_signal();
run_loop(
config,
goal.join(" "),
cli.max_transcript_chars,
cli.json,
cli.stream,
effective_plan_first,
cli.mcp_config,
cli.hook_timing,
shutdown,
)
.await
}
Cmd::Replay {
path,
resume_from,
goal,
tail,
head,
} => {
// Check mutual exclusivity of --head and --tail
if tail.is_some() && head.is_some() {
anyhow::bail!("--head and --tail are mutually exclusive");
}
let file = recursive::TranscriptFile::read_from(&path)?;
match resume_from {
None => {
// If --head is provided, use pretty_head
if let Some(n) = head {
print!("{}", file.pretty_head(n));
// If --tail is provided without --resume-from, use pretty_tail
} else if let Some(n) = tail {
print!("{}", file.pretty_tail(n));
} else {
print!("{}", file.pretty());
}
Ok(())
}
Some(_) if goal.is_empty() => {
anyhow::bail!("--resume-from requires a trailing <goal> to continue the run");
}
Some(n) => {
let seed = file.take_first_n(n).ok_or_else(|| {
anyhow::anyhow!(
"--resume_from {n} exceeds saved transcript length ({})",
file.messages().len()
)
})?;
let shutdown = shutdown_signal();
cli::resume::run_resumed(
config,
seed.to_vec(),
goal.join(" "),
cli.max_transcript_chars,
cli.transcript_out,
cli.session_out,
cli.json,
effective_plan_first,
cli.mcp_config,
cli.hook_timing,
!cli.no_session,
shutdown,
None, // existing_writer — legacy --resume-from creates a fresh session
)
.await
}
}
}
Cmd::Resume {
session,
from_file,
orphans,
} => {
cli::resume::cmd_resume(
config,
session,
from_file,
orphans,
cli.max_transcript_chars,
cli.transcript_out,
cli.session_out,
cli.json,
effective_plan_first,
cli.mcp_config,
cli.hook_timing,
!cli.no_session,
)
.await
}
Cmd::Sessions { cmd } => match cmd {
SessionCmd::List => {
let old_sessions = recursive::session::list_sessions(&config.workspace)?;
let new_sessions =
recursive::session::SessionReader::list_sessions(&config.workspace)?;
let total = old_sessions.len() + new_sessions.len();
if total == 0 {
let sessions_root = recursive::user_sessions_dir(&config.workspace)
.unwrap_or_else(|_| config.workspace.join(".recursive").join("sessions"));
println!("No sessions found in {}", sessions_root.display());
} else {
println!("Sessions ({}):", total);
for s in &old_sessions {
println!(" {} (old format)", s.display());
}
for s in &new_sessions {
// g157: show last_prompt / goal from meta so the user can
// identify sessions without reading the full transcript.
if let Ok(meta) = recursive::session::SessionReader::load_meta(s) {
let label = meta
.last_prompt
.as_deref()
.or(Some(meta.goal.as_str()))
.unwrap_or("(no prompt)");
let name_suffix = meta
.name
.as_deref()
.map(|n| format!(" «{n}»"))
.unwrap_or_default();
println!(
" {} [{}]{} {}",
s.display(),
meta.status,
name_suffix,
label
);
} else {
println!(" {} (JSONL)", s.display());
}
}
}
Ok(())
}
SessionCmd::Show { session } => {
let path = cli::session::resolve_session_path(&config.workspace, &session)?;
if path.is_dir() {
// New JSONL session format (directory with transcript.jsonl + .meta.json)
let meta = recursive::session::SessionReader::load_meta(&path)
.with_context(|| format!("reading session meta: {}", path.display()))?;
let entries = recursive::session::SessionReader::load_transcript(&path)
.with_context(|| {
format!("reading session transcript: {}", path.display())
})?;
println!("Session: {}", path.display());
println!(" session_id: {}", meta.session_id);
println!(" goal: {}", meta.goal);
println!(" model: {}", meta.model);
println!(" provider: {}", meta.provider);
if let Some(preset) = meta.preset.as_deref() {
println!(" preset: {preset}");
}
println!(" created_at: {}", meta.created_at);
println!(" updated_at: {}", meta.updated_at);
println!(" message_count: {}", meta.message_count);
println!(" status: {}", meta.status);
println!();
println!("Transcript ({} entries):", entries.len());
for (i, entry) in entries.iter().enumerate() {
let preview: String = entry.content.chars().take(200).collect();
let truncated = if entry.content.len() > 200 { "…" } else { "" };
println!(" [{:>3}] {:>9}: {}{}", i, entry.role, preview, truncated);
if !entry.tool_calls.is_empty() {
for tc in &entry.tool_calls {
println!(" tool_call: {} ({})", tc.name, tc.id);
}
}
if let Some(ref rc) = entry.reasoning_content {
let rp: String = rc.chars().take(100).collect();
let rt = if rc.len() > 100 { "…" } else { "" };
println!(" reasoning: {}{}", rp, rt);
}
}
Ok(())
} else {
// Old single-file session format (.json)
let file = SessionFile::read_from(&path)
.with_context(|| format!("reading session: {}", path.display()))?;
println!("Session: {}", path.display());
println!(" schema_version: {}", file.schema_version);
println!(" goal: {}", file.goal);
println!(" model: {}", file.model);
println!(" provider: {}", file.provider);
println!(" tool_registry: {}", file.tool_registry_hash);
println!(" steps_consumed: {}", file.steps_consumed);
println!(" transcript_len: {}", file.transcript.len());
println!();
println!("Transcript:");
for (i, msg) in file.transcript.iter().enumerate() {
let role = match msg.role {
recursive::Role::System => "system",
recursive::Role::User => "user",
recursive::Role::Assistant => "assistant",
recursive::Role::Tool => "tool",
};
let preview: String = msg.content.chars().take(200).collect();
let truncated = if msg.content.len() > 200 { "…" } else { "" };
println!(" [{:>3}] {:>9}: {}{}", i, role, preview, truncated);
if !msg.tool_calls.is_empty() {
for tc in &msg.tool_calls {
println!(" tool_call: {} ({})", tc.name, tc.id);
}
}
}
Ok(())
}
}
SessionCmd::Delete { session, force } => {
let path = cli::session::resolve_session_path(&config.workspace, &session)?;
if !force {
eprint!("Delete session '{}'? [y/N] ", path.display());
use std::io::Write;
std::io::stderr().flush()?;
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let input = input.trim().to_lowercase();
if input != "y" && input != "yes" {
println!("Aborted.");
return Ok(());
}
}
if path.is_dir() {
std::fs::remove_dir_all(&path).with_context(|| {
format!("removing session directory: {}", path.display())
})?;
println!("Deleted session directory: {}", path.display());
} else if path.is_file() {
std::fs::remove_file(&path)
.with_context(|| format!("removing session file: {}", path.display()))?;
println!("Deleted session file: {}", path.display());
} else {
anyhow::bail!("Path does not exist: {}", path.display());
}
Ok(())
}
SessionCmd::Export { session, output } => {
let path = cli::session::resolve_session_path(&config.workspace, &session)?;
let exported = recursive::session::ExportedTranscript::from_session_dir(&path)?;
let json = serde_json::to_string_pretty(&exported)?;
if let Some(out) = output {
std::fs::write(&out, &json)?;
println!("Exported to {}", out.display());
} else {
println!("{}", json);
}
Ok(())
}
SessionCmd::Rewind {
session,
to_turn,
force,
dry_run,
} => cli::session::cmd_session_rewind(
&config.workspace,
&session,
to_turn,
force,
dry_run,
),
SessionCmd::MigrateLegacy { path } => {
cli::session::cmd_session_migrate_legacy(&config.workspace, &path)
}
},
Cmd::Config { cmd } => match cmd {
ConfigCmd::Show => {
println!("# Effective configuration (env > config file > default)");
println!("provider_type: {}", config.provider_type);
println!("model: {}", config.model);
println!("api_base: {}", config.api_base);
println!("api_key: {}", mask_key(config.api_key.as_deref()));
// Preset resolution: `provider.preset` from the file wins; if
// absent, fall back to a catalog match against the resolved
// api_base. Surfaces the preset chain added by the
// preset-config goal — without it, a user with
// `preset = "deepseek"` would only see the raw fields and
// have to manually re-derive that they're on DeepSeek.
let preset_label = config
.preset
.clone()
.or_else(|| {
recursive::providers::find_preset_by_api_base(&config.api_base)
.map(|p| p.id.to_string())
})
.unwrap_or_else(|| "(none)".to_string());
println!("preset: {preset_label}");
if let Some(preset) = config
.preset
.as_deref()
.and_then(recursive::providers::find_preset)
.or_else(|| recursive::providers::find_preset_by_api_base(&config.api_base))
{
let key_env = if preset.key_env.is_empty() {
"(none)".to_string()
} else {
preset.key_env.clone()
};
println!(
"preset resolves to: type={}, model={}, key_env={key_env}",
preset.provider_type, preset.default_model
);
}
println!("workspace: {}", config.workspace.display());
println!("max_steps: {}", config.max_steps);
println!("temperature: {}", config.temperature);
println!("shell_timeout: {}s", config.shell_timeout_secs);
if let Some(path) = recursive::config_file::config_file_path() {
println!(
"\nconfig file: {} {}",
path.display(),
if path.exists() {
"(exists)"
} else {
"(not found)"
}
);
}
Ok(())
}
ConfigCmd::Set { key, value } => {
recursive::config_file::set_value(&key, &value)?;
if let Some(path) = recursive::config_file::config_file_path() {
println!("Set {} = {} in {}", key, value, path.display());
}
Ok(())
}
ConfigCmd::Path => {
match recursive::config_file::config_file_path() {
Some(p) => println!("{}", p.display()),
None => anyhow::bail!("could not determine home directory"),
}
Ok(())
}
},
Cmd::Migrate { dry_run } => cli::session::cmd_migrate(&config.workspace, dry_run),
}
}
/// Returns a [`CancellationToken`] that fires on SIGINT (Ctrl+C) or SIGTERM.
fn shutdown_signal() -> tokio_util::sync::CancellationToken {
let token = tokio_util::sync::CancellationToken::new();
let t = token.clone();
tokio::spawn(async move {
let ctrl_c = tokio::signal::ctrl_c();
#[cfg(unix)]
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to register SIGTERM handler");
#[cfg(unix)]
tokio::select! {
_ = ctrl_c => {},
_ = sigterm.recv() => {},
}
#[cfg(not(unix))]
ctrl_c.await.unwrap();
t.cancel();
});
token
}
fn mask_key(key: Option<&str>) -> String {
match key {
None => "(not set)".to_string(),
Some(k) if k.len() <= 8 => "****".to_string(),
Some(k) => format!("{}...{}", &k[..4], &k[k.len() - 4..]),
}
}
fn init_logging(level: &str) -> anyhow::Result<()> {
let lvl: Level = level.parse().context("invalid log level")?;
let trace_spans = std::env::var("RECURSIVE_TRACE_SPANS").as_deref() == Ok("1");
// When span timings are requested, the user-provided `--log warn`
// would suppress the close events (they fire at INFO). Layer an
// info-level filter for the `recursive` crate's instrumented spans
// while leaving the rest of the filter alone.
let filter = tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
let base = lvl.to_string();
if trace_spans {
tracing_subscriber::EnvFilter::new(format!("{base},recursive=info"))
} else {
tracing_subscriber::EnvFilter::new(base)
}
});
let mut layer = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(false)
.with_writer(recursive::logging::StderrOrNullMaker)
.compact();
if trace_spans {
layer = layer.with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
}
layer.init();
Ok(())
}
/// Run the agent in loop mode: agent self-schedules wakeups until it stops.
#[allow(clippy::too_many_arguments)]
async fn run_loop(
config: Config,
goal: String,
max_transcript_chars: Option<usize>,
json_mode: bool,
stream: bool,
plan_first: bool,
mcp_config: Option<PathBuf>,
hook_timing: bool,
shutdown: tokio_util::sync::CancellationToken,
) -> anyhow::Result<()> {
use std::sync::Mutex;
if let Err(msg) = config.validate_for_agent() {
eprintln!("{msg}");
std::process::exit(1);
}
let wakeup_slot: WakeupSlot = Arc::new(Mutex::new(None));
// Build tools with ScheduleWakeup registered; must happen before build_runtime
// so the slot is shared between the tool and the runtime loop.
let mut tools = cli::builder::build_tools(&config).await;
cli::builder::register_mcp_tools(&mut tools, &config.workspace, mcp_config).await;
tools.register_mut(Arc::new(ScheduleWakeup::new(wakeup_slot.clone())));
// Build LLM provider
let api_key = config.require_api_key()?;
let retry = RetryPolicy {
max_retries: config.retry_max,
initial_backoff: Duration::from_secs(config.retry_initial_backoff_secs),
max_backoff: Duration::from_secs(config.retry_max_backoff_secs),
};
let provider: Arc<dyn LlmProvider> = match config.provider_type.as_str() {
"anthropic" => {
let anthropic_retry = recursive::llm::RetryPolicy {
max_retries: config.retry_max,
initial_backoff: Duration::from_secs(config.retry_initial_backoff_secs),
max_backoff: Duration::from_secs(config.retry_max_backoff_secs),
};
let anthropic = AnthropicProvider::new(&config.api_base, api_key, &config.model)
.with_temperature(config.temperature)
.with_retry_policy(anthropic_retry);
Arc::new(anthropic)
}
_ => {
let openai = OpenAiProvider::new(&config.api_base, api_key, &config.model)
.with_temperature(config.temperature)
.with_retry_policy(retry);
Arc::new(openai)
}
};
let mut builder = AgentRuntimeBuilder::new()
.llm(provider)
.tools(tools)
.system_prompt(&config.system_prompt)
.max_steps(config.max_steps)
.streaming(stream)
.shutdown_token(shutdown.clone());
if let Some(n) = max_transcript_chars {
builder = builder.max_transcript_chars(n);
}
if hook_timing {
use recursive::hooks::HookRegistry;
let mut hooks = HookRegistry::new();
hooks.register(Arc::new(recursive::hooks::ToolTimingHook::new()));
builder = builder.hooks(hooks);
}
if plan_first {
builder = builder.planning_mode(PlanningMode::PlanFirst);
}
let mut runtime = builder.build().map_err(Into::<anyhow::Error>::into)?;
let outcomes = runtime.run_loop(&goal, &wakeup_slot).await?;
// Cancellation now reflected in each outcome's finish_reason
// (FinishReason::Cancelled). Historical `if shutdown.is_cancelled()`
// print here was redundant once g137 wired the token through.
let _ = &shutdown;
if json_mode {
let summary: Vec<_> = outcomes
.iter()
.map(|o| {
serde_json::json!({
"finish": format!("{:?}", o.finish_reason),
"steps": o.steps,
})
})
.collect();
println!("{}", serde_json::to_string(&summary)?);
} else {
eprintln!("Loop completed: {} turn(s)", outcomes.len());
}
if let Some(last) = outcomes.last() {
let _ = cli::output::exit_for_finish(&last.finish_reason, last.steps);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn run_once(
config: Config,
goal: String,
max_transcript_chars: Option<usize>,
transcript_out: Option<PathBuf>,
session_out: Option<PathBuf>,
json_mode: bool,
stream: bool,
plan_first: bool,
mcp_config: Option<PathBuf>,
hook_timing: bool,
session: bool,
shutdown: tokio_util::sync::CancellationToken,
) -> anyhow::Result<()> {
if let Err(msg) = config.validate_for_agent() {
eprintln!("{msg}");
std::process::exit(1);
}
let session_writer: Option<Arc<std::sync::Mutex<SessionWriter>>> = if session {
match SessionWriter::create_with_tools(
&config.workspace,
&goal,
&config.model,
&config.provider_type,
&[],
config.preset.as_deref(),
) {
Ok(mut writer) => {
if let Some(ref name) = config.session_name {
writer.set_name(name.as_str());
}
eprintln!("session: recording to {}", writer.session_dir().display());
Some(Arc::new(std::sync::Mutex::new(writer)))
}
Err(e) => {
eprintln!("session: failed to create session writer: {e}");
None
}
}
} else {
None
};
let cost_tracker: Option<std::sync::Mutex<recursive::cost::CostTracker>> = if session {
session_writer.as_ref().map(|w| {
let session_dir = w.lock().unwrap().session_dir().to_path_buf();
std::sync::Mutex::new(recursive::cost::CostTracker::new(
session_dir,
&config.model,
&config.provider_type,
))
})
} else {
None
};
let (channel_sink, event_rx) = ChannelSink::new();
let event_sink: Arc<dyn EventSink> = if let Some(ref sw) = session_writer {
Arc::new(CompositeSink::new(vec![
Box::new(channel_sink) as Box<dyn EventSink>,
Box::new(SessionPersistenceSink::new(sw.clone())) as Box<dyn EventSink>,
]))
} else {
Arc::new(channel_sink)
};
let mut runtime = cli::builder::build_runtime(
&config,
max_transcript_chars,
Vec::new(),
stream,
plan_first,
mcp_config,
hook_timing,
Some(&goal),
Some(event_sink),
Some(shutdown.clone()),
)
.await?;
// Wire up per-turn checkpoints when a session is active and git is
// available. The shadow repo is shared across all sessions in this
// workspace; each session advances its own ref chain.
if let Some(ref sw) = session_writer {
match recursive::ShadowRepo::open(&config.workspace) {
Ok(repo) => {
let session_id = sw.lock().unwrap().session_id().to_string();
let session_dir = sw.lock().unwrap().session_dir().to_path_buf();
let log_path = session_dir.join("checkpoints.jsonl");
let touched = runtime.kernel().tools().touched_files();
if let Err(e) =
runtime.enable_checkpoints(Arc::new(repo), session_id, log_path, touched)
{
eprintln!("checkpoint: failed to enable, continuing without: {e}");
} else {
eprintln!("checkpoint: per-turn snapshots active");
}
}
Err(e) => {
eprintln!("checkpoint: shadow repo unavailable, continuing without: {e}");
}
}
}
let tool_specs = runtime.kernel().tools().specs();
let printer = if json_mode {
tokio::spawn(cli::output::stream_events_json(event_rx))
} else {
tokio::spawn(cli::output::stream_events(event_rx))
};
let outcome = loop {
let o = runtime.run(goal.clone()).await?;
if !matches!(o.finish_reason, FinishReason::PlanPending) {
break o;
}
let plan_text = o.final_text.as_deref().unwrap_or("(no plan)");
eprintln!("\n=== Proposed Plan ===\n{plan_text}");
eprint!("Confirm plan? [Y/n] ");
use std::io::Write;
let _ = std::io::stderr().flush();
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let trimmed = input.trim().to_lowercase();
if trimmed.is_empty() || trimmed == "y" || trimmed == "yes" {
runtime.confirm_plan();
} else {
runtime.reject_plan("User rejected the plan");
break o;
}
};
let transcript = runtime.transcript().to_vec();
drop(runtime);
// Cancellation is now visible via outcome.finish_reason ==
// FinishReason::Cancelled; print_finish_note below renders it.
// The historical `if shutdown.is_cancelled() { eprintln!... }`
// here was redundant once g137 wired the token into the kernel.
let _ = &shutdown;
printer.await.ok();
if !json_mode {
if let Some(ref msg) = outcome.final_text {
println!("\n=== final ===\n{msg}");
}
cli::output::print_usage(
outcome.total_usage,
&config.model,
outcome.llm_latency_ms,
outcome.steps,
);
cli::output::print_finish_note(&outcome.finish_reason);
}
let finish_status = if matches!(outcome.finish_reason, FinishReason::NoMoreToolCalls) {
"success"
} else {
"incomplete"
};
cli::output::finalize_session_writer(session_writer, finish_status);
cli::output::finalize_cost_tracker(
cost_tracker,
outcome.total_usage,
outcome.llm_latency_ms,
&config.model,
);
if let Some(path) = transcript_out {
cli::output::save_transcript(&transcript, outcome.steps, &config.model, &path)?;
}
if let Some(path) = session_out {
if !matches!(outcome.finish_reason, FinishReason::NoMoreToolCalls) {
cli::output::save_session(
&transcript,
outcome.steps,
goal,
&config.model,
&config.provider_type,
&tool_specs,
&path,
)?;
}
}
cli::output::exit_for_finish(&outcome.finish_reason, outcome.steps)
}
#[allow(clippy::too_many_arguments)]
async fn repl(
config: Config,
max_transcript_chars: Option<usize>,
json_mode: bool,
plan_first: bool,
mcp_config: Option<PathBuf>,
stream: bool,
hook_timing: bool,
) -> anyhow::Result<()> {
if let Err(msg) = config.validate_for_agent() {
eprintln!("{msg}");
std::process::exit(1);
}
if !json_mode {
let version = env!("CARGO_PKG_VERSION");
eprintln!(
"recursive v{}\nmodel: {} | provider: {} | workspace: {}\nType your goal, or :q to quit.\n",
version,
config.model,
config.provider_type,
config.workspace.display()
);
}
// Build runtime ONCE — MCP servers are spawned here and stay alive.
// Start with NullSink; we swap in a fresh ChannelSink per turn.
let mut runtime = cli::builder::build_runtime(
&config,
max_transcript_chars,
Vec::new(),
stream,
plan_first,
mcp_config,
hook_timing,
None,
None,
None,
)
.await?;
let mut total_turns = 0usize;
let stdin = BufReader::new(tokio::io::stdin());
let mut lines = stdin.lines();
loop {
eprint!("recursive> ");
use std::io::Write;
let _ = std::io::stderr().flush();
let Some(line) = lines.next_line().await? else {
break;
};
let goal = line.trim();
if goal.is_empty() {
continue;
}
if matches!(goal, ":q" | ":quit" | "exit") {
break;
}
if goal == ":clear" {
runtime.set_transcript(Vec::new());
total_turns = 0;
if !json_mode {
eprintln!("(conversation cleared)");
}
continue;
}
// Fresh ChannelSink per turn; swap back to NullSink when done.
let (sink, event_rx) = ChannelSink::new();
runtime.set_event_sink(Arc::new(sink));
let printer = if json_mode {
tokio::spawn(cli::output::stream_events_json(event_rx))
} else {
tokio::spawn(cli::output::stream_events_repl(event_rx))
};
match runtime.run(goal.to_string()).await {
Ok(outcome) => {
// Reset to NullSink so the channel is dropped and printer finishes
runtime.set_event_sink(Arc::new(NullSink));
printer.await.ok();
if !json_mode {
cli::output::print_usage(
outcome.total_usage,
&config.model,
outcome.llm_latency_ms,
outcome.steps,
);
cli::output::print_finish_note(&outcome.finish_reason);
}
total_turns += 1;
}
Err(e) => {
runtime.set_event_sink(Arc::new(NullSink));
printer.await.ok();
eprintln!("error: {e}");
}
}
}
if !json_mode && total_turns > 0 {
eprintln!("session: {} turn(s)", total_turns);
}
Ok(())
}
/// Run as an MCP stdio server.
///
/// Reads newline-delimited JSON-RPC 2.0 requests from stdin, dispatches
/// them to the agent's tools, and writes newline-delimited JSON-RPC
/// responses to stdout.
///
/// This mode is designed to be used as a subprocess by MCP clients (e.g.
/// Claude Desktop, VS Code extensions) that communicate via stdio.
async fn run_mcp_server_stdio(config: Config, _mcp_config: Option<PathBuf>) -> anyhow::Result<()> {
// Build the tool registry (local tools only — no MCP servers, since
// we *are* the MCP server).
let tools = cli::builder::build_tools(&config).await;
// We don't need an LLM provider or agent for the stdio server mode.
// The tools are called directly via dispatch_request.
// However, we need an McpClient-like wrapper. Since we're acting as
// the MCP server ourselves, we create a thin adapter that wraps the
// tool registry.
let registry = Arc::new(tools);
let stdin = tokio::io::stdin();
let reader = BufReader::new(stdin);
let mut lines = reader.lines();
// Stderr is used for logging/diagnostics; stdout is for JSON-RPC responses.
eprintln!("mcp-server: ready (reading JSON-RPC from stdin)");
while let Some(line) = lines.next_line().await? {
let line = line.trim().to_string();
if line.is_empty() {
continue;
}
// Parse the JSON-RPC request
let request: JsonRpcRequest = match serde_json::from_str(&line) {
Ok(req) => req,
Err(e) => {
// Can't parse — write an error response if there's an id
// Try to extract an id from the raw JSON
let id: Option<serde_json::Value> = serde_json::from_str(&line)
.ok()
.and_then(|v: serde_json::Value| v.get("id").cloned());
let response = JsonRpcResponse::error(id, -32700, format!("Parse error: {e}"));
let output = serde_json::to_string(&response)?;
println!("{output}");
continue;
}
};
let is_notification = request.id.is_none();
// Dispatch the request
let response = dispatch_request_via_registry(&request, ®istry).await;
// Notifications get no response
if is_notification {
continue;
}
if let Some(resp) = response {
let output = serde_json::to_string(&resp)?;
println!("{output}");
}
}
eprintln!("mcp-server: stdin closed, shutting down");
Ok(())
}
/// Dispatch a JSON-RPC request using the local tool registry.
///
/// This is a simplified dispatcher that handles the MCP methods by
/// calling the local tools directly, without an LLM or agent loop.
async fn dispatch_request_via_registry(
request: &JsonRpcRequest,
registry: &ToolRegistry,
) -> Option<JsonRpcResponse> {
let id = request.id.clone();
match request.method.as_str() {
"initialize" => {
let result = serde_json::json!({
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": true,
"resources": false,
"prompts": false
},
"serverInfo": {
"name": "recursive-agent",
"version": env!("CARGO_PKG_VERSION")
}
});
Some(JsonRpcResponse::success(id, result))
}
"notifications/initialized" => None,
"tools/list" => {
let specs = registry.specs();
let tools_arr: Vec<serde_json::Value> = specs
.into_iter()
.map(|s| {
serde_json::json!({
"name": s.name,
"description": s.description,
"inputSchema": s.parameters,
})
})
.collect();
Some(JsonRpcResponse::success(
id,
serde_json::json!({ "tools": tools_arr }),
))
}
"tools/call" => {
let name = request
.params
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("");
let arguments = request.params.get("arguments").cloned().unwrap_or_default();
match registry.invoke(name, arguments).await {
Ok(text) => {
let result = serde_json::json!({
"content": [{"type": "text", "text": text}]
});
Some(JsonRpcResponse::success(id, result))
}
Err(e) => {
let result = serde_json::json!({
"isError": true,
"content": [{"type": "text", "text": e.to_string()}]
});
Some(JsonRpcResponse::success(id, result))
}
}
}
"resources/list" => Some(JsonRpcResponse::success(
id,
serde_json::json!({ "resources": [] }),
)),
"resources/read" => Some(JsonRpcResponse::error(
id,
-32601,
"resources/read not supported",
)),
"prompts/list" => Some(JsonRpcResponse::success(
id,
serde_json::json!({ "prompts": [] }),
)),
"prompts/get" => Some(JsonRpcResponse::error(
id,
-32601,
"prompts/get not supported",
)),
_ => Some(JsonRpcResponse::method_not_found(id, &request.method)),
}
}
// ── WeChat helpers ────────────────────────────────────────────────────────────
/// Run TUI with a WeChat iLink daemon running in the background.
///
/// Starts the WeChat daemon, connects its request channel to the TUI backend,
/// then runs the TUI event loop as normal.
#[cfg(all(feature = "tui", feature = "weixin"))]
async fn run_tui_with_weixin(
base_url: Option<String>,
cred_path: Option<PathBuf>,
workspace: PathBuf,
) -> anyhow::Result<()> {
use recursive::tui::backend::Backend;
use recursive::weixin::{WeixinDaemon, WeixinDaemonOptions};
let mut opts = WeixinDaemonOptions::new(&workspace);
opts.base_url = base_url;
opts.cred_path = cred_path;
let daemon = WeixinDaemon::new(opts);
daemon.login(false).await?;
let (_polling_handle, mut weixin_req_rx) = daemon.start();
// Spawn bridge: forward WeixinRequests to the TUI backend.
let backend = Backend::spawn();
let weixin_tx = backend.weixin_tx.clone();
tokio::spawn(async move {
use recursive::tui::events::WeixinBackendRequest;
while let Some(req) = weixin_req_rx.recv().await {
let backend_req = WeixinBackendRequest {
user_id: req.user_id,
text: req.text,
reply_tx: req.reply_tx,
};
if weixin_tx.send(backend_req).is_err() {
break;
}
}
});
// Run TUI with the already-spawned backend.
recursive::tui::run_with_backend(backend)
.await
.map_err(anyhow::Error::from)
}
/// Run as a headless WeChat-only daemon (no TUI).
///
/// All interaction happens through WeChat messages. The agent runs in a
/// simple request-response loop.
#[cfg(feature = "weixin")]
async fn run_weixin_headless_daemon(
config: recursive::config::Config,
mcp_config: Option<PathBuf>,
base_url: Option<String>,
cred_path: Option<PathBuf>,
) -> anyhow::Result<()> {
use recursive::weixin::{WeixinDaemon, WeixinDaemonOptions};
use tracing::info;
let workspace = config.workspace.clone();
if let Err(msg) = config.validate_for_agent() {
anyhow::bail!("{msg}");
}
let mut opts = WeixinDaemonOptions::new(&workspace);
opts.base_url = base_url;
opts.cred_path = cred_path;
let daemon = WeixinDaemon::new(opts);
daemon.login(false).await?;
let (_polling_handle, mut weixin_req_rx) = daemon.start();
info!("WeChat daemon started — waiting for messages");
eprintln!("📱 Recursive WeChat daemon running. Send a message to get started.");
// Build runtime.
let mut runtime = cli::builder::build_runtime(
&config,
None, // max_transcript_chars
Vec::new(), // seed messages
false, // stream
false, // plan_first
mcp_config,
false, // hook_timing
None, // goal
None, // event_sink (WeChat responses come from enqueue return value)
None, // shutdown_token
)
.await?;
while let Some(req) = weixin_req_rx.recv().await {
info!("WeChat: processing message from {}", req.user_id);
match runtime.enqueue(&req.text).await {
Ok(Some(outcome)) => {
let _ = req.reply_tx.send(outcome.final_text);
}
Ok(None) => {
let _ = req.reply_tx.send(None);
}
Err(e) => {
tracing::error!("WeChat runtime error: {e}");
let _ = req.reply_tx.send(Some(format!("❌ 处理出错: {e}")));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::builder::build_runtime;
fn dummy_config(tmp: &std::path::Path) -> Config {
Config {
workspace: tmp.to_path_buf(),
api_base: "https://example.invalid/v1".into(),
api_key: Some("dummy-test-key".into()),
model: "test-model".into(),
provider_type: "openai".into(),
preset: None,
max_steps: 1,
temperature: 0.0,
system_prompt: "test".into(),
retry_max: 0,
retry_initial_backoff_secs: 1,
retry_max_backoff_secs: 1,
shell_timeout_secs: 5,
headless: false,
memory_summary_limit: 5,
thinking_budget: None,
session_name: None,
}
}
// Regression for the streaming-SSE merge bug (commit 92d257e) where
// the non-streaming code path called `bool::then(...).unwrap()` and
// panicked because `then(false)` returns None. This made every
// `recursive run` (default: stream=false) panic at startup, which
// in turn broke all parallel-self-improve.sh launches in batch 13.
/// Smoke test for `build_runtime` across the matrix of stream flag and
/// provider selector. Consolidated into ONE test per AGENTS.md guidance
/// because the anthropic branch reads `RECURSIVE_PROVIDER_TYPE` from the
/// process env — running it in parallel with other build-runtime tests
/// would race on that global. Asserts:
/// - stream=false / openai (default) → ok (regresses 92d257e bug)
/// - stream=true / openai → ok (regresses streaming-merge bug)
/// - stream=false / anthropic → ok (g47 dogfood)
/// The anthropic branch sets+restores the env var to keep the test
/// hermetic for any tests that come after it.
#[tokio::test]
async fn build_runtime_construction_smoke() {
let tmp = tempfile::tempdir().expect("tempdir");
let cfg = dummy_config(tmp.path());
let r1 = build_runtime(
&cfg,
None,
Vec::new(),
/* stream */ false,
false,
None,
false,
None,
None,
None,
)
.await;
assert!(r1.is_ok(), "openai/stream=false: must not panic or fail");
let r2 = build_runtime(
&cfg,
None,
Vec::new(),
/* stream */ true,
false,
None,
false,
None,
None,
None,
)
.await;
assert!(r2.is_ok(), "openai/stream=true: must not panic or fail");
let original = std::env::var("RECURSIVE_PROVIDER_TYPE").ok();
std::env::set_var("RECURSIVE_PROVIDER_TYPE", "anthropic");
let mut cfg_anthropic = dummy_config(tmp.path());
cfg_anthropic.provider_type = "anthropic".into();
let r3 = build_runtime(
&cfg_anthropic,
None,
Vec::new(),
false,
false,
None,
false,
None,
None,
None,
)
.await;
match original {
Some(v) => std::env::set_var("RECURSIVE_PROVIDER_TYPE", v),
None => std::env::remove_var("RECURSIVE_PROVIDER_TYPE"),
}
assert!(r3.is_ok(), "anthropic/stream=false: must not panic or fail");
}
#[test]
fn hook_timing_flag_accepted() {
// Verify --hook-timing is accepted by the CLI parser
let args = vec!["recursive", "--hook-timing", "run", "test goal"];
let cli = Cli::parse_from(args);
assert!(cli.hook_timing);
}
#[test]
fn hook_timing_flag_defaults_to_false() {
let args = vec!["recursive", "run", "test goal"];
let cli = Cli::parse_from(args);
assert!(!cli.hook_timing);
}
}