-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmain.py
More file actions
1855 lines (1648 loc) · 64.1 KB
/
main.py
File metadata and controls
1855 lines (1648 loc) · 64.1 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
"""LLM 驱动的 ReAct 智能体的 CLI 入口点。"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import textwrap
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List
from dotenv import load_dotenv
from dm_agent import (
CriticAgent,
LLMError,
ReactAgent,
Tool,
create_llm_client,
default_tools,
PROVIDER_DEFAULTS,
)
from dm_agent.mcp import MCPManager, load_mcp_config
from dm_agent.skills import SkillManager
from dm_agent.tracing import TraceWriter
try:
from rich import box
from rich.console import Console, Group
from rich.padding import Padding
from rich.panel import Panel
from rich.prompt import Prompt
from rich.table import Table
from rich.text import Text
RICH_AVAILABLE = True
RICH_CONSOLE = Console(highlight=False, soft_wrap=True)
except ImportError:
RICH_AVAILABLE = False
RICH_CONSOLE = None
# 尝试导入 colorama 用于彩色输出
try:
from colorama import Fore, Style, init as colorama_init
colorama_init(autoreset=True)
COLORS_AVAILABLE = True
except ImportError:
COLORS_AVAILABLE = False
# 如果没有 colorama,定义空的颜色常量
class Fore:
GREEN = ""
YELLOW = ""
RED = ""
CYAN = ""
MAGENTA = ""
BLUE = ""
WHITE = ""
class Style:
BRIGHT = ""
DIM = ""
RESET_ALL = ""
@dataclass
class Config:
"""运行时配置"""
api_key: str
provider: str = "deepseek"
model: str = "deepseek-chat"
base_url: str = "https://api.deepseek.com"
max_steps: int = 100
temperature: float = 0.7
show_steps: bool = False
enable_reflexion: bool = False
max_trials: int = 3
enable_critic: bool = False
enable_adaptive_replanning: bool = False
max_replans: int = -1
enable_repeated_failure_policy_experiment: bool = False
enable_evolution: bool = False
# 配置文件路径
CONFIG_FILE = os.path.join(os.path.dirname(__file__), "config.json")
class UI:
"""Terminal UI layer with Rich rendering and a colorama fallback."""
WIDTH = 88
RICH_STYLES = {
"ok": "bold white on green",
"error": "bold white on red",
"warn": "bold black on yellow",
"info": "bold white on blue",
"run": "bold white on magenta",
}
RICH_LABELS = {
"ok": "DONE",
"error": "ERROR",
"warn": "WARN",
"info": "INFO",
"run": "RUN",
}
@staticmethod
def rich_enabled() -> bool:
return RICH_AVAILABLE and RICH_CONSOLE is not None
@staticmethod
def clear() -> None:
if UI.rich_enabled():
RICH_CONSOLE.clear()
return
os.system("cls" if os.name == "nt" else "clear")
@staticmethod
def width() -> int:
return max(72, min(UI.WIDTH, shutil.get_terminal_size((UI.WIDTH, 20)).columns))
@staticmethod
def paint(text: str, color: str = "", *, bright: bool = False, dim: bool = False) -> str:
style = ""
if bright:
style += Style.BRIGHT
if dim:
style += getattr(Style, "DIM", "")
return f"{style}{color}{text}{Style.RESET_ALL}"
@staticmethod
def rule(label: str = "", *, color: str = Fore.CYAN) -> None:
if UI.rich_enabled():
title = Text(f" {label} ", style="bright_black") if label else ""
RICH_CONSOLE.rule(title, style="bright_black")
return
width = UI.width()
if label:
prefix = f" {label} "
line = prefix + "-" * max(width - len(prefix), 0)
else:
line = "-" * width
print(UI.paint(line, color, dim=not label))
@staticmethod
def banner(title: str, subtitle: str = "") -> None:
if UI.rich_enabled():
heading = Text()
if title == "DM-Code-Agent":
heading.append("DM", style="bold cyan")
heading.append("-Code-Agent", style="bold white")
else:
heading.append(title, style="bold white")
body: Group | Text
if subtitle:
caption = Text(subtitle, style="bright_black")
body = Group(heading, Text(""), caption)
else:
body = heading
RICH_CONSOLE.print(
Panel(
body,
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
expand=True,
subtitle=(
Text("trace tools skills memory", style="bright_black")
if title == "DM-Code-Agent"
else None
),
)
)
return
print()
print(UI.paint(title, Fore.GREEN, bright=True))
if subtitle:
print(" " + UI.paint(subtitle, Fore.WHITE, dim=True))
print()
@staticmethod
def section(title: str, subtitle: str = "") -> None:
if UI.rich_enabled():
text = Text()
text.append(title, style="bold white")
if subtitle:
text.append("\n")
text.append(subtitle, style="bright_black")
RICH_CONSOLE.print(Padding(text, (1, 0, 0, 0)))
return
print()
print(UI.paint(title, Fore.CYAN, bright=True))
if subtitle:
for line in UI.wrap(subtitle, width=UI.width() - 4):
print(" " + UI.paint(line, Fore.WHITE, dim=True))
@staticmethod
def panel(title: str, body: str = "", *, color: str = Fore.CYAN) -> None:
if UI.rich_enabled():
style = UI._rich_color(color)
RICH_CONSOLE.print(
Panel(
UI._rich_wrapped_text(str(body), width=UI.width() - 10),
title=Text(f" {title} ", style=f"bold {style}"),
title_align="left",
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
expand=True,
)
)
return
print()
print(UI.paint(title, color, bright=True))
if body:
for raw_line in str(body).splitlines() or [""]:
wrapped = UI.wrap(raw_line, width=UI.width() - 4) or [""]
for line in wrapped:
print(" " + line)
@staticmethod
def wrap(text: str, *, width: int | None = None) -> List[str]:
return textwrap.wrap(
str(text),
width=width or UI.width() - 4,
replace_whitespace=False,
drop_whitespace=False,
)
@staticmethod
def _rich_wrapped_text(text: str, *, width: int) -> Text:
wrapped = Text()
target_width = max(36, width)
lines: List[str] = []
for raw_line in str(text).splitlines() or [""]:
if raw_line.strip():
lines.extend(UI.wrap(raw_line, width=target_width) or [""])
else:
lines.append("")
for index, line in enumerate(lines):
if index:
wrapped.append("\n")
wrapped.append(line)
return wrapped
@staticmethod
def status(kind: str, message: str, detail: str = "") -> None:
if UI.rich_enabled():
style = UI.RICH_STYLES.get(kind, UI.RICH_STYLES["info"])
label = UI.RICH_LABELS.get(kind, kind.upper())
text = Text()
text.append(f" {label:<5} ", style=style)
text.append(" ")
text.append(message, style="white")
if detail:
text.append(" ")
text.append(detail, style="bright_black")
RICH_CONSOLE.print(Padding(text, (0, 0, 0, 1)))
return
palette = {
"ok": (Fore.GREEN, "ok"),
"error": (Fore.RED, "err"),
"warn": (Fore.YELLOW, "warn"),
"info": (Fore.CYAN, "info"),
"run": (Fore.MAGENTA, "run"),
}
color, icon = palette.get(kind, palette["info"])
line = f"{UI.paint(icon.ljust(5), color, bright=True)} {message}"
if detail:
line += UI.paint(f" {detail}", Fore.WHITE, dim=True)
print(line)
@staticmethod
def key_values(title: str, rows: List[tuple[str, Any]]) -> None:
if UI.rich_enabled():
table = Table.grid(padding=(0, 3))
table.add_column(style="bright_black", no_wrap=True)
table.add_column(style="bold white")
for key, value in rows:
table.add_row(str(key), str(value))
RICH_CONSOLE.print(
Panel(
table,
title=Text(f" {title} ", style="bold cyan"),
title_align="left",
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
)
)
return
UI.section(title)
key_width = max((len(key) for key, _ in rows), default=0)
for key, value in rows:
print(
f" {UI.paint(key.ljust(key_width), Fore.WHITE, dim=True)} "
f"{UI.paint(str(value), Fore.YELLOW)}"
)
@staticmethod
def menu(items: List[tuple[str, str]]) -> None:
if UI.rich_enabled():
table = Table.grid(expand=True, padding=(0, 2))
table.add_column(justify="right", no_wrap=True, width=5)
table.add_column(style="bold white", no_wrap=True, width=18)
table.add_column(style="bright_black", ratio=1)
for index, (title, description) in enumerate(items, start=1):
badge = Text(f" {index} ", style="bold black on cyan")
table.add_row(badge, title, description)
RICH_CONSOLE.print(
Panel(
table,
title=Text(" 主菜单 ", style="bold white"),
title_align="left",
subtitle=Text("输入编号选择操作", style="bright_black"),
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
)
)
return
UI.section("主菜单", "输入编号选择一个操作")
for index, (title, description) in enumerate(items, start=1):
badge = UI.paint(f"[{index}]", Fore.GREEN, bright=True)
name = UI.paint(title.ljust(14), Fore.WHITE, bright=True)
print(f" {badge} {name} {UI.paint(description, Fore.WHITE, dim=True)}")
print()
@staticmethod
def truncate(value: Any, limit: int = 220) -> str:
text = str(value)
if len(text) <= limit:
return text
return text[: max(limit - 3, 0)].rstrip() + "..."
@staticmethod
def ask(
prompt: str,
*,
choices: List[str] | None = None,
default: str | None = None,
show_choices: bool = True,
) -> str:
if UI.rich_enabled():
prompt_kwargs = {
"choices": choices,
"console": RICH_CONSOLE,
"show_choices": show_choices,
}
if default is not None:
prompt_kwargs["default"] = default
return Prompt.ask(Text(prompt, style="bold cyan"), **prompt_kwargs)
suffix = f" [{default}]" if default is not None else ""
return input(f"{UI.paint(prompt, Fore.CYAN)}{suffix}: ")
@staticmethod
def prompt_line(prompt: str, *, default: str = "") -> str:
if UI.rich_enabled():
return Prompt.ask(
Text(prompt, style="bold cyan"),
console=RICH_CONSOLE,
default=default,
show_default=False,
)
suffix = f" [{default}]" if default else ""
return input(f"{UI.paint(prompt, Fore.CYAN)}{suffix}: ")
@staticmethod
def pause(prompt: str = "按 Enter 返回") -> None:
UI.prompt_line(prompt, default="")
@staticmethod
def _rich_color(color: str) -> str:
if color == Fore.GREEN:
return "green"
if color == Fore.YELLOW:
return "yellow"
if color == Fore.RED:
return "red"
if color == Fore.MAGENTA:
return "magenta"
if color == Fore.BLUE:
return "blue"
return "cyan"
def configure_console_encoding() -> None:
"""Avoid crashes when Windows terminals cannot encode Unicode status symbols."""
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
try:
stream.reconfigure(errors="replace")
except Exception:
pass
def load_config_from_file() -> Dict[str, Any]:
"""从配置文件加载设置"""
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
UI.status("warn", "配置文件加载失败,使用默认设置", str(e))
return {}
def save_config_to_file(config: Config) -> None:
"""保存配置到文件"""
try:
config_data = {
"provider": config.provider,
"model": config.model,
"base_url": config.base_url,
"max_steps": config.max_steps,
"temperature": config.temperature,
"show_steps": config.show_steps,
"enable_reflexion": config.enable_reflexion,
"max_trials": config.max_trials,
"enable_critic": config.enable_critic,
"enable_adaptive_replanning": config.enable_adaptive_replanning,
"max_replans": config.max_replans,
"enable_repeated_failure_policy_experiment": (
config.enable_repeated_failure_policy_experiment
),
"enable_evolution": config.enable_evolution,
}
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(config_data, f, indent=2, ensure_ascii=False)
UI.status("ok", "配置已保存")
except Exception as e:
UI.status("error", "配置保存失败", str(e))
def get_api_key_for_provider(provider: str) -> str | None:
"""根据提供商获取对应的 API 密钥"""
provider_env_map = {
"deepseek": "DEEPSEEK_API_KEY",
"openai": "OPENAI_API_KEY",
"claude": "CLAUDE_API_KEY",
"gemini": "GEMINI_API_KEY",
}
env_var = provider_env_map.get(provider.lower())
return os.getenv(env_var) if env_var else None
def resolve_advanced_features(config: Config) -> Dict[str, bool]:
"""Return effective advanced feature switches for one agent run."""
adaptive_replanning = config.enable_adaptive_replanning or config.enable_evolution
repeated_failure_policy = (
config.enable_repeated_failure_policy_experiment or config.enable_evolution
)
return {
"reflexion": config.enable_reflexion,
"critic": config.enable_critic,
"adaptive_replanning": adaptive_replanning,
"repeated_failure_policy_experiment": repeated_failure_policy,
"evolution": config.enable_evolution,
}
def format_advanced_feature_status(config: Config) -> str:
"""Compact human-readable summary of advanced feature switches."""
advanced = resolve_advanced_features(config)
enabled = [
label
for key, label in [
("reflexion", "reflexion"),
("critic", "critic"),
("adaptive_replanning", "adaptive-replan"),
("repeated_failure_policy_experiment", "loop-break"),
("evolution", "evolution"),
]
if advanced[key]
]
return ", ".join(enabled) if enabled else "off"
def validate_feature_args(args: argparse.Namespace) -> str:
"""Validate default-off advanced feature CLI arguments."""
if args.max_trials < 1:
return "--max-trials must be at least 1."
if args.max_replans < -1:
return "--max-replans must be -1 or greater."
if (
args.enable_repeated_failure_policy_experiment
and not args.enable_adaptive_replanning
and not args.enable_evolution
):
return (
"--enable-repeated-failure-policy-experiment requires "
"--enable-adaptive-replanning or --enable-evolution."
)
return ""
def parse_args(argv: Any) -> argparse.Namespace:
# 先加载配置文件中的默认值
saved_config = load_config_from_file()
parser = argparse.ArgumentParser(description="运行基于 LLM 的 ReAct 智能体来完成任务描述。")
parser.add_argument("task", nargs="?", help="智能体要完成的自然语言任务。")
# 获取配置中的提供商或默认值
default_provider = saved_config.get("provider", "deepseek")
# 根据提供商获取对应的 API 密钥
default_api_key = get_api_key_for_provider(default_provider)
parser.add_argument(
"--api-key",
dest="api_key",
default=default_api_key,
help="API 密钥(默认使用环境变量)。",
)
parser.add_argument(
"--provider",
default=saved_config.get("provider", "deepseek"),
help="LLM 提供商 (deepseek/openai/claude/gemini,默认:deepseek)。",
)
parser.add_argument(
"--model",
default=saved_config.get("model", "deepseek-chat"),
help="模型标识符(默认根据提供商选择)。",
)
parser.add_argument(
"--base-url",
dest="base_url",
default=saved_config.get("base_url"),
help="API 基础 URL(可选,使用提供商默认值)。",
)
parser.add_argument(
"--max-steps",
type=int,
default=saved_config.get("max_steps", 100),
help="放弃前的最大推理/工具步骤数(默认:100)。",
)
parser.add_argument(
"--temperature",
type=float,
default=saved_config.get("temperature", 0.7),
help="模型的采样温度(默认:0.7)。",
)
parser.add_argument(
"--show-steps",
action="store_true",
default=saved_config.get("show_steps", False),
help="打印智能体执行的中间 ReAct 步骤。",
)
parser.add_argument(
"--enable-reflexion",
action="store_true",
default=saved_config.get("enable_reflexion", False),
help="启用失败后的 Reflexion 反思重试。默认关闭。",
)
parser.add_argument(
"--max-trials",
type=int,
default=saved_config.get("max_trials", 3),
help="启用 Reflexion 时最多尝试的轮数(默认:3)。",
)
parser.add_argument(
"--enable-critic",
action="store_true",
default=saved_config.get("enable_critic", False),
help="启用完成前 Critic 审查门禁。默认关闭。",
)
parser.add_argument(
"--enable-adaptive-replanning",
action="store_true",
default=saved_config.get("enable_adaptive_replanning", False),
help="启用基于失败信号的自适应重规划。默认关闭。",
)
parser.add_argument(
"--max-replans",
type=int,
default=saved_config.get("max_replans", -1),
help="自适应重规划最多触发次数;-1 表示不限(默认:-1)。",
)
parser.add_argument(
"--enable-repeated-failure-policy-experiment",
action="store_true",
default=saved_config.get("enable_repeated_failure_policy_experiment", False),
help="启用重复失败时的实验性跳出策略。默认关闭。",
)
parser.add_argument(
"--enable-evolution",
action="store_true",
default=saved_config.get("enable_evolution", False),
help="启用实验性进化恢复模式:自动打开自适应重规划和重复失败跳出策略。默认关闭。",
)
parser.add_argument(
"--interactive",
action="store_true",
help="启动交互式菜单模式。",
)
parser.add_argument(
"--trace",
type=Path,
help="将本次任务的结构化执行轨迹写入 JSONL 文件。",
)
parser.add_argument(
"--trace-llm-io",
action="store_true",
help="在 trace 中包含完整 LLM 输入/输出。仅建议在私有调试时启用。",
)
parser.add_argument(
"--report",
type=Path,
help="将本次任务的人类可读运行报告写入 Markdown 文件。",
)
return parser.parse_args(argv)
def print_separator(char: str = "=", length: int = 70) -> None:
"""打印分隔线"""
_ = (char, length)
UI.rule()
def print_header(text: str) -> None:
"""打印标题"""
UI.banner(text)
def print_welcome() -> None:
"""打印欢迎界面"""
UI.banner("DM-Code-Agent", "Local-first code agent with trace, tools, skills, and memory.")
# 显示配置文件状态
if os.path.exists(CONFIG_FILE):
UI.status("ok", "已加载配置文件", "config.json")
else:
UI.status("info", "使用默认配置", "max_steps=100 | temperature=0.7")
print()
def print_menu() -> None:
"""打印主菜单"""
UI.menu(
[
("执行新任务", "一次性运行一个代码维护任务"),
("多轮对话模式", "复用当前 agent 的短期上下文和本地记忆"),
("查看工具列表", "浏览文件、Shell、测试、MCP 等可用工具"),
("配置设置", "切换模型、温度、最大步骤和显示选项"),
("查看可用技能列表", "查看内置和自定义技能"),
("退出程序", "关闭 MCP 并返回终端"),
]
)
def show_tools(tools: List[Tool]) -> None:
"""显示可用工具列表"""
if UI.rich_enabled():
table = Table(
show_header=True,
header_style="bold white",
box=box.SIMPLE_HEAD,
border_style="bright_black",
pad_edge=False,
)
table.add_column("#", justify="right", style="cyan", no_wrap=True)
table.add_column("Tool", style="bold white", no_wrap=True)
table.add_column("Description", style="bright_black")
for idx, tool in enumerate(tools, start=1):
table.add_row(str(idx), tool.name, tool.description)
RICH_CONSOLE.print(
Panel(
table,
title=Text(f" 可用工具 ({len(tools)}) ", style="bold cyan"),
title_align="left",
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
)
)
return
UI.section("可用工具", f"{len(tools)} 个工具已加载")
for idx, tool in enumerate(tools, start=1):
print(
f" {UI.paint(f'{idx:>2}', Fore.GREEN, bright=True)} "
f"{UI.paint(tool.name, Fore.WHITE, bright=True)}"
)
for line in UI.wrap(tool.description, width=UI.width() - 8):
print(f" {UI.paint(line, Fore.WHITE, dim=True)}")
print()
def show_skills(skill_manager: SkillManager) -> None:
"""显示可用技能列表"""
skills_info = skill_manager.get_all_skill_info()
if UI.rich_enabled():
table = Table(
show_header=True,
header_style="bold white",
box=box.SIMPLE_HEAD,
border_style="bright_black",
pad_edge=False,
)
table.add_column("#", justify="right", style="cyan", no_wrap=True)
table.add_column("Skill", no_wrap=True)
table.add_column("Source", style="yellow", no_wrap=True)
table.add_column("Tools", justify="right", style="magenta", no_wrap=True)
table.add_column("Description", style="bright_black")
for idx, info in enumerate(skills_info, start=1):
source = "内置" if info["is_builtin"] else "自定义"
skill_name = Text(str(info["display_name"]), style="bold white")
if info["is_active"]:
skill_name.append(" ACTIVE", style="bold green")
table.add_row(
str(idx),
skill_name,
source,
str(info["tools_count"]),
info["description"],
)
body = table if skills_info else Text("暂无可用技能", style="yellow")
RICH_CONSOLE.print(
Panel(
body,
title=Text(f" 可用技能 ({len(skills_info)}) ", style="bold cyan"),
title_align="left",
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
)
)
return
UI.section("可用技能", f"{len(skills_info)} 个技能已发现")
if not skills_info:
UI.status("warn", "暂无可用技能")
else:
for idx, info in enumerate(skills_info, start=1):
status = UI.paint("active", Fore.GREEN, bright=True) if info["is_active"] else ""
source = "内置" if info["is_builtin"] else "自定义"
header = (
f" {UI.paint(f'{idx:>2}', Fore.GREEN, bright=True)} "
f"{UI.paint(info['display_name'], Fore.WHITE, bright=True)}"
)
print(f"{header} {status}".rstrip())
print(
f" {UI.paint(info['name'], Fore.YELLOW)} | {source} | "
f"v{info['version']} | {info['tools_count']} tools"
)
for line in UI.wrap(info["description"], width=UI.width() - 8):
print(f" {UI.paint(line, Fore.WHITE, dim=True)}")
print(
f" {UI.paint('关键词', Fore.WHITE, dim=True)} "
f"{', '.join(info['keywords'][:8])}"
f"{'...' if len(info['keywords']) > 8 else ''}"
)
print()
print()
def ask_bool_setting(label: str, current: bool) -> bool:
value = UI.ask(label, choices=["y", "n"], default="y" if current else "n").strip().lower()
if value in {"y", "yes", "是"}:
return True
if value in {"n", "no", "否"}:
return False
return current
def configure_settings(config: Config) -> None:
"""配置设置"""
UI.key_values(
"当前配置",
[
("Provider", config.provider),
("Model", config.model),
("Base URL", config.base_url),
("Max steps", config.max_steps),
("Temperature", config.temperature),
("Show steps", "是" if config.show_steps else "否"),
("Advanced", format_advanced_feature_status(config)),
("Reflexion max trials", config.max_trials),
("Max replans", config.max_replans),
],
)
UI.status("info", "选择要修改的设置", "直接回车跳过")
print()
config_changed = False
# 修改提供商
provider_input = (
UI.ask(
"LLM 提供商",
choices=["deepseek", "openai", "claude", "gemini"],
default=config.provider,
)
.strip()
.lower()
)
if provider_input and provider_input in ["deepseek", "openai", "claude", "gemini"]:
if provider_input != config.provider:
# 尝试获取新提供商的 API 密钥
new_api_key = get_api_key_for_provider(provider_input)
if not new_api_key:
UI.status("error", f"未找到 {provider_input.upper()}_API_KEY 环境变量")
UI.status("warn", f"请在 .env 文件中配置 {provider_input.upper()}_API_KEY")
else:
config.provider = provider_input
config.api_key = new_api_key # 更新 API 密钥
# 自动更新默认模型和 base_url
defaults = PROVIDER_DEFAULTS.get(provider_input, {})
config.model = defaults.get("model", config.model)
config.base_url = defaults.get("base_url", config.base_url)
config_changed = True
UI.status("ok", f"已更新提供商为 {provider_input}", "模型和 URL 已自动调整")
elif provider_input and provider_input not in ["deepseek", "openai", "claude", "gemini"]:
UI.status("error", "无效的提供商")
# 修改模型
model_input = UI.ask("模型名称", default=config.model).strip()
if model_input and model_input != config.model:
config.model = model_input
config_changed = True
UI.status("ok", f"已更新模型为 {model_input}")
# 修改 Base URL
base_url_input = UI.ask("Base URL", default=config.base_url).strip()
if base_url_input and base_url_input != config.base_url:
config.base_url = base_url_input
config_changed = True
UI.status("ok", f"已更新 Base URL 为 {base_url_input}")
# 修改最大步骤数
try:
max_steps_input = UI.ask("最大步骤数", default=str(config.max_steps)).strip()
if max_steps_input:
new_max_steps = int(max_steps_input)
if new_max_steps > 0:
if new_max_steps != config.max_steps:
config.max_steps = new_max_steps
config_changed = True
UI.status("ok", f"已更新最大步骤数为 {new_max_steps}")
else:
UI.status("error", "最大步骤数必须大于 0")
except ValueError:
UI.status("error", "无效的数字")
# 修改温度
try:
temp_input = UI.ask("温度 (0.0-2.0)", default=str(config.temperature)).strip()
if temp_input:
new_temp = float(temp_input)
if 0.0 <= new_temp <= 2.0:
if new_temp != config.temperature:
config.temperature = new_temp
config_changed = True
UI.status("ok", f"已更新温度为 {new_temp}")
else:
UI.status("error", "温度必须在 0.0 到 2.0 之间")
except ValueError:
UI.status("error", "无效的数字")
# 修改显示步骤
new_show_steps = ask_bool_setting("显示步骤", config.show_steps)
if new_show_steps != config.show_steps:
config.show_steps = new_show_steps
config_changed = True
UI.status("ok", "已启用显示步骤" if config.show_steps else "已禁用显示步骤")
UI.section(
"高级功能",
"这些能力会增加模型调用或改变恢复策略;默认关闭,建议按任务显式启用。",
)
new_reflexion = ask_bool_setting("启用 Reflexion 反思重试", config.enable_reflexion)
if new_reflexion != config.enable_reflexion:
config.enable_reflexion = new_reflexion
config_changed = True
if config.enable_reflexion:
try:
max_trials_input = UI.ask("反思最大尝试轮数", default=str(config.max_trials)).strip()
if max_trials_input:
new_max_trials = int(max_trials_input)
if new_max_trials >= 1:
if new_max_trials != config.max_trials:
config.max_trials = new_max_trials
config_changed = True
else:
UI.status("error", "反思最大尝试轮数必须至少为 1")
except ValueError:
UI.status("error", "无效的数字")
new_critic = ask_bool_setting("启用 Critic 完成审查", config.enable_critic)
if new_critic != config.enable_critic:
config.enable_critic = new_critic
config_changed = True
new_adaptive = ask_bool_setting("启用自适应重规划", config.enable_adaptive_replanning)
if new_adaptive != config.enable_adaptive_replanning:
config.enable_adaptive_replanning = new_adaptive
config_changed = True
if config.enable_adaptive_replanning:
try:
max_replans_input = UI.ask(
"最大重规划次数 (-1 表示不限)", default=str(config.max_replans)
).strip()
if max_replans_input:
new_max_replans = int(max_replans_input)
if new_max_replans >= -1:
if new_max_replans != config.max_replans:
config.max_replans = new_max_replans
config_changed = True
else:
UI.status("error", "最大重规划次数必须为 -1 或更大")
except ValueError:
UI.status("error", "无效的数字")
new_loop_break = ask_bool_setting(
"启用重复失败跳出实验", config.enable_repeated_failure_policy_experiment
)
if new_loop_break != config.enable_repeated_failure_policy_experiment:
config.enable_repeated_failure_policy_experiment = new_loop_break
config_changed = True
if config.enable_repeated_failure_policy_experiment and not config.enable_adaptive_replanning:
config.enable_adaptive_replanning = True
config_changed = True
UI.status("info", "已同步启用自适应重规划", "重复失败跳出实验依赖重规划")
new_evolution = ask_bool_setting("启用进化恢复模式", config.enable_evolution)
if new_evolution != config.enable_evolution:
config.enable_evolution = new_evolution
config_changed = True
if config.enable_evolution and not config.enable_adaptive_replanning:
UI.status("info", "进化恢复会在运行时自动启用自适应重规划和重复失败跳出")
# 保存配置
if config_changed:
print()
save_choice = (
UI.ask("是否保存为永久配置?", choices=["y", "n"], default="y").strip().lower()
)
if save_choice in ["", "y", "yes", "是"]:
save_config_to_file(config)
print()
def display_result(result: Dict[str, Any], show_steps: bool = False) -> None:
"""格式化显示任务结果"""
if show_steps and result.get("steps"):
if UI.rich_enabled():
table = Table(
show_header=True,
header_style="bold white",
box=box.SIMPLE_HEAD,
border_style="bright_black",
pad_edge=False,
)
table.add_column("#", justify="right", style="cyan", no_wrap=True)
table.add_column("Action", style="bold white", no_wrap=True)
table.add_column("Thought", style="bright_black")
table.add_column("Observation", style="bright_black")
for idx, step in enumerate(result.get("steps", []), start=1):
table.add_row(
str(idx),
str(step.get("action", "")),
UI.truncate(step.get("thought", ""), 120),
UI.truncate(step.get("observation", ""), 140),
)
RICH_CONSOLE.print(
Panel(
table,
title=Text(" 执行步骤 ", style="bold magenta"),
title_align="left",
border_style="bright_black",
box=box.ROUNDED,
padding=(1, 2),
)
)
else:
UI.section("执行步骤")
for idx, step in enumerate(result.get("steps", []), start=1):
print(
f" {UI.paint(f'{idx:>2}', Fore.MAGENTA, bright=True)} "
f"{UI.paint(str(step.get('action', '')), Fore.WHITE, bright=True)}"
)
print(f" {UI.paint('thought', Fore.WHITE, dim=True)} {step.get('thought')}")
action_input = step.get("action_input")
if action_input: