imitatort 0.0.1-SNAPSHOT-dev.20260302111239

轻量级多Agent公司模拟框架
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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! 框架内置工具实现
//!
//! 提供通用的框架级工具执行能力

use anyhow::Result;
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::core::messaging::MessageBus;
use crate::core::skill::SkillManager;
use crate::core::store::{MessageFilter, Store};
use crate::core::tool::ToolRegistry;
use crate::core::tool_provider::{CompositeToolProvider, FrameworkToolProvider};
use crate::domain::tool::{MatchType, ToolCallContext, ToolProvider};
use crate::domain::{Group, Message, MessageTarget, Organization};
use crate::infrastructure::tool::ToolResult;

/// 工具执行环境
///
/// 包含工具执行所需的所有运行时依赖
#[derive(Clone)]
pub struct ToolEnvironment {
    /// 消息总线
    pub message_bus: Arc<MessageBus>,
    /// 组织架构
    pub organization: Arc<RwLock<Organization>>,
    /// 工具注册表
    pub tool_registry: Arc<ToolRegistry>,
    /// 工具提供者(用于查询)
    pub tool_provider: Arc<CompositeToolProvider>,
    /// 消息存储
    pub message_store: Arc<dyn Store>,
    /// 技能管理器
    pub skill_manager: Arc<SkillManager>,
}

impl ToolEnvironment {
    /// 创建新的工具环境
    pub fn new(
        message_bus: Arc<MessageBus>,
        organization: Arc<RwLock<Organization>>,
        tool_registry: Arc<ToolRegistry>,
        message_store: Arc<dyn Store>,
        skill_manager: Arc<SkillManager>,
    ) -> Self {
        // 创建组合提供者,包含框架工具和应用工具
        let tool_provider = CompositeToolProvider::new()
            .add_provider(Box::new(FrameworkToolProvider::new()))
            .with_registry(tool_registry.clone());

        Self {
            message_bus,
            organization,
            tool_registry,
            tool_provider: Arc::new(tool_provider),
            message_store,
            skill_manager,
        }
    }
}

/// 框架工具执行器
pub struct FrameworkToolExecutor {
    env: ToolEnvironment,
}

impl FrameworkToolExecutor {
    /// 创建框架工具执行器
    pub fn new(env: ToolEnvironment) -> Self {
        Self { env }
    }

    /// 获取支持的框架工具ID列表
    pub fn supported_tool_ids() -> Vec<&'static str> {
        vec![
            // Tool 查询类
            "tool.search",
            "tool.list_categories",
            "tool.get_category_tools",
            // 消息发送类
            "message.send_direct",
            "message.send_group",
            "message.send_to_guilty_line",
            "message.reply",
            // 群组管理类
            "group.list",
            // 时间类
            "time.now",
            // 组织架构类
            "org.get_structure",
            "org.get_department",
            "org.get_leader",
            "org.find_agents",
            "org.get_sub_departments",
            "org.get_subordinates",
            // 文件操作类
            "file.read",
            "file.write",
            "file.delete",
            "file.list",
            // 命令执行类
            "shell.exec",
            // 网页请求类
            "http.fetch",
        ]
    }

    /// 执行工具调用
    pub async fn execute(
        &self,
        tool_id: &str,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<ToolResult> {
        match tool_id {
            // Tool 查询类
            "tool.search" => self.execute_tool_search(params).await,
            "tool.list_categories" => self.execute_tool_list_categories(params).await,
            "tool.get_category_tools" => self.execute_tool_get_category_tools(params).await,
            // 消息发送类
            "message.send_direct" => self.execute_message_send_direct(params, context).await,
            "message.send_group" => self.execute_message_send_group(params, context).await,
            "message.send_to_guilty_line" => {
                self.execute_message_send_to_guilty_line(params, context)
                    .await
            }
            "message.reply" => self.execute_message_reply(params, context).await,
            // 群组管理类
            "group.list" => self.execute_group_list(params, context).await,
            // 时间类
            "time.now" => self.execute_time_now().await,
            // 组织架构类
            "org.get_structure" => self.execute_org_get_structure().await,
            "org.get_department" => self.execute_org_get_department(params).await,
            "org.get_leader" => self.execute_org_get_leader(params).await,
            "org.find_agents" => self.execute_org_find_agents(params).await,
            "org.get_sub_departments" => self.execute_org_get_sub_departments(params).await,
            "org.get_subordinates" => self.execute_org_get_subordinates(params).await,
            // 文件操作类
            "file.read" => self.execute_file_read(params).await,
            "file.write" => self.execute_file_write(params).await,
            "file.delete" => self.execute_file_delete(params).await,
            "file.list" => self.execute_file_list(params).await,
            // 命令执行类
            "shell.exec" => self.execute_shell_exec(params).await,
            // 网页请求类
            "http.fetch" => self.execute_http_fetch(params).await,
            _ => Ok(ToolResult::error(format!("Unknown tool: {}", tool_id))),
        }
    }

    // ==================== Tool 查询类 ====================

    async fn execute_tool_search(&self, params: Value) -> Result<ToolResult> {
        let query = params["query"].as_str().unwrap_or("");
        if query.is_empty() {
            return Ok(ToolResult::error("Query parameter is required"));
        }

        let match_type = match params["match_type"].as_str() {
            Some("exact") => MatchType::Exact,
            _ => MatchType::Fuzzy,
        };

        let category_filter = params["category_filter"].as_str();

        let mut results = self.env.tool_provider.search_tools(query, match_type);

        // 应用分类过滤
        if let Some(category) = category_filter {
            results.retain(|tool| tool.category.to_path_string().starts_with(category));
        }

        let tools_json: Vec<Value> = results
            .iter()
            .map(|tool| {
                json!({
                    "id": tool.id,
                    "name": tool.name,
                    "description": tool.description,
                    "category": tool.category.to_path_string(),
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "query": query,
            "match_type": if match_type == MatchType::Exact { "exact" } else { "fuzzy" },
            "count": tools_json.len(),
            "tools": tools_json,
        })))
    }

    async fn execute_tool_list_categories(&self, params: Value) -> Result<ToolResult> {
        let parent_category = params["parent_category"].as_str().unwrap_or("");

        let tree = self.env.tool_provider.get_category_tree();

        // 如果指定了父分类,找到对应节点
        let target_node = if parent_category.is_empty() {
            tree
        } else {
            find_category_node(&tree, parent_category)
                .unwrap_or_else(|| crate::domain::tool::CategoryNodeInfo::new("empty", ""))
        };

        Ok(ToolResult::success(json!({
            "parent": parent_category,
            "categories": target_node.children.iter().map(|c| {
                json!({
                    "name": c.name,
                    "path": c.path,
                    "tool_count": c.tool_count,
                })
            }).collect::<Vec<_>>(),
        })))
    }

    async fn execute_tool_get_category_tools(&self, params: Value) -> Result<ToolResult> {
        let category = params["category"].as_str().unwrap_or("");
        if category.is_empty() {
            return Ok(ToolResult::error("Category parameter is required"));
        }

        let _recursive = params["recursive"].as_bool().unwrap_or(true);

        let tools = self.env.tool_provider.list_tools_by_category(category);

        let tools_json: Vec<Value> = tools
            .iter()
            .map(|tool| {
                json!({
                    "id": tool.id,
                    "name": tool.name,
                    "description": tool.description,
                    "category": tool.category.to_path_string(),
                    "parameters": tool.parameters,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "category": category,
            "count": tools_json.len(),
            "tools": tools_json,
        })))
    }

    // ==================== 消息发送类 ====================

    async fn execute_message_send_direct(
        &self,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<ToolResult> {
        let to_agent_id = params["to_agent_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("to_agent_id is required"))?;
        let content = params["content"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("content is required"))?;
        let reply_to = params["reply_to_message_id"].as_str();

        let mut message = Message::private(&context.caller_id, to_agent_id, content);

        if let Some(reply_id) = reply_to {
            message = message.with_reply_to(reply_id);
        }

        self.env.message_bus.send(message).await?;

        Ok(ToolResult::success(json!({ "sent": true })))
    }

    async fn execute_message_send_group(
        &self,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<ToolResult> {
        let group_id = params["group_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("group_id is required"))?;
        let content = params["content"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("content is required"))?;

        // 检查群聊是否为隐藏群聊,如果是,则不允许通过常规消息发送工具发送
        let groups = self.env.message_store.load_groups().await?;
        let target_group = groups.iter().find(|g| g.id == group_id);

        match target_group {
            Some(group) => {
                // 如果是隐藏群聊,不允许通过普通的消息发送工具发送
                if matches!(
                    group.visibility,
                    crate::domain::message::GroupVisibility::Hidden
                ) {
                    return Ok(ToolResult::error("Cannot send message to hidden group using regular message.send_group tool. Use message.send_to_guilty_line instead.".to_string()));
                }

                // 检查调用者是否是群聊成员
                let is_member = group.members.contains(&context.caller_id);
                if !is_member {
                    return Ok(ToolResult::error(
                        "Caller is not a member of the target group".to_string(),
                    ));
                }
            }
            None => {
                return Ok(ToolResult::error("Target group not found".to_string()));
            }
        }

        let mut message = Message::group(&context.caller_id, group_id, content);

        // 处理 @ 列表
        if let Some(mentions) = params["mention_agent_ids"].as_array() {
            for mention in mentions {
                if let Some(id) = mention.as_str() {
                    message = message.with_mention(id);
                }
            }
        }

        // 处理回复
        if let Some(reply_id) = params["reply_to_message_id"].as_str() {
            message = message.with_reply_to(reply_id);
        }

        self.env.message_bus.send(message).await?;

        Ok(ToolResult::success(json!({ "sent": true })))
    }

    async fn execute_message_send_to_guilty_line(
        &self,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<ToolResult> {
        // 首先检查调用者是否具备特定技能来访问隐藏群聊
        // 检查调用者是否拥有guilty_line_access技能
        let _required_skills = ["guilty_line_access".to_string()];

        // 这里我们检查调用者是否拥有访问隐藏群聊的权限
        // 为了实现这一点,我们需要模拟调用者拥有的技能
        // 在实际实现中,这通常通过Agent的配置或其他方式传递
        let _caller_has_required_skills = true; // 临时设置为true,后续实现真实权限检查

        let groups = self.env.message_store.load_groups().await?;
        let guilty_line_group = groups.iter().find(|g| {
            g.id == "guilty_line_group"
                && matches!(
                    g.visibility,
                    crate::domain::message::GroupVisibility::Hidden
                )
        });

        match guilty_line_group {
            Some(group) => {
                // 检查调用者是否是该群聊的成员
                let is_member = group.members.contains(&context.caller_id);

                if !is_member {
                    return Ok(ToolResult::error(
                        "Caller is not a member of the Guilty Line group".to_string(),
                    ));
                }

                let content = params["content"]
                    .as_str()
                    .ok_or_else(|| anyhow::anyhow!("content is required"))?;

                let mut message = Message::group(&context.caller_id, &group.id, content);

                // 处理 @ 列表
                if let Some(mentions) = params["mention_agent_ids"].as_array() {
                    for mention in mentions {
                        if let Some(id) = mention.as_str() {
                            message = message.with_mention(id);
                        }
                    }
                }

                // 处理回复
                if let Some(reply_id) = params["reply_to_message_id"].as_str() {
                    message = message.with_reply_to(reply_id);
                }

                self.env.message_bus.send(message).await?;

                Ok(ToolResult::success(json!({
                    "sent": true,
                    "group_id": &group.id,
                    "group_name": &group.name
                })))
            }
            None => Ok(ToolResult::error(
                "Guilty Line group not found or not hidden".to_string(),
            )),
        }
    }

    async fn execute_group_list(
        &self,
        _params: Value,
        _context: &ToolCallContext,
    ) -> Result<ToolResult> {
        let all_groups = self.env.message_store.load_groups().await?;

        // 只返回非隐藏的群组
        let visible_groups: Vec<&Group> = all_groups
            .iter()
            .filter(|g| {
                matches!(
                    g.visibility,
                    crate::domain::message::GroupVisibility::Public
                )
            })
            .collect();

        let groups_json: Vec<Value> = visible_groups
            .iter()
            .map(|g| {
                json!({
                    "id": g.id,
                    "name": g.name,
                    "creator_id": g.creator_id,
                    "member_count": g.members.len(),
                    "created_at": g.created_at,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "count": groups_json.len(),
            "groups": groups_json,
        })))
    }

    async fn execute_message_reply(
        &self,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<ToolResult> {
        let message_id = params["message_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("message_id is required"))?;
        let content = params["content"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("content is required"))?;

        // 从消息存储中查找原消息
        let original_messages = self
            .env
            .message_store
            .load_messages(MessageFilter::new().limit(1).to(message_id))
            .await?;

        let reply_message = if let Some(orig_msg) = original_messages.first() {
            // 如果找到了原始消息,则根据原始消息的目标创建回复
            let reply_content = format!("[回复消息 {}] {}", message_id, content);
            let mut message = match &orig_msg.to {
                MessageTarget::Direct(sender_id) => {
                    // 如果原始消息是私聊,回复给对方
                    if *sender_id == context.caller_id {
                        // 如果原始消息发送者就是当前调用者,回复给原消息的发送者
                        Message::private(&context.caller_id, &orig_msg.from, reply_content)
                    } else {
                        // 否则回复给原始消息发送者
                        Message::private(&context.caller_id, sender_id, reply_content)
                    }
                }
                MessageTarget::Group(group_id) => {
                    // 如果原始消息是群聊,回复到同一群组
                    Message::group(&context.caller_id, group_id, reply_content)
                }
            };

            // 设置回复关系
            message = message.with_reply_to(message_id);

            // 处理 @ 列表
            if let Some(mentions) = params["mention_agent_ids"].as_array() {
                for mention in mentions {
                    if let Some(id) = mention.as_str() {
                        message = message.with_mention(id);
                    }
                }
            }

            let message_id_clone = message.id.clone();
            let target_clone = format!("{:?}", message.to);

            // 发送消息
            self.env.message_bus.send(message).await?;
            Ok(ToolResult::success(json!({
                "sent": true,
                "message_id": message_id_clone,
                "reply_to": message_id,
                "target": target_clone,
            })))
        } else {
            // 如果没有找到原始消息,返回错误
            Ok(ToolResult::error(format!(
                "Original message not found: {}",
                message_id
            )))
        };

        reply_message
    }

    // ==================== 时间类 ====================

    async fn execute_time_now(&self) -> Result<ToolResult> {
        let now = chrono::Utc::now();

        Ok(ToolResult::success(json!({
            "timestamp": now.timestamp(),
            "iso": now.to_rfc3339(),
            "date": now.format("%Y-%m-%d").to_string(),
            "time": now.format("%H:%M:%S").to_string(),
            "timezone": "UTC",
        })))
    }

    // ==================== 组织架构类 ====================

    async fn execute_org_get_structure(&self) -> Result<ToolResult> {
        let org = self.env.organization.read().await;
        let tree = org.build_tree();

        fn convert_node(node: &crate::domain::org::DepartmentNode) -> Value {
            json!({
                "id": node.department.id,
                "name": node.department.name,
                "leader_id": node.department.leader_id,
                "members": node.members,
                "children": node.children.iter().map(convert_node).collect::<Vec<_>>(),
            })
        }

        let departments: Vec<Value> = tree.iter().map(convert_node).collect();

        let agents: Vec<Value> = org
            .agents
            .iter()
            .map(|a| {
                json!({
                    "id": a.id,
                    "name": a.name,
                    "role": a.role.title,
                    "department_id": a.department_id,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "departments": departments,
            "agents": agents,
            "total_departments": org.departments.len(),
            "total_agents": org.agents.len(),
        })))
    }

    async fn execute_org_get_department(&self, params: Value) -> Result<ToolResult> {
        let dept_id = params["department_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("department_id is required"))?;

        let org = self.env.organization.read().await;

        let dept = org
            .find_department(dept_id)
            .ok_or_else(|| anyhow::anyhow!("Department not found: {}", dept_id))?;

        let members: Vec<&crate::domain::Agent> = org.get_department_members(dept_id);

        Ok(ToolResult::success(json!({
            "id": dept.id,
            "name": dept.name,
            "parent_id": dept.parent_id,
            "leader_id": dept.leader_id,
            "members": members.iter().map(|m| {
                json!({
                    "id": m.id,
                    "name": m.name,
                    "role": m.role.title,
                })
            }).collect::<Vec<_>>(),
            "member_count": members.len(),
        })))
    }

    async fn execute_org_get_leader(&self, params: Value) -> Result<ToolResult> {
        let dept_id = params["department_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("department_id is required"))?;

        let org = self.env.organization.read().await;

        let leader = org
            .get_department_leader(dept_id)
            .ok_or_else(|| anyhow::anyhow!("No leader found for department: {}", dept_id))?;

        Ok(ToolResult::success(json!({
            "id": leader.id,
            "name": leader.name,
            "role": leader.role.title,
            "department_id": leader.department_id,
        })))
    }

    async fn execute_org_find_agents(&self, params: Value) -> Result<ToolResult> {
        let query_type = params["query_type"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("query_type is required"))?;
        let query_value = params["query_value"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("query_value is required"))?;
        let fuzzy = params["fuzzy_match"].as_bool().unwrap_or(false);

        let org = self.env.organization.read().await;
        let query_lower = query_value.to_lowercase();

        let results: Vec<&crate::domain::Agent> = org
            .agents
            .iter()
            .filter(|agent| match query_type {
                "id" => {
                    if fuzzy {
                        agent.id.to_lowercase().contains(&query_lower)
                    } else {
                        agent.id.to_lowercase() == query_lower
                    }
                }
                "name" => {
                    if fuzzy {
                        agent.name.to_lowercase().contains(&query_lower)
                    } else {
                        agent.name.to_lowercase() == query_lower
                    }
                }
                "role" | "position" => {
                    if fuzzy {
                        agent.role.title.to_lowercase().contains(&query_lower)
                    } else {
                        agent.role.title.to_lowercase() == query_lower
                    }
                }
                "department" => {
                    if let Some(d) = agent.department_id.as_ref() {
                        if fuzzy {
                            d.to_lowercase().contains(&query_lower)
                        } else {
                            d.to_lowercase() == query_lower
                        }
                    } else {
                        false
                    }
                }
                "description" => {
                    if fuzzy {
                        agent
                            .role
                            .system_prompt
                            .to_lowercase()
                            .contains(&query_lower)
                    } else {
                        agent.role.system_prompt.to_lowercase() == query_lower
                    }
                }
                _ => false,
            })
            .collect();

        let agents_json: Vec<Value> = results
            .iter()
            .map(|a| {
                json!({
                    "id": a.id,
                    "name": a.name,
                    "role": a.role.title,
                    "department_id": a.department_id,
                    "expertise": a.role.expertise,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "query_type": query_type,
            "query_value": query_value,
            "fuzzy_match": fuzzy,
            "count": agents_json.len(),
            "agents": agents_json,
        })))
    }

    async fn execute_org_get_sub_departments(&self, params: Value) -> Result<ToolResult> {
        let dept_id = params["department_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("department_id is required"))?;

        let org = self.env.organization.read().await;

        let sub_depts = org.get_sub_departments(dept_id);

        let depts_json: Vec<Value> = sub_depts
            .iter()
            .map(|d| {
                json!({
                    "id": d.id,
                    "name": d.name,
                    "leader_id": d.leader_id,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "parent_id": dept_id,
            "count": depts_json.len(),
            "departments": depts_json,
        })))
    }

    async fn execute_org_get_subordinates(&self, params: Value) -> Result<ToolResult> {
        let agent_id = params["agent_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("agent_id is required"))?;

        let org = self.env.organization.read().await;

        // Find the department where this Agent belongs, check if it's a leader
        let agent = org
            .find_agent(agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {}", agent_id))?;

        let mut subordinates = Vec::new();

        if let Some(dept_id) = &agent.department_id {
            if let Some(dept) = org.find_department(dept_id) {
                // Check if it's a department leader
                if dept.leader_id.as_ref() == Some(&agent_id.to_string()) {
                    // Get other department members as subordinates
                    subordinates = org
                        .get_department_members(dept_id)
                        .into_iter()
                        .filter(|a| a.id != agent_id)
                        .cloned()
                        .collect::<Vec<_>>();
                }
            }
        }

        let subordinates_json: Vec<Value> = subordinates
            .iter()
            .map(|a| {
                json!({
                    "id": a.id,
                    "name": a.name,
                    "role": a.role.title,
                })
            })
            .collect();

        Ok(ToolResult::success(json!({
            "agent_id": agent_id,
            "is_leader": !subordinates.is_empty(),
            "count": subordinates_json.len(),
            "subordinates": subordinates_json,
        })))
    }

    // ==================== 文件操作类 ====================

    async fn execute_file_read(&self, params: Value) -> Result<ToolResult> {
        use tokio::fs;

        let path = params["path"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("path is required"))?;

        match fs::read_to_string(path).await {
            Ok(content) => Ok(ToolResult::success(json!({
                "success": true,
                "content": content,
            }))),
            Err(e) => Ok(ToolResult::success(json!({
                "success": false,
                "error": format!("Failed to read file: {}", e),
            }))),
        }
    }

    async fn execute_file_write(&self, params: Value) -> Result<ToolResult> {
        use tokio::fs;
        use tokio::io::AsyncWriteExt;

        let path = params["path"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("path is required"))?;
        let content = params["content"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("content is required"))?;
        let append = params["append"].as_bool().unwrap_or(false);

        let result = if append {
            // 追加模式
            match fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .await
            {
                Ok(mut file) => match file.write_all(content.as_bytes()).await {
                    Ok(_) => true,
                    Err(_) => {
                        let _ = fs::remove_file(path).await;
                        false
                    }
                },
                Err(_) => false,
            }
        } else {
            // 覆盖模式
            fs::write(path, content).await.is_ok()
        };

        if result {
            Ok(ToolResult::success(json!({
                "success": true,
            })))
        } else {
            Ok(ToolResult::success(json!({
                "success": false,
                "error": "Failed to write file",
            })))
        }
    }

    async fn execute_file_delete(&self, params: Value) -> Result<ToolResult> {
        use tokio::fs;

        let path = params["path"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("path is required"))?;

        match fs::remove_file(path).await {
            Ok(_) => Ok(ToolResult::success(json!({
                "success": true,
            }))),
            Err(e) => Ok(ToolResult::success(json!({
                "success": false,
                "error": format!("Failed to delete file: {}", e),
            }))),
        }
    }

    async fn execute_file_list(&self, params: Value) -> Result<ToolResult> {
        use tokio::fs;

        let path = params["path"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("path is required"))?;
        let pattern = params["pattern"].as_str();

        match fs::read_dir(path).await {
            Ok(mut dir) => {
                let mut entries = Vec::new();

                while let Ok(Some(entry)) = dir.next_entry().await {
                    if let Ok(name) = entry.file_name().into_string() {
                        // 应用简单的通配符过滤(仅支持 *)
                        let should_include = if let Some(pat) = pattern {
                            // 简单实现:*.rs -> ends_with(".rs"), test_* -> starts_with("test_")
                            if pat.starts_with('*') && pat.ends_with('*') {
                                name.contains(&pat[1..pat.len() - 1])
                            } else if let Some(suffix) = pat.strip_prefix('*') {
                                name.ends_with(suffix)
                            } else if let Some(prefix) = pat.strip_suffix('*') {
                                name.starts_with(prefix)
                            } else {
                                name == pat
                            }
                        } else {
                            true
                        };

                        if should_include {
                            let entry_type = entry.file_type().await.ok();
                            entries.push(json!({
                                "name": name,
                                "is_dir": entry_type.map(|t| t.is_dir()).unwrap_or(false),
                                "is_file": entry_type.map(|t| t.is_file()).unwrap_or(true),
                            }));
                        }
                    }
                }

                Ok(ToolResult::success(json!({
                    "success": true,
                    "entries": entries,
                })))
            }
            Err(e) => Ok(ToolResult::success(json!({
                "success": false,
                "error": format!("Failed to list directory: {}", e),
            }))),
        }
    }

    // ==================== 命令执行类 ====================

    async fn execute_shell_exec(&self, params: Value) -> Result<ToolResult> {
        use std::time::Duration;
        use tokio::process::Command;
        use tokio::time::timeout;

        let command = params["command"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("command is required"))?;
        let timeout_secs = params["timeout"].as_u64().unwrap_or(60);

        // 根据平台选择 shell
        let (shell, shell_arg) = if cfg!(windows) {
            ("cmd", "/C")
        } else {
            ("sh", "-c")
        };

        match timeout(Duration::from_secs(timeout_secs), Command::new(shell).arg(shell_arg).arg(command).output()).await {
            Ok(Ok(output)) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();
                Ok(ToolResult::success(json!({
                    "success": output.status.success(),
                    "stdout": stdout,
                    "stderr": stderr,
                    "exit_code": output.status.code().unwrap_or(-1),
                })))
            }
            Ok(Err(e)) => Ok(ToolResult::success(json!({
                "success": false,
                "stdout": "",
                "stderr": "",
                "exit_code": -1,
                "error": format!("Failed to execute command: {}", e),
            }))),
            Err(_) => Ok(ToolResult::success(json!({
                "success": false,
                "stdout": "",
                "stderr": "",
                "exit_code": -1,
                "error": format!("Command timed out after {} seconds", timeout_secs),
            }))),
        }
    }

    // ==================== 网页请求类 ====================

    async fn execute_http_fetch(&self, params: Value) -> Result<ToolResult> {
        use reqwest::{Client, header};

        let url = match params["url"].as_str() {
            Some(u) => u,
            None => return Ok(ToolResult::success(json!({
                "success": false,
                "status": 0,
                "body": "",
                "headers": {},
                "error": "url is required",
            }))),
        };
        let method = params["method"].as_str().unwrap_or("GET");
        let timeout_secs = params["timeout"].as_u64().unwrap_or(30);

        // 创建 Chrome 浏览器特征请求头
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::USER_AGENT,
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
                .parse()
                .unwrap(),
        );
        headers.insert(
            header::ACCEPT,
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"
                .parse()
                .unwrap(),
        );
        headers.insert(
            header::ACCEPT_LANGUAGE,
            "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7".parse().unwrap(),
        );
        headers.insert(
            header::ACCEPT_ENCODING,
            "gzip, deflate, br".parse().unwrap(),
        );
        headers.insert(header::CONNECTION, "keep-alive".parse().unwrap());
        headers.insert(
            "Upgrade-Insecure-Requests",
            "1".parse().unwrap(),
        );
        // Chrome Sec-Ch-Ua 头
        headers.insert(
            "Sec-Ch-Ua",
            "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\"".parse().unwrap(),
        );
        headers.insert("Sec-Ch-Ua-Mobile", "?0".parse().unwrap());
        headers.insert("Sec-Ch-Ua-Platform", "\"macOS\"".parse().unwrap());

        // 构建客户端
        let client = Client::builder()
            .default_headers(headers)
            .timeout(std::time::Duration::from_secs(timeout_secs))
            .redirect(reqwest::redirect::Policy::limited(10))
            .build();

        let client = match client {
            Ok(c) => c,
            Err(e) => {
                return Ok(ToolResult::success(json!({
                    "success": false,
                    "status": 0,
                    "body": "",
                    "headers": {},
                    "error": format!("Failed to create HTTP client: {}", e),
                })));
            }
        };

        // 解析方法
        let reqwest_method = match method.to_uppercase().as_str() {
            "GET" => reqwest::Method::GET,
            "POST" => reqwest::Method::POST,
            "PUT" => reqwest::Method::PUT,
            "DELETE" => reqwest::Method::DELETE,
            "PATCH" => reqwest::Method::PATCH,
            "HEAD" => reqwest::Method::HEAD,
            "OPTIONS" => reqwest::Method::OPTIONS,
            _ => {
                return Ok(ToolResult::success(json!({
                    "success": false,
                    "status": 0,
                    "body": "",
                    "headers": {},
                    "error": format!("Unsupported HTTP method: {}", method),
                })));
            }
        };

        // 执行请求
        match client.request(reqwest_method, url).send().await {
            Ok(response) => {
                let status = response.status().as_u16();
                let headers_map: serde_json::Map<String, Value> = response
                    .headers()
                    .iter()
                    .map(|(k, v)| {
                        (
                            k.as_str().to_string(),
                            Value::String(v.to_str().unwrap_or("").to_string()),
                        )
                    })
                    .collect();

                let body = match response.text().await {
                    Ok(text) => text,
                    Err(e) => {
                        return Ok(ToolResult::success(json!({
                            "success": false,
                            "status": status,
                            "body": "",
                            "headers": headers_map,
                            "error": format!("Failed to read response body: {}", e),
                        })));
                    }
                };

                Ok(ToolResult::success(json!({
                    "success": true,
                    "status": status,
                    "body": body,
                    "headers": headers_map,
                })))
            }
            Err(e) => Ok(ToolResult::success(json!({
                "success": false,
                "status": 0,
                "body": "",
                "headers": {},
                "error": format!("Failed to fetch URL: {}", e),
            }))),
        }
    }
}

/// 使用 domain::tool::CategoryNodeInfo
fn find_category_node(
    tree: &crate::domain::tool::CategoryNodeInfo,
    path: &str,
) -> Option<crate::domain::tool::CategoryNodeInfo> {
    if tree.path == path {
        return Some(tree.clone());
    }

    for child in &tree.children {
        if let Some(found) = find_category_node(child, path) {
            return Some(found);
        }
    }

    None
}

// ==================== ToolExecutor Trait Implementation ====================

use crate::infrastructure::tool::ToolExecutor as ToolExecutorTrait;
use async_trait::async_trait;

#[async_trait]
impl ToolExecutorTrait for FrameworkToolExecutor {
    async fn execute(
        &self,
        tool_id: &str,
        params: Value,
        context: &ToolCallContext,
    ) -> Result<Value> {
        let result = Self::execute(self, tool_id, params, context).await?;

        if result.success {
            Ok(result.data)
        } else {
            Err(anyhow::anyhow!(result
                .error
                .unwrap_or_else(|| "Unknown error".to_string())))
        }
    }

    fn can_execute(&self, tool_id: &str) -> bool {
        Self::supported_tool_ids().contains(&tool_id)
    }

    fn can_execute_with_skills(&self, tool_id: &str, skills: &[String]) -> bool {
        // 检查技能管理器是否允许使用此工具
        self.env.skill_manager.can_call_tool(tool_id, skills)
    }

    fn supported_tools(&self) -> Vec<String> {
        Self::supported_tool_ids()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }
}

// Tests moved to tests/infrastructure_framework_tools.rs