-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuiltin_commands.cpp
More file actions
2031 lines (1869 loc) · 79.6 KB
/
Copy pathbuiltin_commands.cpp
File metadata and controls
2031 lines (1869 loc) · 79.6 KB
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
#include "builtin_commands.hpp"
#include "compact.hpp"
#include "desktop_command.hpp"
#include "history_command.hpp"
#include "goal_command.hpp"
#include "init_command.hpp"
#include "lsp_command.hpp"
#include "memory_command.hpp"
#include "model_command.hpp"
#include "models_command.hpp"
#include "proxy_command.hpp"
#include "remote_control_command.hpp"
#include "resume_state_sync.hpp"
#include "websearch_command.hpp"
#include "../config/config.hpp"
#include "../tui/mode_picker.hpp"
#include "../tui/theme_palette.hpp"
#include "../config/saved_models.hpp"
#include "../provider/apply_model_to_session.hpp"
#include "../provider/cwd_model_override.hpp"
#include "../provider/model_resolver.hpp"
#include "../feedback/feedback_upload.hpp"
#include "../tool/mcp_manager.hpp"
#include "../tool/tool_executor.hpp"
#include "../skills/skill_registry.hpp"
#include "../skills/skill_commands.hpp"
#include "../session/session_manager.hpp"
#include "../session/session_resume_restore.hpp"
#include "../session/session_storage.hpp"
#include "../tui/subagent_host.hpp"
#include "../session/session_rewind.hpp"
#include "../session/thread_goal_store.hpp"
#include "../utils/logger.hpp"
#include "../utils/terminal_title.hpp"
#include "../utils/utf8_path.hpp"
#include "version.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <limits>
#include <mutex>
#include <optional>
#include <sstream>
#include <iomanip>
#include <thread>
#include <nlohmann/json.hpp>
namespace acecode {
namespace fs = std::filesystem;
namespace {
std::string trim_ascii_command(std::string s) {
auto is_space = [](unsigned char c) { return std::isspace(c) != 0; };
while (!s.empty() && is_space(static_cast<unsigned char>(s.front()))) s.erase(s.begin());
while (!s.empty() && is_space(static_cast<unsigned char>(s.back()))) s.pop_back();
return s;
}
std::string format_goal_status_chip(const ThreadGoal& goal) {
std::ostringstream oss;
oss << "goal: " << to_string(goal.status) << " "
<< TokenTracker::format_tokens(static_cast<int>(std::min<std::int64_t>(
goal.tokens_used, static_cast<std::int64_t>(std::numeric_limits<int>::max()))));
if (goal.token_budget.has_value()) {
oss << "/" << TokenTracker::format_tokens(static_cast<int>(std::min<std::int64_t>(
*goal.token_budget, static_cast<std::int64_t>(std::numeric_limits<int>::max()))));
}
return oss.str();
}
std::optional<PermissionMode> parse_permission_mode_arg(std::string mode) {
mode = trim_ascii_command(std::move(mode));
if (mode == "acceptEdits") mode = "accept-edits";
if (mode == "default") return PermissionMode::Default;
if (mode == "accept-edits") return PermissionMode::AcceptEdits;
if (mode == "plan") return PermissionMode::Plan;
if (mode == "yolo") return PermissionMode::Yolo;
return std::nullopt;
}
std::string mode_usage_text() {
return "Usage: /mode | /mode <default|accept-edits|plan|yolo>\n"
" /mode default <default|accept-edits|plan|yolo>\n"
" /mode --default <default|accept-edits|plan|yolo>";
}
void emit_system_message_locked(TuiState& state, std::string content) {
state.conversation.push_back({"system", std::move(content), false});
state.chat_follow_tail = true;
}
void apply_current_permission_mode(PermissionManager& permissions,
SessionManager* session_manager,
PermissionMode mode) {
const PermissionMode before = permissions.mode();
permissions.set_mode(mode);
permissions.clear_session_allows();
if (!session_manager) return;
session_manager->set_permission_mode(PermissionManager::mode_name(mode));
if (mode == PermissionMode::Plan) {
session_manager->set_pre_plan_permission_mode(
PermissionManager::mode_name(
before == PermissionMode::Plan
? permissions.pre_plan_mode()
: before));
session_manager->ensure_plan_file_path();
} else {
session_manager->set_pre_plan_permission_mode(std::string{});
}
}
std::string permission_mode_confirmation(PermissionMode mode) {
return std::string("Permission mode: ") + PermissionManager::mode_name(mode) +
" - " + PermissionManager::mode_description(mode);
}
void open_mode_picker(CommandContext& ctx) {
auto options = build_mode_picker_options(ctx.permissions.mode());
auto* state = &ctx.state;
auto* permissions = &ctx.permissions;
auto* session_manager = ctx.session_manager;
auto callback = [state, permissions, session_manager](PermissionMode mode) {
apply_current_permission_mode(*permissions, session_manager, mode);
emit_system_message_locked(*state, permission_mode_confirmation(mode));
};
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
ctx.state.mode_picker_options = std::move(options);
ctx.state.mode_picker_selected = 0;
for (std::size_t i = 0; i < ctx.state.mode_picker_options.size(); ++i) {
if (ctx.state.mode_picker_options[i].is_current) {
ctx.state.mode_picker_selected = static_cast<int>(i);
break;
}
}
ctx.state.mode_picker_callback = std::move(callback);
ctx.state.mode_picker_open = true;
}
if (ctx.post_event) ctx.post_event();
}
void set_permission_mode_for_next_session(CommandContext& ctx, PermissionMode mode) {
if (ctx.permissions.is_dangerous()) {
mode = PermissionMode::Yolo;
}
if (mode == PermissionMode::Plan) {
ctx.permissions.set_mode(PermissionMode::Default);
}
ctx.permissions.set_mode(mode);
ctx.permissions.clear_session_allows();
if (!ctx.session_manager) return;
ctx.session_manager->set_permission_mode(
PermissionManager::mode_name(mode),
/*persist_immediately=*/false);
if (mode == PermissionMode::Plan) {
ctx.session_manager->set_pre_plan_permission_mode(
PermissionManager::mode_name(ctx.permissions.pre_plan_mode()),
/*persist_immediately=*/false);
}
}
std::string apply_defaults_for_next_session(CommandContext& ctx) {
std::vector<std::string> notices;
std::string refresh_error;
if (!refresh_default_session_preferences_from_config(ctx.config, {}, &refresh_error)) {
notices.push_back("Default preference refresh failed: " + refresh_error);
}
const auto cwd_override = load_cwd_model_override(ctx.cwd);
const ModelProfile entry = resolve_effective_model(
ctx.config, cwd_override, std::optional<SessionMeta>{});
std::optional<SessionModelState> applied_model;
if (!entry.provider.empty() && !entry.model.empty() && ctx.model_binding) {
ApplyModelDeps deps;
deps.model_binding = ctx.model_binding;
deps.sm = ctx.session_manager;
deps.loop = &ctx.agent_loop;
deps.cfg = &ctx.config;
try {
auto result = apply_model_to_session(entry, deps);
ctx.config.context_window = result.state.context_window;
applied_model = result.state;
if (!result.warning.empty()) {
notices.push_back("Default model warning: " + result.warning);
}
} catch (const std::exception& e) {
notices.push_back(std::string("Default model apply failed: ") + e.what());
}
} else {
if (ctx.model_binding) {
ctx.model_binding->install_runtime_snapshot(
nullptr, SessionModelState{}, current_saved_models_revision());
}
if (ctx.session_manager) {
ctx.session_manager->set_active_provider(std::string{}, std::string{}, std::string{});
}
notices.push_back("No configured default model for next session.");
}
PermissionMode next_mode = PermissionMode::Default;
if (auto parsed = parse_permission_mode_arg(ctx.config.default_permission_mode)) {
next_mode = *parsed;
}
set_permission_mode_for_next_session(ctx, next_mode);
std::ostringstream summary;
summary << "Next session defaults: ";
if (applied_model.has_value()) {
summary << "model " << applied_model->name << " ("
<< applied_model->provider << "/" << applied_model->model << ")";
} else {
summary << "no model";
}
summary << ", permission " << PermissionManager::mode_name(ctx.permissions.mode());
for (const auto& notice : notices) {
summary << "\n" << notice;
}
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
if (applied_model.has_value()) {
std::string status = tui_model_status_line(*applied_model);
if (!status.empty()) ctx.state.status_line = std::move(status);
} else {
ctx.state.status_line = "No model configured";
}
ctx.agent_loop.set_context_window(ctx.config.context_window);
ctx.state.token_status = ctx.token_tracker.format_status(ctx.config.context_window);
ctx.state.token_percent = ctx.token_tracker.context_percent(ctx.config.context_window);
}
return summary.str();
}
void publish_goal_state_locked(TuiState& state, AgentLoop& agent_loop, SessionManager* session_manager) {
if (!session_manager) {
state.goal_status.clear();
return;
}
const std::string sid = session_manager->current_session_id();
if (sid.empty()) {
state.goal_status.clear();
agent_loop.restore_goal_runtime();
return;
}
ThreadGoalStore* store = session_manager->existing_goal_store();
if (!store) {
state.goal_status.clear();
agent_loop.events().emit(SessionEventKind::GoalCleared,
nlohmann::json{{"session_id", sid}});
agent_loop.restore_goal_runtime();
return;
}
std::string error;
auto goal = store->get_thread_goal(sid, &error);
if (!error.empty()) {
LOG_WARN("[goal] failed to publish TUI goal state: " + error);
state.goal_status.clear();
agent_loop.restore_goal_runtime();
return;
}
if (goal.has_value()) {
state.goal_status = format_goal_status_chip(*goal);
agent_loop.events().emit(SessionEventKind::GoalUpdated,
nlohmann::json{{"session_id", goal->thread_id}, {"goal", thread_goal_to_json(*goal)}});
} else {
state.goal_status.clear();
agent_loop.events().emit(SessionEventKind::GoalCleared,
nlohmann::json{{"session_id", sid}});
}
agent_loop.restore_goal_runtime();
}
} // namespace
static void emit_command_message(CommandContext& ctx, std::string message) {
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, std::move(message));
}
if (ctx.post_event) ctx.post_event();
}
static void cmd_turn(CommandContext& ctx, const std::string& raw_args) {
const std::string guidance = trim_ascii_command(raw_args);
if (guidance.empty()) {
emit_command_message(ctx, "Usage: /turn <guidance>");
return;
}
const std::string turn_id = ctx.agent_loop.active_turn_id();
if (turn_id.empty()) {
emit_command_message(
ctx,
"No active steerable turn. /turn only guides the turn that is "
"currently running.");
return;
}
UserInput input;
input.text = guidance;
auto result = ctx.agent_loop.interrupt_turn(turn_id, input);
switch (result.status) {
case TurnSteerStatus::Accepted:
emit_command_message(
ctx,
"Interrupting the active turn to submit guidance immediately.");
return;
case TurnSteerStatus::NoActiveTurn:
case TurnSteerStatus::NonSteerable:
emit_command_message(
ctx,
"The active turn ended before the guidance could be accepted.");
return;
case TurnSteerStatus::TurnMismatch:
emit_command_message(
ctx,
"The active turn changed before the guidance could be accepted.");
return;
case TurnSteerStatus::QueueFull:
emit_command_message(
ctx,
"The immediate guidance queue is full. Try again after the "
"agent starts the pending turn.");
return;
case TurnSteerStatus::InvalidInput:
emit_command_message(ctx, "Usage: /turn <guidance>");
return;
case TurnSteerStatus::UnknownSession:
break;
}
emit_command_message(ctx, "Active-turn guidance is unavailable.");
}
static void cmd_side_question(CommandContext& ctx,
const std::string& raw_args,
const std::string& command_name) {
const std::string question = trim_ascii_command(raw_args);
if (question.empty()) {
emit_command_message(
ctx, "Usage: /" + command_name + " <question>");
return;
}
emit_command_message(
ctx, "[/" + command_name + "] Side question started: " + question);
auto* state = &ctx.state;
auto post_event = ctx.post_event;
const bool started = ctx.agent_loop.ask_side_question_async(
question,
[state, post_event, command_name](SideQuestionResult result) {
std::string message;
if (result.status == SideQuestionStatus::Ok) {
message = "[/" + command_name + "] " + result.answer;
} else {
message = "[/" + command_name + "] Side question failed: " +
(result.error.empty()
? std::string("unknown error")
: result.error);
}
{
std::lock_guard<std::mutex> lk(state->mu);
emit_system_message_locked(*state, std::move(message));
}
if (post_event) post_event();
});
if (!started) {
emit_command_message(
ctx, "[/" + command_name +
"] Side question could not start because the session is "
"shutting down.");
}
}
static void cmd_help(CommandContext& ctx, const std::string& /*args*/) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
std::ostringstream oss;
oss << "Available commands:\n"
<< " /help - Show this help message\n"
<< " /clear - Clear conversation history\n"
<< " /new - Alias for /clear\n"
<< " /archive - Archive this session, then clear the conversation\n"
<< " /archieve - Alias for /archive\n"
<< " /compact - Compress conversation history\n"
<< " /model - Show or switch current model\n"
<< " /mode - Show or switch permission mode\n"
<< " /config - Show current configuration\n"
<< " /tokens - Show session token usage\n"
<< " /goal - Create, view, pause, resume, edit, or clear the thread goal\n"
<< " /plan - Enter plan mode or start planning a described task\n"
<< " /turn - Interrupt the active turn and send guidance immediately\n"
<< " /btw - Ask a detached one-turn side question\n"
<< " /side - Alias for /btw\n"
<< " /resume - Resume a previous session\n"
<< " /rewind - Rewind to a previous user turn\n"
<< " /fork - Fork from a previous user turn\n"
<< " /mcp - Manage MCP servers\n"
<< " /skills - List, invoke, or reload installed skills\n"
<< " /memory - List, view, edit, forget, or reload persistent user memory\n"
<< " /init - Generate an AGENT.md skeleton in the current directory\n"
<< " /history - List or clear the per-working-directory input history\n"
<< " /feedback - Upload current session and runtime logs to the configured upgrade service\n"
<< " /models - Inspect bundled models.dev registry\n"
<< " /proxy - Show or switch the HTTP proxy used for LLM/API requests\n"
<< " /desktop - Open ACECode Desktop\n"
<< " /title - Set or show the window title for this session\n"
<< " /exit - Exit acecode";
if (ctx.skills) {
size_t n = ctx.skills->list().size();
if (n > 0) {
oss << "\n\n" << n << " skill" << (n == 1 ? "" : "s")
<< " installed. Type /skills for the full list, or /skills help for usage.";
}
}
ctx.state.conversation.push_back({"system", oss.str(), false});
ctx.state.chat_follow_tail = true;
}
static bool ensure_empty_file_exists(const fs::path& path, std::string* error) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
if (ec) {
if (error) *error = "failed to create session directory: " + ec.message();
return false;
}
if (fs::exists(path, ec)) return true;
std::ofstream ofs(path, std::ios::binary | std::ios::app);
if (!ofs) {
if (error) *error = "failed to create session JSONL file: " + path_to_utf8(path);
return false;
}
return true;
}
static std::string feedback_error_with_package(const std::string& error,
const std::string& upload_url,
const fs::path& package_path) {
std::ostringstream oss;
oss << "Feedback upload failed: " << error
<< "\nUpload URL: " << upload_url;
if (!package_path.empty()) {
oss << "\nPackage retained: " << path_to_utf8(package_path);
}
return oss.str();
}
static void cmd_feedback(CommandContext& ctx, const std::string& raw_args) {
const std::string feedback_text = trim_ascii_command(raw_args);
if (!ctx.session_manager) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, "Feedback upload failed: session persistence is not available.");
return;
}
if (!is_valid_upgrade_base_url(ctx.config.upgrade.base_url)) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
"Feedback upload failed: upgrade.base_url must be a non-empty http or https URL.");
return;
}
const std::string upload_url = normalize_upgrade_base_url(ctx.config.upgrade.base_url);
const std::string session_id = ctx.session_manager->ensure_active_session_id();
if (session_id.empty()) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, "Feedback upload failed: active session is not available.");
return;
}
const std::string project_dir = SessionStorage::get_project_dir(ctx.cwd);
const fs::path session_jsonl =
path_from_utf8(SessionStorage::session_path(project_dir, session_id));
std::string session_file_error;
if (!ensure_empty_file_exists(session_jsonl, &session_file_error)) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, "Feedback upload failed: " + session_file_error);
return;
}
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
"Preparing feedback package for upload to " + upload_url);
}
if (ctx.post_event) ctx.post_event();
acecode::feedback::FeedbackPackageRequest package_req;
package_req.feedback_text = feedback_text;
package_req.session_id = session_id;
package_req.session_jsonl_path = session_jsonl;
package_req.acecode_version = ACECODE_VERSION;
// TUI 自己的日志(cwd/acecode.log)+ 同机 daemon / desktop 的滚动日志:
// TUI 会话也可能被 daemon 侧的组件影响,缺失的来源会被静默跳过。
{
acecode::feedback::FeedbackLogSource tui_log;
tui_log.path = path_from_utf8(ctx.cwd) / "acecode.log";
tui_log.entry_name = "logs/acecode.log.tail.txt";
package_req.logs.push_back(std::move(tui_log));
}
for (auto& source :
acecode::feedback::collect_runtime_log_sources(path_from_utf8(get_logs_dir()))) {
package_req.logs.push_back(std::move(source));
}
auto package = acecode::feedback::build_feedback_package(package_req);
if (!package.ok) {
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, "Feedback upload failed: " + package.error);
}
if (ctx.post_event) ctx.post_event();
return;
}
acecode::feedback::FeedbackUploadRequest upload_req;
upload_req.upload_url = upload_url;
upload_req.package_path = package.package_path;
upload_req.package_filename = package.package_filename;
upload_req.timeout_ms = ctx.config.upgrade.timeout_ms;
auto upload = acecode::feedback::upload_feedback_package(upload_req);
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
if (upload.ok) {
std::error_code ec;
fs::remove(package.package_path, ec);
emit_system_message_locked(
ctx.state,
"Feedback uploaded: " + package.package_filename);
} else {
emit_system_message_locked(
ctx.state,
feedback_error_with_package(upload.error, upload_url, package.package_path));
}
}
if (ctx.post_event) ctx.post_event();
}
static void cmd_mode(CommandContext& ctx, const std::string& raw_args) {
const std::string args = trim_ascii_command(raw_args);
if (args.empty()) {
open_mode_picker(ctx);
return;
}
std::istringstream iss(args);
std::string first;
std::string second;
std::string extra;
iss >> first;
iss >> second;
iss >> extra;
const bool set_default =
first == "default" || first == "--default" || first == "set-default";
if (set_default) {
if (second.empty() || !extra.empty()) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, mode_usage_text());
return;
}
auto parsed = parse_permission_mode_arg(second);
if (!parsed.has_value()) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state,
"Invalid permission mode: " + second + "\n" + mode_usage_text());
return;
}
const std::string before = ctx.config.default_permission_mode;
ctx.config.default_permission_mode = PermissionManager::mode_name(*parsed);
try {
save_config(ctx.config);
} catch (const std::exception& e) {
ctx.config.default_permission_mode = before;
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state,
std::string("/mode default: write failed: ") + e.what());
return;
}
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state,
"Default permission mode: " + ctx.config.default_permission_mode +
" - applies to new sessions");
return;
}
if (!second.empty() || !extra.empty()) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, mode_usage_text());
return;
}
auto parsed = parse_permission_mode_arg(first);
if (!parsed.has_value()) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state,
"Invalid permission mode: " + first + "\n" + mode_usage_text());
return;
}
apply_current_permission_mode(ctx.permissions, ctx.session_manager, *parsed);
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(ctx.state, permission_mode_confirmation(*parsed));
}
static void cmd_plan(CommandContext& ctx, const std::string& raw_args) {
const std::string args = trim_ascii_command(raw_args);
std::string plan_file;
std::string prompt_to_submit;
std::string display_to_submit;
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
const PermissionMode before = ctx.permissions.mode();
ctx.permissions.set_mode(PermissionMode::Plan);
ctx.permissions.clear_session_allows();
if (ctx.session_manager) {
ctx.session_manager->set_permission_mode("plan");
ctx.session_manager->set_pre_plan_permission_mode(
PermissionManager::mode_name(
before == PermissionMode::Plan
? ctx.permissions.pre_plan_mode()
: before));
plan_file = ctx.session_manager->ensure_plan_file_path();
}
std::ostringstream oss;
oss << "Plan mode enabled.";
if (!plan_file.empty()) {
oss << "\nPlan file: " << plan_file;
}
oss << "\nExplore and update only the plan file, then call ExitPlanMode for approval.";
ctx.state.conversation.push_back({"system", oss.str(), false});
ctx.state.chat_follow_tail = true;
if (!args.empty()) {
display_to_submit = "/plan " + args;
if (ctx.state.is_waiting || ctx.state.tool_running) {
ctx.state.pending_queue.push_back(display_to_submit);
UserInput queued;
queued.text = args;
queued.display_text = display_to_submit;
ctx.state.pending_structured_queue.push_back(std::move(queued));
} else {
ctx.state.current_thinking_phrase = "Planning";
ctx.state.thinking_start_time = std::chrono::steady_clock::now();
ctx.state.streaming_output_chars = 0;
ctx.state.turn_completion_tokens_confirmed = 0;
ctx.state.is_waiting = true;
prompt_to_submit = args;
}
}
}
if (!prompt_to_submit.empty()) {
submit_user_text(ctx, prompt_to_submit, display_to_submit);
}
if (ctx.post_event) ctx.post_event();
}
static void reset_conversation_for_new_session(CommandContext& ctx) {
std::string cleared_session_id;
bool clear_title = false;
{
std::lock_guard<std::mutex> lk(ctx.state.mu);
ctx.state.conversation.clear();
ctx.agent_loop.clear_messages();
ctx.token_tracker.reset();
ctx.state.token_status = ctx.token_tracker.format_status(ctx.config.context_window);
ctx.state.token_percent = ctx.token_tracker.context_percent(ctx.config.context_window);
ctx.state.goal_status.clear();
if (ctx.session_manager) {
cleared_session_id = ctx.session_manager->current_session_id();
}
if (!ctx.state.current_session_title.empty()) {
ctx.state.current_session_title.clear();
clear_title = true;
}
}
if (ctx.session_manager) {
ctx.session_manager->end_current_session();
}
if (!cleared_session_id.empty()) {
ctx.agent_loop.events().emit(SessionEventKind::GoalCleared,
nlohmann::json{{"session_id", cleared_session_id}});
ctx.agent_loop.restore_goal_runtime();
}
if (clear_title) {
clear_terminal_title();
}
const std::string default_summary = apply_defaults_for_next_session(ctx);
std::lock_guard<std::mutex> lk(ctx.state.mu);
ctx.state.conversation.push_back({
"system",
"Conversation cleared.\n" + default_summary,
false});
ctx.state.chat_follow_tail = true;
}
static void cmd_clear(CommandContext& ctx, const std::string& /*args*/) {
reset_conversation_for_new_session(ctx);
}
static void cmd_archive(CommandContext& ctx, const std::string& /*args*/) {
if (!ctx.session_manager) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
"Archive failed: session persistence is unavailable. "
"The current conversation was not cleared.");
return;
}
const ArchiveCurrentSessionResult result =
ctx.session_manager->archive_current_session();
if (result == ArchiveCurrentSessionResult::PersistenceFailed) {
std::string detail = ctx.session_manager->last_error();
if (detail.empty()) {
detail = "Failed to persist archived session metadata.";
}
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
"Archive failed: " + detail +
" The current conversation was not cleared.");
return;
}
// No active persisted session still receives the requested /clear effect.
// reset_conversation_for_new_session keeps session creation lazy, so this
// path never creates an empty archived session.
reset_conversation_for_new_session(ctx);
}
static void show_config_summary(CommandContext& ctx) {
auto provider_snap = ctx.model_binding
? ctx.model_binding->provider_snapshot()
: nullptr;
std::lock_guard<std::mutex> lk(ctx.state.mu);
std::ostringstream oss;
oss << "Current configuration:\n"
<< " provider: " << ctx.config.provider << "\n"
<< " model: " << (provider_snap ? provider_snap->model() : std::string("(unavailable)")) << "\n"
<< " context_window: " << ctx.config.context_window << "\n"
<< " permission: " << PermissionManager::mode_name(ctx.permissions.mode());
if (ctx.config.provider == "openai") {
oss << "\n base_url: " << ctx.config.openai.base_url;
}
ctx.state.conversation.push_back({"system", oss.str(), false});
ctx.state.chat_follow_tail = true;
}
static void cmd_config(CommandContext& ctx, const std::string& raw_args) {
const std::string args = trim_ascii_command(raw_args);
if (args == "show") {
show_config_summary(ctx);
return;
}
if (!ctx.open_settings_surface) {
if (args.empty()) {
show_config_summary(ctx);
} else {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
"/config settings UI is only available in an interactive TUI.");
}
return;
}
std::string error;
if (!ctx.open_settings_surface(args, error)) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
emit_system_message_locked(
ctx.state,
error.empty() ? "Could not open settings." : std::move(error));
}
}
static void cmd_tokens(CommandContext& ctx, const std::string& /*args*/) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
std::ostringstream oss;
oss << "Session token usage:\n"
<< " prompt: " << TokenTracker::format_tokens(ctx.token_tracker.prompt_tokens()) << "\n"
<< " completion: " << TokenTracker::format_tokens(ctx.token_tracker.completion_tokens()) << "\n"
<< " total: " << TokenTracker::format_tokens(ctx.token_tracker.total_tokens());
ctx.state.conversation.push_back({"system", oss.str(), false});
ctx.state.chat_follow_tail = true;
}
static void cmd_compact(CommandContext& ctx, const std::string& /*args*/) {
// Serialize manual compaction on the AgentLoop worker, the same path used
// by daemon sessions. This prevents transcript/model-history races and
// gives TUI and web callers identical checkpoint semantics.
if (ctx.agent_loop.is_busy()) {
ctx.agent_loop.emit_system_message("Compaction unavailable while another operation is active.");
return;
}
ctx.agent_loop.submit_compact();
}
static const char* mcp_state_label(McpServerState s) {
switch (s) {
case McpServerState::Starting: return "starting";
case McpServerState::Connected: return "connected";
case McpServerState::Disabled: return "disabled";
case McpServerState::Failed: return "failed";
case McpServerState::Cancelled: return "cancelled";
case McpServerState::TimedOut: return "timed_out";
}
return "unknown";
}
static void mcp_push(CommandContext& ctx, const std::string& msg) {
std::lock_guard<std::mutex> lk(ctx.state.mu);
ctx.state.conversation.push_back({"system", msg, false});
ctx.state.chat_follow_tail = true;
}
static std::string mcp_known_servers(const McpManager& mgr) {
auto names = mgr.server_names();
if (names.empty()) return "(none)";
std::ostringstream oss;
for (size_t i = 0; i < names.size(); ++i) {
if (i) oss << ", ";
oss << names[i];
}
return oss.str();
}
static void cmd_mcp(CommandContext& ctx, const std::string& args) {
const std::string normalized_args = trim_ascii_command(args);
if (normalized_args.empty() && ctx.open_management_surface) {
std::string error;
if (!ctx.open_management_surface("mcp", error)) {
mcp_push(
ctx,
error.empty() ? "Could not open MCP management." : error);
}
return;
}
if (!ctx.mcp_manager || !ctx.tools) {
mcp_push(ctx, "MCP manager is not available in this session.");
return;
}
McpManager& mgr = *ctx.mcp_manager;
ToolExecutor& tools = *ctx.tools;
// Parse: first token is subcommand, remainder is name.
std::string trimmed = normalized_args;
while (!trimmed.empty() && std::isspace(static_cast<unsigned char>(trimmed.front()))) {
trimmed.erase(trimmed.begin());
}
while (!trimmed.empty() && std::isspace(static_cast<unsigned char>(trimmed.back()))) {
trimmed.pop_back();
}
std::string sub, name;
if (!trimmed.empty()) {
auto sp = trimmed.find(' ');
if (sp == std::string::npos) {
sub = trimmed;
} else {
sub = trimmed.substr(0, sp);
name = trimmed.substr(sp + 1);
while (!name.empty() && std::isspace(static_cast<unsigned char>(name.front()))) {
name.erase(name.begin());
}
}
}
// Default view: list servers with state summary.
if (sub.empty()) {
auto servers = mgr.list_servers();
if (servers.empty()) {
mcp_push(ctx, "No MCP servers configured.");
return;
}
std::ostringstream oss;
oss << "MCP servers:";
for (const auto& s : servers) {
oss << "\n " << s.name
<< " [" << mcp_state_label(s.state) << "]"
<< " [" << s.transport << "]"
<< " tools=" << s.tool_count
<< " at=" << s.command_line;
if (!s.error.empty()) {
oss << " error=" << s.error;
}
}
mcp_push(ctx, oss.str());
return;
}
if (sub == "help") {
std::ostringstream oss;
oss << "/mcp usage:\n"
<< " /mcp - Open MCP management in the TUI\n"
<< " /mcp list - List tools grouped by server\n"
<< " /mcp enable <name> - Connect a disabled or failed server\n"
<< " /mcp disable <name> - Stop a server and unregister its tools\n"
<< " /mcp reconnect <name> - Force a teardown + reconnect\n"
<< " /mcp help - Show this help";
mcp_push(ctx, oss.str());
return;
}
if (sub == "list") {
auto grouped = mgr.list_tools_by_server();
if (grouped.empty()) {
mcp_push(ctx, "No MCP servers configured.");
return;
}
auto servers = mgr.list_servers();
std::map<std::string, McpServerState> state_map;
for (const auto& s : servers) state_map[s.name] = s.state;
std::ostringstream oss;
oss << "MCP tools:";
for (const auto& [server, defs] : grouped) {
auto it = state_map.find(server);
const char* label = (it != state_map.end()) ? mcp_state_label(it->second) : "unknown";
oss << "\n " << server << " [" << label << "]";
if (defs.empty()) {
oss << "\n (no tools registered)";
} else {
for (const auto& d : defs) {
oss << "\n - " << d.name;
if (!d.description.empty()) {
std::string desc = d.description;
if (desc.size() > 80) desc = desc.substr(0, 77) + "...";
oss << " " << desc;
}
}
}
}
mcp_push(ctx, oss.str());
return;
}
if (sub == "disable" || sub == "enable" || sub == "reconnect") {
if (name.empty()) {
mcp_push(ctx, "Usage: /mcp " + sub + " <server-name>");
return;
}
if (!mgr.has_server(name)) {
mcp_push(ctx, "Unknown MCP server '" + name + "'. Known: " + mcp_known_servers(mgr));
return;
}
bool changed = false;
if (sub == "disable") {
changed = mgr.disable(name, tools);
if (changed) {
mcp_push(ctx, "Disabled MCP server '" + name + "'.");
} else {
mcp_push(ctx, "MCP server '" + name + "' is already disabled.");
}
} else if (sub == "enable") {
changed = mgr.enable(name, tools);
if (changed) {
mcp_push(ctx, "Starting MCP server '" + name + "' in the background.");
} else {
// Distinguish already-connected vs failed.
auto servers = mgr.list_servers();
for (const auto& s : servers) {
if (s.name == name) {
if (s.state == McpServerState::Connected) {
mcp_push(ctx, "MCP server '" + name + "' is already connected.");
} else if (s.state == McpServerState::Starting) {
mcp_push(ctx, "MCP server '" + name + "' is already starting.");
} else {
mcp_push(ctx, "Failed to enable MCP server '" + name + "'. Check logs for details.");
}
return;
}
}
}
} else { // reconnect
changed = mgr.reconnect(name, tools);