-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.cpp
More file actions
5769 lines (5388 loc) · 261 KB
/
main.cpp
File metadata and controls
5769 lines (5388 loc) · 261 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 <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cctype>
#include <algorithm>
#include <array>
#include <sstream>
#include <string_view>
#include <random>
#include <filesystem>
#include <optional>
#include <unordered_set>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <io.h>
#include <direct.h>
#include <imm.h>
#pragma comment(lib, "Imm32.lib")
#else
#include <termios.h>
#include <unistd.h>
#endif
#include <ftxui/component/component.hpp>
#include <ftxui/component/screen_interactive.hpp>
#include <ftxui/dom/elements.hpp>
#include <ftxui/screen/string.hpp>
#include <ftxui/screen/terminal.hpp>
#include "version.hpp"
#include "config/config.hpp"
#include "network/proxy_resolver.hpp"
#include "provider/provider_factory.hpp"
#include "provider/copilot_provider.hpp"
#include "provider/model_context_resolver.hpp"
#include "provider/models_dev_registry.hpp"
#include "provider/model_resolver.hpp"
#include "provider/cwd_model_override.hpp"
#include "provider/apply_model_to_session.hpp"
#include "tool/tool_executor.hpp"
#include "tool/bash_tool.hpp"
#include "tool/builtin_tool_registry.hpp"
#include "tool/file_read_tool.hpp"
#include "tool/file_write_tool.hpp"
#include "tool/file_edit_tool.hpp"
#include "tool/grep_tool.hpp"
#include "tool/glob_tool.hpp"
#include "tool/task_complete_tool.hpp"
#include "tool/goal_tool.hpp"
#include "tool/mcp_manager.hpp"
#include "tool/skills_tool.hpp"
#include "tool/skill_view_tool.hpp"
#include "tool/memory_read_tool.hpp"
#include "tool/memory_write_tool.hpp"
#include "tool/ask_user_question_tool.hpp"
#include "tool/ask_overlay_input.hpp"
#include "tool/ace_browser_bridge/browser_tools.hpp"
#include "tui/confirm_question.hpp"
#include "skills/skill_init.hpp"
#include "skills/skill_registry.hpp"
#include "skills/skill_commands.hpp"
#include "skills/default_skill_seeder.hpp"
#include "memory/memory_paths.hpp"
#include "memory/memory_registry.hpp"
#include "tool/web_search/runtime.hpp"
#include "tool/web_search/backend_router.hpp"
#include "tool/web_search/region_detector.hpp"
#include "tool/web_search/web_search_tool.hpp"
#include "utils/logger.hpp"
#include "permissions.hpp"
#include "agent_loop.hpp"
#include "commands/configure.hpp"
#include "daemon/cli.hpp"
#ifdef _WIN32
# include "daemon/service_win.hpp"
#endif
#include "upgrade/apply.hpp"
#include "upgrade/check.hpp"
#include "upgrade/manifest.hpp"
#include "upgrade/upgrade.hpp"
#include "commands/command_registry.hpp"
#include "commands/builtin_commands.hpp"
#include "commands/compact.hpp"
#include "utils/token_tracker.hpp"
#include "markdown/markdown_formatter.hpp"
#include "session/session_manager.hpp"
#include "session/session_registry.hpp"
#include "session/session_resume_restore.hpp"
#include "tui/chat_scroll.hpp"
#include "tui/diff_view.hpp"
#include "tui/unclipped_reflect.hpp"
#include "tui/paste_handler.hpp"
#include "tui/ask_question_overlay.hpp"
#include "tui/picker_scroll.hpp"
#include "tui/render_mode_factory.hpp"
#include "utils/terminal_capability.hpp"
#include "utils/state_file.hpp"
#include "tui/slash_dropdown.hpp"
#include "tui/text_truncation.hpp"
#include "tui/thick_vscroll_bar.hpp"
#include "tui/tool_progress.hpp"
#include "tui/sidebar_model.hpp"
#include "tui/input_history_navigation.hpp"
#include "utils/base64.hpp"
#include "utils/clipboard.hpp"
#include "utils/drag_scroll.hpp"
#include "utils/terminal_title.hpp"
#include "session/session_storage.hpp"
#include "history/input_history_store.hpp"
#include "desktop/workspace_registry.hpp"
#include <cstdio>
using namespace ftxui;
using namespace acecode;
namespace {
static const std::string EN_THINKING_PHRASES[50] = {
"Analyzing", "Pondering", "Investigating", "Synthesizing", "Reviewing",
"Processing", "Compiling", "Evaluating", "Formulating", "Brainstorming",
"Searching", "Deciphering", "Gathering", "Debugging", "Inspecting",
"Generating", "Organizing", "Mapping", "Exploring", "Tracing",
"Validating", "Considering", "Reflecting", "Simulating", "Calculating",
"Abstracting", "Diving", "Looking", "Troubleshooting", "Crafting",
"Polishing", "Assembling", "Connecting", "Building", "Parsing",
"Extracting", "Tuning", "Optimizing", "Designing", "Theorizing",
"Hypothesizing", "Seeking", "Interpreting", "Measuring", "Weighing",
"Reading", "Preparing", "Reasoning", "Constructing", "Finalizing"
};
static const std::string ZH_THINKING_PHRASES[50] = {
"分析中", "思考中", "研究中", "探索中", "综合中",
"审查中", "处理中", "编译中", "评估中", "规划中",
"构思中", "搜索中", "解码中", "收集中", "调试中",
"检查中", "生成中", "组织中", "映射中", "推理中",
"验证中", "考虑中", "反思中", "模拟中", "计算中",
"抽象中", "深挖中", "寻找中", "排查中", "打磨中",
"完善中", "组装中", "连接中", "构建中", "解析中",
"提取中", "微调中", "优化中", "设计中", "推论中",
"假设中", "路线中", "解读中", "测量中", "权衡中",
"阅读中", "准备中", "追溯中", "构造中", "总结中"
};
static bool is_user_chinese(const acecode::TuiState& state) {
if (state.conversation.empty()) return false;
for (auto it = state.conversation.rbegin(); it != state.conversation.rend(); ++it) {
if (it->role == "user") {
for (unsigned char c : it->content) {
if (c >= 0xE0) return true;
}
return false;
}
}
return false;
}
static std::string get_random_thinking_phrase(bool is_zh) {
static thread_local std::random_device rd;
static thread_local std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 49);
return is_zh ? ZH_THINKING_PHRASES[dis(gen)] : EN_THINKING_PHRASES[dis(gen)];
}
// A ToolSummary whose metrics contain `exit`, `aborted`, or `timeout` indicates
// a failure; used by the tool_result renderer to pick colour and decide whether
// to show the inline error tail.
static bool is_success_summary(const acecode::ToolSummary& s) {
for (const auto& kv : s.metrics) {
if (kv.first == "exit" && kv.second != "0") return false;
if (kv.first == "aborted" && kv.second == "true") return false;
if (kv.first == "timeout" && kv.second == "true") return false;
}
return true;
}
static std::string renderable_tool_summary_line(const acecode::ToolSummary& s,
const std::string& metric_str,
int max_visual_width) {
const std::string prefix = s.icon + " " + s.verb + " \xC2\xB7 ";
const std::string suffix = metric_str.empty()
? std::string()
: " \xC2\xB7 " + metric_str;
return acecode::tui::truncate_middle_segment(
prefix, s.object, suffix, max_visual_width);
}
static std::string collapse_sidebar_title_whitespace(std::string_view text) {
std::string out;
bool in_space = false;
for (unsigned char c : text) {
if (std::isspace(c)) {
if (!out.empty() && !in_space) {
out.push_back(' ');
}
in_space = true;
} else {
out.push_back(static_cast<char>(c));
in_space = false;
}
}
if (!out.empty() && out.back() == ' ') {
out.pop_back();
}
return out;
}
static std::string first_user_message_title(const acecode::TuiState& state) {
for (const auto& msg : state.conversation) {
if (msg.role == "user") {
std::string title = collapse_sidebar_title_whitespace(msg.content);
if (!title.empty()) {
return title;
}
}
}
std::string explicit_title =
collapse_sidebar_title_whitespace(state.current_session_title);
return explicit_title.empty() ? std::string("New session") : explicit_title;
}
static void trim_ascii_space_suffix(std::string& text) {
while (!text.empty() && text.back() == ' ') {
text.pop_back();
}
}
static std::string truncate_cells_prefix(std::string_view text, int max_cells) {
if (max_cells <= 0) {
return {};
}
std::string out;
int used = 0;
for (const auto& glyph : ftxui::Utf8ToGlyphs(std::string(text))) {
if (glyph.empty()) {
continue;
}
const int width = std::max(0, ftxui::string_width(glyph));
if (used + width > max_cells) {
break;
}
out += glyph;
used += width;
}
return out;
}
static std::string truncate_cells_middle_ascii(std::string_view text, int max_cells) {
if (max_cells <= 0) {
return {};
}
const std::string input(text);
if (ftxui::string_width(input) <= max_cells) {
return input;
}
if (max_cells <= 3) {
return truncate_cells_prefix(input, max_cells);
}
const int body_cells = max_cells - 3;
const int head_cells = std::max(1, body_cells / 2);
const int tail_cells = std::max(0, body_cells - head_cells);
const auto glyphs = ftxui::Utf8ToGlyphs(input);
std::string head;
int used_head = 0;
for (const auto& glyph : glyphs) {
const int width = std::max(0, ftxui::string_width(glyph));
if (used_head + width > head_cells) {
break;
}
head += glyph;
used_head += width;
}
std::vector<std::string> tail_glyphs;
int used_tail = 0;
for (std::size_t i = glyphs.size(); i > 0; --i) {
const auto& glyph = glyphs[i - 1];
const int width = std::max(0, ftxui::string_width(glyph));
if (used_tail + width > tail_cells) {
break;
}
tail_glyphs.push_back(glyph);
used_tail += width;
}
std::reverse(tail_glyphs.begin(), tail_glyphs.end());
std::string out = head + "...";
for (const auto& glyph : tail_glyphs) {
out += glyph;
}
return out;
}
static Element sidebar_section_header(const std::string& label, int count) {
return hbox({
text(label) | color(Color::GrayLight) | dim,
text(" " + std::to_string(count)) | color(Color::GrayDark) | dim,
});
}
static std::string sidebar_change_stats_text(
const acecode::tui::SidebarFileChange& change) {
std::string out;
if (change.additions > 0) {
out += "+" + std::to_string(change.additions);
}
if (change.deletions > 0) {
if (!out.empty()) {
out += " ";
}
out += "-" + std::to_string(change.deletions);
}
return out.empty() ? std::string("0") : out;
}
static Element render_sidebar_change_row(
const acecode::tui::SidebarFileChange& change,
int content_width) {
const std::string stats_text = sidebar_change_stats_text(change);
const int file_width =
std::max(1, content_width - 2 - static_cast<int>(stats_text.size()) - 1);
Elements stats_parts;
if (change.additions > 0) {
stats_parts.push_back(
text("+" + std::to_string(change.additions)) |
color(Color::GreenLight));
}
if (change.deletions > 0) {
if (!stats_parts.empty()) {
stats_parts.push_back(text(" "));
}
stats_parts.push_back(
text("-" + std::to_string(change.deletions)) |
color(Color::RedLight));
}
if (stats_parts.empty()) {
stats_parts.push_back(text("0") | color(Color::GrayDark) | dim);
}
return hbox({
text(" ") | color(Color::GrayDark),
text(truncate_cells_middle_ascii(
change.display_file.empty() ? change.file : change.display_file,
file_width)) |
color(Color::GrayLight),
filler(),
hbox(std::move(stats_parts)),
});
}
static Element queued_badge() {
return text(" QUEUED ") | bold | color(Color::White) |
bgcolor(Color::RGB(128, 96, 0));
}
static std::string repeat_utf8_glyph(const char* glyph, int count) {
std::string out;
if (count <= 0) {
return out;
}
const std::string g(glyph);
out.reserve(g.size() * static_cast<std::size_t>(count));
for (int i = 0; i < count; ++i) {
out += g;
}
return out;
}
static Color token_progress_color(int percent) {
if (percent <= 0) {
return Color::GrayDark;
}
if (percent > 90) {
return Color::RedLight;
}
if (percent >= 60) {
return Color::Yellow;
}
return Color::GreenLight;
}
static Element render_token_usage_chip(const acecode::TuiState& state) {
if (state.token_status.empty()) {
return text("");
}
constexpr int kBarCells = 10;
constexpr const char* kFilled = "\xE2\x96\x88";
constexpr const char* kEmpty = "\xE2\x96\x91";
const int percent = std::clamp(state.token_percent, 0, 100);
const int filled = percent <= 0 ? 0 : std::clamp((percent + 9) / 10, 1, kBarCells);
const int empty = kBarCells - filled;
const Color progress_color = token_progress_color(percent);
return hbox({
text(" " + state.token_status + " ") | dim | color(Color::CyanLight),
text("[") | dim | color(Color::GrayDark),
text(repeat_utf8_glyph(kFilled, filled)) | color(progress_color),
text(repeat_utf8_glyph(kEmpty, empty)) | dim | color(Color::GrayDark),
text("] ") | dim | color(Color::GrayDark),
text(std::to_string(percent) + "% ") | dim | color(progress_color),
});
}
static Element render_pending_queue_block(const acecode::TuiState& state,
int available_width) {
if (state.pending_queue.empty()) {
return emptyElement();
}
constexpr std::size_t kMaxVisibleQueuedPrompts = 3;
constexpr int kBadgeCells = 8;
const int prompt_width =
std::max(10, available_width - kBadgeCells - 5);
const std::size_t visible =
std::min(kMaxVisibleQueuedPrompts, state.pending_queue.size());
Elements rows;
const std::size_t hidden =
state.pending_queue.size() > visible
? state.pending_queue.size() - visible
: 0;
if (hidden > 0) {
rows.push_back(
text(" +" + std::to_string(hidden) + " more queued") |
color(Color::GrayDark) | dim);
}
const std::size_t start = state.pending_queue.size() - visible;
for (std::size_t i = start; i < state.pending_queue.size(); ++i) {
const std::string preview = collapse_sidebar_title_whitespace(
state.pending_queue[i]);
rows.push_back(hbox({
text(" "),
queued_badge(),
text(" "),
text(truncate_cells_middle_ascii(preview, prompt_width)) |
color(Color::White),
}));
}
return vbox(std::move(rows));
}
static std::vector<std::string> sidebar_title_lines(const std::string& title,
int max_width) {
max_width = std::max(1, max_width);
const auto glyphs = ftxui::Utf8ToGlyphs(title);
std::vector<std::string> lines;
std::size_t index = 0;
for (int line_index = 0; line_index < 2 && index < glyphs.size(); ++line_index) {
std::string line;
int width = 0;
while (index < glyphs.size()) {
const auto& glyph = glyphs[index];
const int glyph_width = std::max(0, ftxui::string_width(glyph));
if (width > 0 && width + glyph_width > max_width) {
break;
}
if (width == 0 && glyph_width > max_width) {
line += glyph;
++index;
break;
}
line += glyph;
width += glyph_width;
++index;
}
trim_ascii_space_suffix(line);
lines.push_back(std::move(line));
while (index < glyphs.size() && glyphs[index] == " ") {
++index;
}
}
if (lines.empty()) {
lines.push_back("New session");
}
if (index < glyphs.size()) {
if (lines.size() == 1) {
lines.push_back("");
}
const int body_width = std::max(0, max_width - 3);
lines[1] = truncate_cells_prefix(lines[1], body_width);
trim_ascii_space_suffix(lines[1]);
lines[1] += "...";
}
return lines;
}
static Element render_regular_sidebar(const acecode::TuiState& state,
const std::string& version_str,
const std::string& cwd_display,
int sidebar_width) {
const int content_width = std::max(1, sidebar_width - 2);
Elements top_rows;
for (const auto& line : sidebar_title_lines(first_user_message_title(state),
content_width)) {
top_rows.push_back(text(line) | bold | color(Color::White));
}
const auto file_changes =
acecode::tui::collect_sidebar_file_changes(state.conversation,
cwd_display);
top_rows.push_back(text(""));
top_rows.push_back(sidebar_section_header(
"Files Changed", static_cast<int>(file_changes.size())));
constexpr std::size_t kMaxSidebarFiles = 5;
const std::size_t shown_files =
std::min(kMaxSidebarFiles, file_changes.size());
for (std::size_t i = 0; i < shown_files; ++i) {
top_rows.push_back(
render_sidebar_change_row(file_changes[i], content_width));
}
if (file_changes.size() > shown_files) {
top_rows.push_back(
text(" +" + std::to_string(file_changes.size() - shown_files) +
" more") |
color(Color::GrayDark) | dim);
}
Elements bottom_rows;
const bool show_bash_task =
state.tool_running && state.tool_progress.tool_name == "bash";
if (show_bash_task) {
bottom_rows.push_back(sidebar_section_header("Background Tasks", 1));
std::string command = state.tool_progress.command_preview.empty()
? std::string("bash")
: state.tool_progress.command_preview;
bottom_rows.push_back(
text(" " + truncate_cells_middle_ascii(command,
std::max(1, content_width - 2))) |
color(Color::GrayLight));
bottom_rows.push_back(text(""));
}
bottom_rows.push_back(paragraph(version_str) | color(Color::GrayLight) | dim);
if (!state.update_notice.empty()) {
bottom_rows.push_back(paragraph(state.update_notice) |
color(Color::YellowLight));
}
if (!state.status_line.empty()) {
bottom_rows.push_back(paragraph(state.status_line) | color(Color::White));
}
if (!cwd_display.empty()) {
bottom_rows.push_back(paragraph(cwd_display) | color(Color::CyanLight) | dim);
}
return hbox({
text(" "),
vbox({
vbox(std::move(top_rows)),
filler(),
vbox(std::move(bottom_rows)),
}) | flex,
text(" "),
}) | size(WIDTH, EQUAL, sidebar_width) |
bgcolor(Color::RGB(18, 18, 20));
}
static Element render_tool_result_lines_preserving_breaks(
const std::string& display_content) {
Elements lines;
size_t pos = 0;
while (pos <= display_content.size()) {
const size_t nl = display_content.find('\n', pos);
const std::string line = (nl == std::string::npos)
? display_content.substr(pos)
: display_content.substr(pos, nl - pos);
Element line_el = line.empty() ? text(" ") : paragraph(line);
lines.push_back(line_el | color(Color::GrayLight) | dim);
if (nl == std::string::npos) break;
pos = nl + 1;
}
return vbox(std::move(lines));
}
bool is_space_glyph(const std::string& glyph) {
return glyph == " " || glyph == "\t";
}
bool is_narrow_glyph(const std::string& glyph) {
return ftxui::string_width(glyph) == 1;
}
bool is_opening_cjk_punctuation(const std::string& glyph) {
static constexpr std::array<std::string_view, 8> kOpening = {
"(", "《", "「", "【", "‘", "“", "〈", "『"
};
for (const auto& candidate : kOpening) {
if (glyph == candidate) {
return true;
}
}
return false;
}
bool is_closing_cjk_punctuation(const std::string& glyph) {
static constexpr std::array<std::string_view, 15> kClosing = {
",", "。", "!", "?", ";", ":", "、", ")",
"》", "」", "】", "’", "”", "〉", "』"
};
for (const auto& candidate : kClosing) {
if (glyph == candidate) {
return true;
}
}
return false;
}
void flush_ascii_run(std::string* ascii_run,
std::string* pending_prefix,
std::vector<std::string>* output) {
if (ascii_run->empty()) {
return;
}
std::string token = std::move(*ascii_run);
ascii_run->clear();
if (!pending_prefix->empty()) {
token = std::move(*pending_prefix) + token;
pending_prefix->clear();
}
output->push_back(std::move(token));
}
std::vector<std::string> tokenize_wrapped_input(const std::string& text) {
std::vector<std::string> tokens;
std::string ascii_run;
std::string pending_prefix;
for (const auto& glyph : ftxui::Utf8ToGlyphs(text)) {
if (glyph.empty()) {
continue;
}
if (is_space_glyph(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!tokens.empty()) {
tokens.back() += " ";
}
continue;
}
if (is_opening_cjk_punctuation(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
pending_prefix += glyph;
continue;
}
if (is_closing_cjk_punctuation(glyph)) {
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!tokens.empty()) {
tokens.back() += glyph;
} else if (!pending_prefix.empty()) {
pending_prefix += glyph;
} else {
tokens.push_back(glyph);
}
continue;
}
if (is_narrow_glyph(glyph)) {
ascii_run += glyph;
continue;
}
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
std::string token = glyph;
if (!pending_prefix.empty()) {
token = std::move(pending_prefix) + token;
pending_prefix.clear();
}
tokens.push_back(std::move(token));
}
flush_ascii_run(&ascii_run, &pending_prefix, &tokens);
if (!pending_prefix.empty()) {
if (!tokens.empty()) {
tokens.back() += pending_prefix;
} else {
tokens.push_back(std::move(pending_prefix));
}
}
return tokens;
}
Element render_wrapped_input_text(const std::string& input_value, size_t cursor_bytes) {
if (cursor_bytes > input_value.size()) cursor_bytes = input_value.size();
// Split input into head/cursor_glyph/tail so the caret block can be drawn
// over the glyph under the caret (or a space when the caret sits at end).
std::string head = input_value.substr(0, cursor_bytes);
std::string cursor_glyph;
std::string tail;
if (cursor_bytes < input_value.size()) {
size_t next = cursor_bytes + 1;
while (next < input_value.size() &&
(static_cast<unsigned char>(input_value[next]) & 0xC0) == 0x80) {
next++;
}
cursor_glyph = input_value.substr(cursor_bytes, next - cursor_bytes);
tail = input_value.substr(next);
}
auto tokens_head = tokenize_wrapped_input(head);
auto tokens_tail = tokenize_wrapped_input(tail);
auto cursor_elem = ftxui::text(cursor_glyph.empty() ? std::string(" ") : cursor_glyph)
| focusCursorBlock;
if (tokens_head.empty() && tokens_tail.empty()) {
return cursor_elem;
}
Elements parts;
parts.reserve(tokens_head.size() + tokens_tail.size() + 1);
// Emit all but the last head token as standalone flex items.
for (size_t i = 0; i + 1 < tokens_head.size(); ++i) {
parts.push_back(ftxui::text(std::move(tokens_head[i])));
}
// Fuse (last_head_token, cursor_elem, first_tail_token) into one hbox so
// the caret never lands at a natural wrap boundary.
Elements compound;
if (!tokens_head.empty()) {
compound.push_back(ftxui::text(std::move(tokens_head.back())));
}
compound.push_back(cursor_elem);
size_t tail_start = 0;
if (!tokens_tail.empty()) {
compound.push_back(ftxui::text(std::move(tokens_tail[0])));
tail_start = 1;
}
parts.push_back(hbox(std::move(compound)));
for (size_t i = tail_start; i < tokens_tail.size(); ++i) {
parts.push_back(ftxui::text(std::move(tokens_tail[i])));
}
static const auto config = FlexboxConfig().SetGap(0, 0);
return flexbox(std::move(parts), config);
}
} // namespace
// ---- Get current working directory ----
static std::string get_cwd() {
#ifdef _WIN32
char buf[MAX_PATH];
if (_getcwd(buf, sizeof(buf))) return std::string(buf);
#else
char buf[4096];
if (getcwd(buf, sizeof(buf))) return std::string(buf);
#endif
return ".";
}
static std::string get_executable_dir_from_argv(int argc, char* argv[]) {
if (argc <= 0 || !argv[0]) return "";
std::error_code ec;
std::filesystem::path exe(argv[0]);
std::filesystem::path abs = std::filesystem::weakly_canonical(exe, ec);
if (!ec) return abs.parent_path().string();
return exe.parent_path().string();
}
static void seed_default_skills_if_first_initialization(const std::string& argv0_dir) {
bool first_initialization = acecode::consume_acecode_home_created_by_process();
auto result = acecode::install_default_global_skills_on_first_initialization(
std::filesystem::path(acecode::get_acecode_dir()),
argv0_dir,
first_initialization);
if (!result.attempted) return;
size_t installed = 0;
size_t skipped = 0;
size_t errors = 0;
for (const auto& outcome : result.outcomes) {
if (outcome.result == "installed") ++installed;
else if (outcome.result == "skipped") ++skipped;
else ++errors;
}
if (!result.error.empty()) {
LOG_WARN("[skills] Default skill seeding issue: " + result.error);
}
LOG_INFO("[skills] Default skill seeding attempted: installed=" +
std::to_string(installed) + " skipped=" + std::to_string(skipped) +
" errors=" + std::to_string(errors));
}
static void write_terminal_control_sequence(std::string_view seq) {
#ifdef _WIN32
auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD out_mode = 0;
const bool restore_mode =
stdout_handle != INVALID_HANDLE_VALUE &&
GetConsoleMode(stdout_handle, &out_mode);
if (!restore_mode) {
return;
}
constexpr DWORD enable_virtual_terminal_processing = 0x0004;
constexpr DWORD disable_newline_auto_return = 0x0008;
SetConsoleMode(stdout_handle,
out_mode | enable_virtual_terminal_processing |
disable_newline_auto_return);
#endif
std::cout.write(seq.data(), static_cast<std::streamsize>(seq.size()));
std::cout.flush();
#ifdef _WIN32
SetConsoleMode(stdout_handle, out_mode);
#endif
}
static void set_ftxui_full_repaint_mode(bool enabled) {
#ifdef _WIN32
_putenv_s("ACECODE_FTXUI_FULL_REPAINT", enabled ? "1" : "0");
#else
if (enabled) {
setenv("ACECODE_FTXUI_FULL_REPAINT", "1", 1);
} else {
unsetenv("ACECODE_FTXUI_FULL_REPAINT");
}
#endif
}
// ---- Reset terminal cursor visibility on exit ----
static void reset_cursor() {
// DECTCEM: show cursor (ESC [ ? 25 h)
write_terminal_control_sequence("\033[?25h");
}
static void flush_terminal_input_buffer() {
#ifdef _WIN32
auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
if (stdin_handle == INVALID_HANDLE_VALUE) {
return;
}
FlushConsoleInputBuffer(stdin_handle);
#else
if (isatty(STDIN_FILENO)) {
tcflush(STDIN_FILENO, TCIFLUSH);
}
#endif
}
#ifndef ACECODE_TUI_INPUT_TRACE
#define ACECODE_TUI_INPUT_TRACE 0
#endif
#if ACECODE_TUI_INPUT_TRACE
static std::string box_for_log(const Box& box) {
return "[" + std::to_string(box.x_min) + "," +
std::to_string(box.y_min) + "]-[" +
std::to_string(box.x_max) + "," +
std::to_string(box.y_max) + "]";
}
static std::string event_for_log(const Event& event) {
if (event.is_character()) {
return "Event::Character(bytes=" +
std::to_string(event.character().size()) + ")";
}
return event.DebugString();
}
static std::string drag_phase_for_log(acecode::drag_scroll::Phase phase) {
switch (phase) {
case acecode::drag_scroll::Phase::Idle:
return "Idle";
case acecode::drag_scroll::Phase::Dragging:
return "Dragging";
case acecode::drag_scroll::Phase::ScrollingUp:
return "ScrollingUp";
case acecode::drag_scroll::Phase::ScrollingDown:
return "ScrollingDown";
}
return "?";
}
static std::string scrollbar_geometry_for_log(
const acecode::tui::ChatScrollbarThumbGeometry& geometry) {
return "{max_top=" + std::to_string(geometry.max_top_row) +
" range2x=" + std::to_string(geometry.scroll_range_2x) +
" thumb_size2x=" + std::to_string(geometry.thumb_size_2x) +
" thumb_top2x=" + std::to_string(geometry.thumb_top_2x) + "}";
}
#endif
// ---- Session finalization on exit ----
static SessionManager* g_session_manager = nullptr;
// Active FTXUI screen, used by signal / console-ctrl handlers to trigger a
// graceful Loop exit. Must be cleared before ScreenInteractive is destroyed
// so handlers can't dereference a dead object.
// App::Exit() is thread-safe (posts a task internally — see app.cpp:1063).
static std::atomic<ftxui::ScreenInteractive*> g_active_screen{nullptr};
static void finalize_session_atexit() {
if (g_session_manager) {
g_session_manager->finalize();
auto sid = g_session_manager->current_session_id();
if (!sid.empty()) {
std::cerr << "\nacecode: session " << sid
<< " saved. Resume with: acecode --resume " << sid << std::endl;
}
}
// Best-effort: hand the window title back to the parent shell. Not
// strictly async-signal-safe but consistent with the existing finalize
// path which already uses iostreams.
clear_terminal_title();
}
#ifdef _WIN32
static BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) {
// Normal Ctrl+C is handled through stdin once ENABLE_PROCESSED_INPUT is
// cleared after FTXUI installs its terminal mode. This handler remains as
// a fallback for hosts that still deliver CTRL_C_EVENT, and for
// Ctrl+Break/close events where graceful shutdown is more important than
// prompting.
auto* s = g_active_screen.load(std::memory_order_acquire);
if (ctrl_type == CTRL_C_EVENT) {
if (s) {
s->PostEvent(ftxui::Event::CtrlC);
return TRUE;
}
finalize_session_atexit();
return FALSE;
}
if (ctrl_type == CTRL_BREAK_EVENT || ctrl_type == CTRL_CLOSE_EVENT) {
// Break / 关窗:明确退出意图,直接走 FTXUI 优雅退出 —— Loop 返回后
// ScreenInteractive 析构跑 on_exit_functions,把 alt-screen /
// mouse tracking / Windows console mode 还原回去。返回 FALSE 会让
// 默认 handler TerminateProcess(),终端会留在 mouse-tracking 开
// 的状态,父 shell 收到鼠标事件原样喷成乱码字节。
if (s) {
s->Exit();
return TRUE;
}
finalize_session_atexit();
return FALSE;
}
return FALSE;
}
static void prepare_windows_ctrl_c_handling_after_ftxui_install() {
auto stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD in_mode = 0;
if (stdin_handle != INVALID_HANDLE_VALUE &&
GetConsoleMode(stdin_handle, &in_mode)) {
// FTXUI preserves ENABLE_PROCESSED_INPUT from the original console
// mode. When it stays enabled, Windows turns Ctrl+C into a console
// control event instead of a stdin byte, and FTXUI's SIGINT handler can
// exit before our Event::CtrlC branch gets a chance to show the prompt.
SetConsoleMode(stdin_handle, in_mode & ~ENABLE_PROCESSED_INPUT);
}
// Re-register after FTXUI's Loop/PreMain installs its own signal handling
// so this handler gets first chance at CTRL_BREAK_EVENT / CTRL_CLOSE_EVENT
// and any CTRL_C_EVENT fallback.
SetConsoleCtrlHandler(console_ctrl_handler, FALSE);
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
}
#else
#include <csignal>
static void signal_handler(int /*sig*/) {
// FTXUI overrides SIGINT/SIGTERM during Loop() (app.cpp:575) so this only
// fires before Loop starts or after it returns — terminal isn't in the
// raw/alt-screen state yet, so _exit is safe.
finalize_session_atexit();
_exit(1);
}
#endif
#ifdef _WIN32
static int max_int(int a, int b) {
return a > b ? a : b;
}
static std::string ptr_to_hex(const void* ptr) {
std::ostringstream oss;