alou 0.1.0

High-performance Rust implementation of Alou AI agent with MCP tool integration and DeepSeek API support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
use std::io::{self, Write};
use std::process;
use std::sync::Arc;
use anyhow::Result;
use clap::{Parser, Subcommand, Args};
use crate::config::Config;
use crate::agent::FileOperationAgent;
use crate::tool_registry::ToolRegistry;
use crate::prompt_registry::PromptRegistry;
use crate::env_config::*;

/// Alou - 智能文件操作助手
/// 一个基于Rust的交互式CLI代理,专注于软件工程任务
#[derive(Parser)]
#[command(name = "alou")]
#[command(version = "0.1.0")]
#[command(about = "智能文件操作助手 - 基于Rust的交互式CLI代理")]
#[command(long_about = "Alou是一个智能文件操作助手,专注于软件工程任务。它可以帮助你进行文件操作、代码分析、项目重构等各种开发任务。")]
pub struct Cli {
    /// 要执行的命令
    #[arg(short, long)]
    pub command: Option<String>,

    /// 交互式聊天模式
    #[arg(short, long)]
    pub interactive: bool,

    /// 列出所有可用的工具
    #[arg(long)]
    pub list_tools: bool,

    /// 列出所有可用的提示
    #[arg(long)]
    pub list_prompts: bool,

    /// 显示配置信息
    #[arg(long)]
    pub show_config: bool,

    /// 配置文件路径
    #[arg(long)]
    pub config: Option<String>,

    /// 工作区根目录
    #[arg(long)]
    pub workspace: Option<String>,

    /// 会话ID
    #[arg(long)]
    pub session: Option<String>,

    /// 模型名称
    #[arg(long)]
    pub model: Option<String>,

    /// 最大令牌数
    #[arg(long)]
    pub max_tokens: Option<usize>,

    /// 温度设置
    #[arg(long)]
    pub temperature: Option<f64>,

    /// 启用调试模式
    #[arg(long)]
    pub debug: bool,

    /// 启用沙盒模式
    #[arg(long)]
    pub sandbox: bool,

    /// 沙盒目录
    #[arg(long)]
    pub sandbox_dir: Option<String>,

    /// 子命令
    #[command(subcommand)]
    pub subcommand: Option<Commands>,
}

/// 子命令
#[derive(Subcommand)]
pub enum Commands {
    /// 聊天模式
    Chat(ChatArgs),
    /// 执行单个命令
    Run(RunArgs),
    /// 工具管理
    Tools(ToolsArgs),
    /// 配置管理
    Config(ConfigArgs),
    /// MCP管理
    MCP(MCPArgs),
    /// 帮助信息
    Info(HelpArgs),
}

/// 聊天模式参数
#[derive(Args)]
pub struct ChatArgs {
    /// 系统提示
    #[arg(long)]
    pub system_prompt: Option<String>,

    /// 用户记忆
    #[arg(long)]
    pub user_memory: Option<String>,

    /// 最大轮次
    #[arg(long, default_value = "100")]
    pub max_rounds: usize,

    /// 自动保存
    #[arg(long)]
    pub auto_save: bool,
}

/// 执行命令参数
#[derive(Args)]
pub struct RunArgs {
    /// 要执行的命令
    pub command: String,

    /// 命令参数
    pub args: Vec<String>,

    /// 工作目录
    #[arg(long)]
    pub work_dir: Option<String>,

    /// 超时时间(秒)
    #[arg(long, default_value = "30")]
    pub timeout: u64,

    /// 重试次数
    #[arg(long, default_value = "3")]
    pub retries: usize,
}

/// 工具管理参数
#[derive(Args)]
pub struct ToolsArgs {
    /// 子命令
    #[command(subcommand)]
    pub subcommand: ToolsSubcommand,
}

/// 工具管理子命令
#[derive(Subcommand)]
pub enum ToolsSubcommand {
    /// 列出所有工具
    List,
    /// 显示工具详情
    Show { name: String },
    /// 测试工具
    Test { name: String },
    /// 启用工具
    Enable { name: String },
    /// 禁用工具
    Disable { name: String },
}

/// 配置管理参数
#[derive(Args)]
pub struct ConfigArgs {
    /// 子命令
    #[command(subcommand)]
    pub subcommand: ConfigSubcommand,
}

/// 配置管理子命令
#[derive(Subcommand)]
pub enum ConfigSubcommand {
    /// 显示当前配置
    Show,
    /// 设置配置项
    Set { key: String, value: String },
    /// 重置配置
    Reset,
    /// 验证配置
    Validate,
    /// 导出配置
    Export { path: String },
    /// 导入配置
    Import { path: String },
}

/// MCP管理参数
#[derive(Args)]
pub struct MCPArgs {
    /// 子命令
    #[command(subcommand)]
    pub subcommand: MCPSubcommand,
}

/// MCP管理子命令
#[derive(Subcommand)]
pub enum MCPSubcommand {
    /// 发现可用的MCP服务器
    Discover,
    /// 测试MCP服务器连接
    Test { server: String },
    /// 导出配置文件
    Export { output: String },
    /// 自动发现并导出配置
    Auto { output: String },
}

/// 帮助信息参数
#[derive(Args)]
pub struct HelpArgs {
    /// 主题
    pub topic: Option<String>,
}

/// CLI应用程序
pub struct CliApp {
    config: Config,
    agent: FileOperationAgent,
    tool_registry: ToolRegistry,
    prompt_registry: PromptRegistry,
}

impl CliApp {
    /// 创建新的CLI应用程序
    pub async fn new() -> Result<Self> {
        // 初始化环境配置
        init_env_config()?;

        // 创建配置
        let config = Config::new()?;

        // 创建工具注册表
        let tool_registry = ToolRegistry::new();

        // 创建提示注册表
        let prompt_registry = PromptRegistry::new();

        // 创建并初始化代理
        let agent = FileOperationAgent::new_initialized(
            config.clone(), 
            Arc::new(tool_registry.clone()), 
            Arc::new(prompt_registry.clone())
        ).await?;

        Ok(CliApp {
            config,
            agent,
            tool_registry,
            prompt_registry,
        })
    }

    /// 运行CLI应用程序
    pub async fn run(&mut self, cli: Cli) -> Result<()> {
        // 处理全局选项
        self.handle_global_options(&cli)?;

        // 处理子命令
        if let Some(subcommand) = cli.subcommand {
            self.handle_subcommand(subcommand).await?;
        } else if cli.interactive {
            self.run_interactive_mode().await?;
        } else if let Some(command) = cli.command {
            self.run_single_command(&command).await?;
        } else if cli.list_tools {
            self.list_tools().await?;
        } else if cli.list_prompts {
            self.list_prompts()?;
        } else if cli.show_config {
            self.show_config()?;
        } else {
            // 默认进入交互模式
            self.run_interactive_mode().await?;
        }

        Ok(())
    }

    /// 处理全局选项
    fn handle_global_options(&mut self, cli: &Cli) -> Result<()> {
        // 设置调试模式
        if cli.debug {
            std::env::set_var("DEBUG", "true");
            std::env::set_var("RUST_LOG", "debug");
        }

        // 设置工作区根目录
        if let Some(workspace) = &cli.workspace {
            self.config.workspace_root = std::path::PathBuf::from(workspace);
        }

        // 设置会话ID
        if let Some(session) = &cli.session {
            self.config.session_id = session.clone();
        }

        // 设置模型
        if let Some(model) = &cli.model {
            self.config.update_default_model(model.clone());
        }

        // 设置最大令牌数
        if let Some(max_tokens) = cli.max_tokens {
            self.config.update_max_tokens(max_tokens);
        }

        // 设置温度
        if let Some(temperature) = cli.temperature {
            self.config.update_temperature(temperature);
        }

        // 设置沙盒模式
        if cli.sandbox {
            let sandbox_dir = cli.sandbox_dir.as_ref()
                .map(|s| std::path::PathBuf::from(s));
            self.config.update_sandbox(true, sandbox_dir);
        }

        // 加载配置文件
        if let Some(config_path) = &cli.config {
            let file_config = Config::from_file(config_path)?;
            self.config = file_config;
        }

        Ok(())
    }

    /// 处理子命令
    async fn handle_subcommand(&mut self, subcommand: Commands) -> Result<()> {
        match subcommand {
            Commands::Chat(args) => self.run_chat_mode(args).await?,
            Commands::Run(args) => self.run_command(args).await?,
            Commands::Tools(args) => self.handle_tools_command(args).await?,
            Commands::Config(args) => self.handle_config_command(args)?,
            Commands::MCP(args) => self.handle_mcp_command(args).await?,
            Commands::Info(args) => self.show_help(args)?,
        }
        Ok(())
    }

    /// 运行交互模式
    async fn run_interactive_mode(&mut self) -> Result<()> {
        println!("欢迎使用 Alou - 智能文件操作助手!");
        println!("输入 '/help' 查看帮助信息,输入 '/exit' 退出程序。");
        println!();

        let mut round_count = 0;
        const MAX_ROUNDS: usize = 100;

        loop {
            if round_count >= MAX_ROUNDS {
                println!("已达到最大轮次限制,程序退出。");
                break;
            }

            print!("alou> ");
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;
            let input = input.trim();

            if input.is_empty() {
                continue;
            }

            // 处理特殊命令
            if input.starts_with('/') {
                if self.handle_special_command(input).await? {
                    break;
                }
                continue;
            }

            // 显示加载状态
            print!("🤔 思考中");
            io::stdout().flush()?;
            
            // 启动一个异步任务来处理请求
            let agent = self.agent.clone();
            let input_clone = input.to_string();
            
            let handle = tokio::spawn(async move {
                agent.process_request(&input_clone).await
            });
            
            // 显示加载动画
            let loading_chars = ['', '', '', '', '', '', '', '', '', ''];
            let mut i = 0;
            
            while !handle.is_finished() {
                print!("\r🤔 思考中{} ", loading_chars[i % loading_chars.len()]);
                io::stdout().flush().unwrap();
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                i += 1;
            }
            
            // 获取结果
            match handle.await? {
                Ok(response) => {
                    print!("\r✅ 完成!\n");
                    if let Some(content) = response.content {
                        println!("{}", content);
                    }
                    if let Some(memory_updates) = response.memory_updates {
                        // TODO: 需要根据实际的memory_updates结构来处理
                        println!("💾 已保存到记忆: {:?}", memory_updates);
                    }
                }
                Err(e) => {
                    print!("\r❌ 错误!\n");
                    eprintln!("处理请求时出错: {}", e);
                }
            }

            round_count += 1;
        }

        Ok(())
    }

    /// 运行聊天模式
    async fn run_chat_mode(&mut self, args: ChatArgs) -> Result<()> {
        println!("进入聊天模式...");
        
        // 设置系统提示
        if let Some(_system_prompt) = args.system_prompt {
            // 这里可以设置自定义系统提示
            println!("使用自定义系统提示");
        }

        // 设置用户记忆
        if let Some(_user_memory) = args.user_memory {
            // 这里可以设置用户记忆
            println!("加载用户记忆");
        }

        let mut round_count = 0;

        loop {
            if round_count >= args.max_rounds {
                println!("已达到最大轮次限制,程序退出。");
                break;
            }

            print!("chat> ");
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;
            let input = input.trim();

            if input.is_empty() {
                continue;
            }

            if input == "/exit" {
                break;
            }

            // 显示加载状态
            print!("🤔 思考中");
            io::stdout().flush()?;
            
            // 启动一个异步任务来处理请求
            let agent = self.agent.clone();
            let input_clone = input.to_string();
            
            let handle = tokio::spawn(async move {
                agent.process_request(&input_clone).await
            });
            
            // 显示加载动画
            let loading_chars = ['', '', '', '', '', '', '', '', '', ''];
            let mut i = 0;
            
            while !handle.is_finished() {
                print!("\r🤔 思考中{} ", loading_chars[i % loading_chars.len()]);
                io::stdout().flush().unwrap();
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                i += 1;
            }
            
            // 获取结果
            match handle.await? {
                Ok(response) => {
                    print!("\r✅ 完成!\n");
                    if let Some(content) = response.content {
                        println!("{}", content);
                    }
                }
                Err(e) => {
                    print!("\r❌ 错误!\n");
                    eprintln!("处理请求时出错: {}", e);
                }
            }

            round_count += 1;
        }

        Ok(())
    }

    /// 运行单个命令
    async fn run_single_command(&mut self, command: &str) -> Result<()> {
        println!("执行命令: {}", command);
        
        match self.agent.process_request(command).await {
            Ok(response) => {
                if let Some(content) = response.content {
                    println!("{}", content);
                }
            }
            Err(e) => {
                eprintln!("错误: {}", e);
                process::exit(1);
            }
        }

        Ok(())
    }

    /// 运行命令
    async fn run_command(&mut self, args: RunArgs) -> Result<()> {
        let full_command = format!("{} {}", args.command, args.args.join(" "));
        println!("执行命令: {}", full_command);
        
        match self.agent.process_request(&full_command).await {
            Ok(response) => {
                if let Some(content) = response.content {
                    println!("{}", content);
                }
            }
            Err(e) => {
                eprintln!("错误: {}", e);
                process::exit(1);
            }
        }

        Ok(())
    }

    /// 处理工具命令
    async fn handle_tools_command(&mut self, args: ToolsArgs) -> Result<()> {
        match args.subcommand {
            ToolsSubcommand::List => self.list_tools().await?,
            ToolsSubcommand::Show { name } => self.show_tool(&name).await?,
            ToolsSubcommand::Test { name } => self.test_tool(&name)?,
            ToolsSubcommand::Enable { name } => self.enable_tool(&name)?,
            ToolsSubcommand::Disable { name } => self.disable_tool(&name)?,
        }
        Ok(())
    }

    /// 处理配置命令
    fn handle_config_command(&mut self, args: ConfigArgs) -> Result<()> {
        match args.subcommand {
            ConfigSubcommand::Show => self.show_config()?,
            ConfigSubcommand::Set { key, value } => self.set_config(&key, &value)?,
            ConfigSubcommand::Reset => self.reset_config()?,
            ConfigSubcommand::Validate => self.validate_config()?,
            ConfigSubcommand::Export { path } => self.export_config(&path)?,
            ConfigSubcommand::Import { path } => self.import_config(&path)?,
        }
        Ok(())
    }

    /// 处理MCP命令
    async fn handle_mcp_command(&mut self, args: MCPArgs) -> Result<()> {
        // 创建独立的工具注册表用于MCP操作
        let mcp_tool_registry = ToolRegistry::new();
        
        match args.subcommand {
            MCPSubcommand::Discover => self.discover_mcp_servers_with_registry(&mcp_tool_registry).await?,
            MCPSubcommand::Test { server } => self.test_mcp_server_with_registry(&mcp_tool_registry, &server).await?,
            MCPSubcommand::Export { output } => self.export_mcp_config_with_registry(&mcp_tool_registry, &output).await?,
            MCPSubcommand::Auto { output } => self.auto_discover_and_export_with_registry(&mcp_tool_registry, &output).await?,
        }
        Ok(())
    }

    /// 显示帮助信息
    fn show_help(&self, args: HelpArgs) -> Result<()> {
        if let Some(topic) = args.topic {
            self.show_topic_help(&topic)?;
        } else {
            self.show_general_help()?;
        }
        Ok(())
    }

    /// 处理特殊命令
    async fn handle_special_command(&mut self, command: &str) -> Result<bool> {
        match command {
            "/help" => {
                self.show_general_help()?;
                Ok(false)
            }
            "/exit" | "/quit" => {
                println!("再见!");
                Ok(true)
            }
            "/tools" => {
                // 异步调用需要特殊处理
                println!("工具列表功能暂时不可用");
                Ok(false)
            }
            "/prompts" => {
                self.list_prompts()?;
                Ok(false)
            }
            "/config" => {
                self.show_config()?;
                Ok(false)
            }
            "/clear" => {
                print!("\x1B[2J\x1B[1;1H");
                io::stdout().flush()?;
                Ok(false)
            }
            "/status" => {
                self.show_status().await?;
                Ok(false)
            }
            _ => {
                println!("未知命令: {}", command);
                println!("输入 '/help' 查看可用命令");
                Ok(false)
            }
        }
    }

    /// 列出所有工具
    async fn list_tools(&self) -> Result<()> {
        println!("可用的工具:");
        let tools = self.tool_registry.get_all_tools().await;
        for tool in tools {
            println!("  - {}: {}", tool.name(), tool.description());
        }
        Ok(())
    }

    /// 列出所有提示
    fn list_prompts(&self) -> Result<()> {
        println!("可用的提示:");
        let prompts = self.prompt_registry.get_all_prompts();
        for prompt in prompts {
            println!("  - {}: {:?}", prompt.name, prompt.description);
        }
        Ok(())
    }

    /// 显示配置信息
    fn show_config(&self) -> Result<()> {
        println!("当前配置:");
        let summary = self.config.get_summary();
        for (key, value) in summary {
            println!("  {}: {}", key, value);
        }
        Ok(())
    }

    /// 显示工具详情
    async fn show_tool(&self, name: &str) -> Result<()> {
        if let Some(tool) = self.tool_registry.get_tool(name).await {
            println!("工具: {}", tool.name());
            println!("描述: {}", tool.description());
            println!("参数: {:?}", tool.parameter_schema());
        } else {
            println!("未找到工具: {}", name);
        }
        Ok(())
    }

    /// 测试工具
    fn test_tool(&self, name: &str) -> Result<()> {
        println!("测试工具: {}", name);
        // 这里可以实现工具测试逻辑
        Ok(())
    }

    /// 启用工具
    fn enable_tool(&mut self, name: &str) -> Result<()> {
        println!("启用工具: {}", name);
        // 这里可以实现工具启用逻辑
        Ok(())
    }

    /// 禁用工具
    fn disable_tool(&mut self, name: &str) -> Result<()> {
        println!("禁用工具: {}", name);
        // 这里可以实现工具禁用逻辑
        Ok(())
    }

    /// 设置配置项
    fn set_config(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "model" => self.config.update_default_model(value.to_string()),
            "max_tokens" => {
                if let Ok(tokens) = value.parse::<usize>() {
                    self.config.update_max_tokens(tokens);
                } else {
                    return Err(anyhow::anyhow!("无效的最大令牌数: {}", value));
                }
            }
            "temperature" => {
                if let Ok(temp) = value.parse::<f64>() {
                    self.config.update_temperature(temp);
                } else {
                    return Err(anyhow::anyhow!("无效的温度值: {}", value));
                }
            }
            _ => return Err(anyhow::anyhow!("未知的配置项: {}", key)),
        }
        println!("已设置 {} = {}", key, value);
        Ok(())
    }

    /// 重置配置
    fn reset_config(&mut self) -> Result<()> {
        self.config = Config::new()?;
        println!("配置已重置");
        Ok(())
    }

    /// 验证配置
    fn validate_config(&self) -> Result<()> {
        match self.config.validate() {
            Ok(_) => {
                println!("配置验证通过");
                Ok(())
            }
            Err(e) => {
                eprintln!("配置验证失败: {}", e);
                Err(e)
            }
        }
    }

    /// 导出配置
    fn export_config(&self, path: &str) -> Result<()> {
        self.config.save_to_file(path)?;
        println!("配置已导出到: {}", path);
        Ok(())
    }

    /// 导入配置
    fn import_config(&mut self, path: &str) -> Result<()> {
        self.config = Config::from_file(path)?;
        println!("配置已从 {} 导入", path);
        Ok(())
    }

    /// 显示状态
    async fn show_status(&self) -> Result<()> {
        println!("Alou 状态:");
        println!("  会话ID: {}", self.config.session_id);
        println!("  工作区: {}", self.config.workspace_root.display());
        println!("  模型: {}", self.config.get_default_model());
        println!("  工具数量: {}", self.tool_registry.get_all_tools().await.len());
        println!("  提示数量: {}", self.prompt_registry.get_all_prompts().len());
        Ok(())
    }

    /// 显示一般帮助
    fn show_general_help(&self) -> Result<()> {
        println!("Alou - 智能文件操作助手");
        println!();
        println!("可用命令:");
        println!("  /help          - 显示此帮助信息");
        println!("  /exit, /quit   - 退出程序");
        println!("  /tools         - 列出所有可用工具");
        println!("  /prompts       - 列出所有可用提示");
        println!("  /config        - 显示当前配置");
        println!("  /clear         - 清屏");
        println!("  /status        - 显示状态信息");
        println!();
        println!("使用示例:");
        println!("  alou --interactive                    # 进入交互模式");
        println!("  alou --command \"分析这个项目\"          # 执行单个命令");
        println!("  alou --list-tools                     # 列出所有工具");
        println!("  alou --show-config                    # 显示配置");
        println!("  alou chat --max-rounds 50             # 聊天模式,最多50轮");
        println!("  alou run \"ls -la\"                     # 执行命令");
        println!("  alou tools list                       # 列出工具");
        println!("  alou config show                      # 显示配置");
        Ok(())
    }

    /// 显示主题帮助
    fn show_topic_help(&self, topic: &str) -> Result<()> {
        match topic {
            "tools" => {
                println!("工具帮助:");
                println!("  tools list     - 列出所有工具");
                println!("  tools show <name> - 显示工具详情");
                println!("  tools test <name> - 测试工具");
                println!("  tools enable <name> - 启用工具");
                println!("  tools disable <name> - 禁用工具");
            }
            "config" => {
                println!("配置帮助:");
                println!("  config show    - 显示当前配置");
                println!("  config set <key> <value> - 设置配置项");
                println!("  config reset   - 重置配置");
                println!("  config validate - 验证配置");
                println!("  config export <path> - 导出配置");
                println!("  config import <path> - 导入配置");
            }
            "mcp" => {
                println!("MCP管理帮助:");
                println!("  mcp discover   - 发现可用的MCP服务器");
                println!("  mcp test <server> - 测试MCP服务器连接");
                println!("  mcp export <path> - 导出MCP配置文件");
                println!("  mcp auto <path> - 自动发现并导出配置");
            }
            "chat" => {
                println!("聊天模式帮助:");
                println!("  chat --system-prompt <prompt> - 设置系统提示");
                println!("  chat --user-memory <memory> - 设置用户记忆");
                println!("  chat --max-rounds <number> - 设置最大轮次");
                println!("  chat --auto-save - 启用自动保存");
            }
            _ => {
                println!("未知主题: {}", topic);
                println!("可用主题: tools, config, mcp, chat");
            }
        }
        Ok(())
    }

    /// 发现MCP服务器
    async fn discover_mcp_servers(&self) -> Result<()> {
        let configs = self.tool_registry.discover_npm_mcp_servers().await?;
        
        if configs.is_empty() {
            println!("❌ 未发现任何可用的MCP服务器");
            println!("💡 提示: 确保已安装Node.js和npm,并且网络连接正常");
        } else {
            println!("🎉 发现 {} 个可用的MCP服务器:", configs.len());
            for config in configs {
                if let Some(command) = &config.command {
                    println!("{} - {}", "server", command);
                }
            }
        }
        Ok(())
    }

    /// 使用指定工具注册表发现MCP服务器
    async fn discover_mcp_servers_with_registry(&self, tool_registry: &ToolRegistry) -> Result<()> {
        let configs = tool_registry.discover_npm_mcp_servers().await?;
        
        if configs.is_empty() {
            println!("❌ 未发现任何可用的MCP服务器");
            println!("💡 提示: 确保已安装Node.js和npm,并且网络连接正常");
        } else {
            println!("🎉 发现 {} 个可用的MCP服务器:", configs.len());
            for config in configs {
                if let Some(command) = &config.command {
                    println!("{} - {}", "server", command);
                }
            }
        }
        Ok(())
    }

    /// 测试MCP服务器
    async fn test_mcp_server(&self, server: &str) -> Result<()> {
        // 使用 tool_registry 的测试功能
        let configs = self.tool_registry.discover_npm_mcp_servers().await?;
        
        let found_config = configs.iter().find(|config| {
            config.command.as_ref().map(|cmd| cmd.contains(server)).unwrap_or(false) ||
            config.args.as_ref().map(|args| args.contains(&server.to_string())).unwrap_or(false)
        });
        
        match found_config {
            Some(config) => {
                println!("✅ 服务器测试成功: {}", server);
                if let Some(command) = &config.command {
                    println!("   命令: {}", command);
                }
                if let Some(args) = &config.args {
                    println!("   参数: {:?}", args);
                }
            }
            None => {
                println!("❌ 服务器测试失败: 未找到服务器 {}", server);
                println!("💡 提示: 检查服务器名称是否正确,或尝试使用完整包名");
            }
        }
        Ok(())
    }

    /// 使用指定工具注册表测试MCP服务器
    async fn test_mcp_server_with_registry(&self, tool_registry: &ToolRegistry, server: &str) -> Result<()> {
        let configs = tool_registry.discover_npm_mcp_servers().await?;
        
        let found_config = configs.iter().find(|config| {
            config.command.as_ref().map(|cmd| cmd.contains(server)).unwrap_or(false) ||
            config.args.as_ref().map(|args| args.contains(&server.to_string())).unwrap_or(false)
        });
        
        match found_config {
            Some(config) => {
                println!("✅ 服务器测试成功: {}", server);
                if let Some(command) = &config.command {
                    println!("   命令: {}", command);
                }
                if let Some(args) = &config.args {
                    println!("   参数: {:?}", args);
                }
            }
            None => {
                println!("❌ 服务器测试失败: 未找到服务器 {}", server);
                println!("💡 提示: 检查服务器名称是否正确,或尝试使用完整包名");
            }
        }
        Ok(())
    }

    /// 导出MCP配置
    async fn export_mcp_config(&self, output: &str) -> Result<()> {
        let configs = self.tool_registry.discover_npm_mcp_servers().await?;
        
        if configs.is_empty() {
            println!("❌ 没有可用的MCP服务器配置可导出");
            return Ok(());
        }

        self.tool_registry.export_mcp_config(configs.clone(), output)?;
        println!("✅ 已导出 {} 个MCP服务器配置到: {}", configs.len(), output);
        Ok(())
    }

    /// 使用指定工具注册表导出MCP配置
    async fn export_mcp_config_with_registry(&self, tool_registry: &ToolRegistry, output: &str) -> Result<()> {
        let configs = tool_registry.discover_npm_mcp_servers().await?;
        
        if configs.is_empty() {
            println!("❌ 没有可用的MCP服务器配置可导出");
            return Ok(());
        }

        tool_registry.export_mcp_config(configs.clone(), output)?;
        println!("✅ 已导出 {} 个MCP服务器配置到: {}", configs.len(), output);
        Ok(())
    }

    /// 自动发现并导出MCP配置
    async fn auto_discover_and_export(&self, output: &str) -> Result<()> {
        self.tool_registry.auto_discover_and_export(output).await
    }

    /// 使用指定工具注册表自动发现并导出MCP配置
    async fn auto_discover_and_export_with_registry(&self, tool_registry: &ToolRegistry, output: &str) -> Result<()> {
        tool_registry.auto_discover_and_export(output).await
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_parsing() {
        let cli = Cli::try_parse_from(&["alou", "--interactive"]);
        assert!(cli.is_ok());
        
        let cli = cli.unwrap();
        assert!(cli.interactive);
    }

    #[test]
    fn test_cli_commands() {
        let cli = Cli::try_parse_from(&["alou", "chat", "--max-rounds", "10"]);
        assert!(cli.is_ok());
        
        let cli = cli.unwrap();
        assert!(matches!(cli.subcommand, Some(Commands::Chat(_))));
    }

    #[test]
    fn test_cli_tools() {
        let cli = Cli::try_parse_from(&["alou", "tools", "list"]);
        assert!(cli.is_ok());
        
        let cli = cli.unwrap();
        assert!(matches!(cli.subcommand, Some(Commands::Tools(_))));
    }

    #[test]
    fn test_cli_config() {
        let cli = Cli::try_parse_from(&["alou", "config", "show"]);
        assert!(cli.is_ok());
        
        let cli = cli.unwrap();
        assert!(matches!(cli.subcommand, Some(Commands::Config(_))));
    }
}