echo_agent 0.1.1

AI Agent framework with ReAct loop, multi-provider LLM, tool execution, and A2A HTTP server
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
//! 文本文件处理工具
//!
//! 提供文本文件读取和处理能力,支持:
//! - 读取各种文本格式文件
//! - 文本搜索和统计
//! - 编码检测

use futures::future::BoxFuture;
use serde_json::Value;

use super::security::{SecurityConfig, create_safe_regex};
use crate::error::{Result, ToolError};
use crate::tools::{Tool, ToolParameters, ToolResult};

const TOOL_NAME: &str = "text_tools";

/// 文本文件读取工具
pub struct TextReadTool;

impl Tool for TextReadTool {
    fn name(&self) -> &str {
        "read_text"
    }

    fn description(&self) -> &str {
        "读取文本文件内容,支持各种文本格式。自动检测编码。"
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "文本文件的绝对路径"
                },
                "start_line": {
                    "type": "integer",
                    "description": "起始行号(默认 1)"
                },
                "line_count": {
                    "type": "integer",
                    "description": "读取行数(默认 100,-1 表示全部)"
                },
                "encoding": {
                    "type": "string",
                    "description": "文件编码(如 'utf-8', 'gbk'),默认自动检测"
                }
            },
            "required": ["file_path"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let file_path = parameters
                .get("file_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("file_path".to_string()))?;

            let start_line = parameters
                .get("start_line")
                .and_then(|v| v.as_u64())
                .unwrap_or(1)
                .max(1) as usize; // 确保至少为 1

            let line_count = parameters
                .get("line_count")
                .and_then(|v| v.as_i64())
                .unwrap_or(100);

            let _encoding = parameters.get("encoding").and_then(|v| v.as_str());

            let security = SecurityConfig::global();
            let path = security.validate_file(file_path)?;

            // 读取文件
            let bytes = std::fs::read(&path).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("读取文件失败: {}", e),
            })?;

            // 尝试解码(优先 UTF-8,失败则尝试其他编码)
            let content = String::from_utf8(bytes.clone()).unwrap_or_else(|_| {
                // 尝试 GBK 解码
                encoding_rs::GBK.decode(&bytes).0.into_owned()
            });

            let lines: Vec<&str> = content.lines().collect();
            let total_lines = lines.len();

            // 应用预览行数限制
            let max_preview = security.limits.max_preview_rows;
            let effective_line_count = if line_count < 0 {
                max_preview
            } else {
                (line_count as usize).min(max_preview)
            };

            // 计算读取范围
            let start = (start_line - 1).min(total_lines);
            let end = (start + effective_line_count).min(total_lines);

            // 结构化输出
            let preview_lines_data: Vec<Value> = lines[start..end]
                .iter()
                .enumerate()
                .map(|(idx, line)| {
                    serde_json::json!({
                        "line_number": start + idx + 1,
                        "content": line,
                    })
                })
                .collect();

            let result = serde_json::json!({
                "file": file_path,
                "total_lines": total_lines,
                "start_line": start + 1,
                "end_line": end,
                "truncated": end < total_lines,
                "remaining_lines": total_lines.saturating_sub(end),
                "lines": preview_lines_data,
            });
            Ok(ToolResult::success_json(result))
        })
    }
}

/// 文本搜索工具
pub struct TextSearchTool;

impl Tool for TextSearchTool {
    fn name(&self) -> &str {
        "search_text"
    }

    fn description(&self) -> &str {
        "在文本文件中搜索内容,支持正则表达式。"
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "文本文件的绝对路径"
                },
                "pattern": {
                    "type": "string",
                    "description": "搜索模式(支持正则表达式)"
                },
                "context": {
                    "type": "integer",
                    "description": "显示匹配行前后的上下文行数(默认 0)"
                },
                "ignore_case": {
                    "type": "boolean",
                    "description": "是否忽略大小写(默认 false)"
                }
            },
            "required": ["file_path", "pattern"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let file_path = parameters
                .get("file_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("file_path".to_string()))?;

            let pattern = parameters
                .get("pattern")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("pattern".to_string()))?;

            let context = parameters
                .get("context")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as usize;

            let ignore_case = parameters
                .get("ignore_case")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);

            let security = SecurityConfig::global();
            let path = security.validate_file(file_path)?;

            // 读取文件
            let bytes = std::fs::read(&path).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("读取文件失败: {}", e),
            })?;

            let content = String::from_utf8(bytes.clone())
                .unwrap_or_else(|_| encoding_rs::GBK.decode(&bytes).0.into_owned());

            // 使用安全的正则表达式构建
            let re = if ignore_case {
                regex::RegexBuilder::new(pattern)
                    .case_insensitive(true)
                    .size_limit(security.limits.regex_max_size)
                    .dfa_size_limit(security.limits.regex_max_size)
                    .build()
                    .map_err(|e| ToolError::InvalidParameter {
                        name: "pattern".to_string(),
                        message: format!("无效的正则表达式: {}", e),
                    })?
            } else {
                create_safe_regex(pattern, &security.limits)?
            };

            let lines: Vec<&str> = content.lines().collect();
            let mut matches = Vec::new();
            let mut match_count = 0;

            // 限制匹配数量
            let max_matches = security.limits.max_preview_rows;

            for (idx, line) in lines.iter().enumerate() {
                if match_count >= max_matches {
                    break;
                }

                if re.is_match(line) {
                    match_count += 1;

                    // 添加上下文
                    if context > 0 {
                        let start = idx.saturating_sub(context);
                        let end = (idx + context + 1).min(lines.len());

                        matches.push(String::new());
                        for (i, context_line) in lines[start..end].iter().enumerate() {
                            let line_idx = start + i;
                            let prefix = if line_idx == idx { ">>>" } else { "   " };
                            matches.push(format!(
                                "{} {:5} | {}",
                                prefix,
                                line_idx + 1,
                                context_line
                            ));
                        }
                    } else {
                        matches.push(format!("{:5} | {}", idx + 1, line));
                    }
                }
            }

            let result = serde_json::json!({
                "file": file_path,
                "pattern": pattern,
                "match_count": match_count,
                "truncated": match_count >= max_matches,
                "max_matches": max_matches,
                "matches": matches,
            });
            Ok(ToolResult::success_json(result))
        })
    }
}

/// 文本统计工具
pub struct TextStatsTool;

impl Tool for TextStatsTool {
    fn name(&self) -> &str {
        "text_stats"
    }

    fn description(&self) -> &str {
        "统计文本文件的信息:行数、字数、字符数等。"
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "文本文件的绝对路径"
                }
            },
            "required": ["file_path"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let file_path = parameters
                .get("file_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("file_path".to_string()))?;

            let security = SecurityConfig::global();
            let path = security.validate_file(file_path)?;

            // 读取文件
            let bytes = std::fs::read(&path).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("读取文件失败: {}", e),
            })?;

            let content = String::from_utf8(bytes.clone())
                .unwrap_or_else(|_| encoding_rs::GBK.decode(&bytes).0.into_owned());

            // 统计
            let lines = content.lines().count();
            let chars = content.chars().count();
            let words = content.split_whitespace().count();
            let chinese_chars = content
                .chars()
                .filter(|c| '\u{4E00}' <= *c && *c <= '\u{9FFF}')
                .count();
            let english_words = content
                .split(|c: char| !c.is_ascii_alphabetic())
                .filter(|s| s.len() >= 2)
                .count();

            let line_lengths: Vec<usize> = content.lines().map(|l| l.len()).collect();
            let avg_line_len = if !line_lengths.is_empty() {
                Some(line_lengths.iter().sum::<usize>() as f64 / line_lengths.len() as f64)
            } else {
                None
            };
            let max_line_len = line_lengths.iter().max().copied();

            let file_size_kb = std::fs::metadata(&path)
                .ok()
                .map(|m| m.len() as f64 / 1024.0);

            let result = serde_json::json!({
                "file": file_path,
                "lines": lines,
                "chars": chars,
                "words": words,
                "chinese_chars": chinese_chars,
                "english_words": english_words,
                "file_size_kb": file_size_kb,
                "avg_line_len": avg_line_len,
                "max_line_len": max_line_len,
            });
            Ok(ToolResult::success_json(result))
        })
    }
}

/// 文本处理工具
pub struct TextProcessTool;

impl Tool for TextProcessTool {
    fn name(&self) -> &str {
        "process_text"
    }

    fn description(&self) -> &str {
        "对文本进行处理:提取行、合并、去重等操作。"
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "文本文件的绝对路径"
                },
                "operation": {
                    "type": "string",
                    "description": "操作类型:'unique'(去重)、'sort'(排序)、'reverse'(反转行)、'trim'(去除空白行)、'head'(前N行)、'tail'(后N行)"
                },
                "count": {
                    "type": "integer",
                    "description": "用于 head/tail 操作的行数"
                }
            },
            "required": ["file_path", "operation"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let file_path = parameters
                .get("file_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("file_path".to_string()))?;

            let operation = parameters
                .get("operation")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("operation".to_string()))?;

            let count = parameters
                .get("count")
                .and_then(|v| v.as_u64())
                .unwrap_or(10) as usize;

            let security = SecurityConfig::global();
            let path = security.validate_file(file_path)?;

            // 读取文件
            let bytes = std::fs::read(&path).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("读取文件失败: {}", e),
            })?;

            let content = String::from_utf8(bytes.clone())
                .unwrap_or_else(|_| encoding_rs::GBK.decode(&bytes).0.into_owned());

            let mut lines: Vec<&str> = content.lines().collect();
            let original_count = lines.len();
            let max_preview = security.limits.max_preview_rows;

            match operation {
                "unique" => {
                    use std::collections::HashSet;
                    let mut seen = HashSet::new();
                    lines.retain(|line| seen.insert(*line));
                }
                "sort" => {
                    lines.sort();
                }
                "reverse" => {
                    lines.reverse();
                }
                "trim" => {
                    lines.retain(|line| !line.trim().is_empty());
                }
                "head" => {
                    lines = lines.into_iter().take(count.min(max_preview)).collect();
                }
                "tail" => {
                    let start = lines.len().saturating_sub(count.min(max_preview));
                    lines = lines.into_iter().skip(start).collect();
                }
                _ => {
                    return Err(ToolError::InvalidParameter {
                        name: "operation".to_string(),
                        message: format!("不支持的操作: '{}'", operation),
                    }
                    .into());
                }
            }

            let preview_lines: Vec<&str> = lines.iter().take(max_preview).copied().collect();
            let result = serde_json::json!({
                "file": file_path,
                "operation": operation,
                "original_lines": original_count,
                "result_lines": lines.len(),
                "preview": preview_lines,
                "truncated": lines.len() > max_preview,
            });
            Ok(ToolResult::success_json(result))
        })
    }
}

/// 文本导出工具
pub struct TextExportTool;

impl Tool for TextExportTool {
    fn name(&self) -> &str {
        "export_text"
    }

    fn description(&self) -> &str {
        "将处理后的文本导出到新文件。"
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "input_file": {
                    "type": "string",
                    "description": "输入文本文件路径"
                },
                "output_file": {
                    "type": "string",
                    "description": "输出文件路径"
                },
                "operation": {
                    "type": "string",
                    "description": "可选操作:'unique'、'sort'、'trim' 等"
                }
            },
            "required": ["input_file", "output_file"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let input_file = parameters
                .get("input_file")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("input_file".to_string()))?;

            let output_file = parameters
                .get("output_file")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("output_file".to_string()))?;

            let operation = parameters.get("operation").and_then(|v| v.as_str());

            let security = SecurityConfig::global();
            let path = security.validate_file(input_file)?;

            // 读取文件
            let bytes = std::fs::read(&path).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("读取文件失败: {}", e),
            })?;

            let mut content = String::from_utf8(bytes.clone())
                .unwrap_or_else(|_| encoding_rs::GBK.decode(&bytes).0.into_owned());

            // 执行操作
            if let Some(op) = operation {
                let mut lines: Vec<&str> = content.lines().collect();
                match op {
                    "unique" => {
                        use std::collections::HashSet;
                        let mut seen = HashSet::new();
                        lines.retain(|line| seen.insert(*line));
                    }
                    "sort" => lines.sort(),
                    "trim" => lines.retain(|line| !line.trim().is_empty()),
                    _ => {}
                }
                content = lines.join("\n");
            }

            // 创建输出目录
            let output_path = security.validate_output_file(output_file)?;
            if let Some(parent) = output_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| ToolError::ExecutionFailed {
                    tool: TOOL_NAME.to_string(),
                    message: format!("创建输出目录失败: {}", e),
                })?;
            }

            // 写入文件
            std::fs::write(output_path, content).map_err(|e| ToolError::ExecutionFailed {
                tool: TOOL_NAME.to_string(),
                message: format!("写入文件失败: {}", e),
            })?;

            Ok(ToolResult::success(format!(
                "文本已导出: {} -> {}",
                input_file, output_file
            )))
        })
    }
}