echo_agent 0.1.0

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
//! 统一配置管理
//!
//! 从 `echo-agent.yaml` 加载全局配置。
//!
//! # 配置文件搜索顺序
//!
//! 1. `--config <PATH>` 指定的路径
//! 2. `./echo-agent.yaml`
//! 3. `~/.echo-agent/config.yaml`
//! 4. 无配置文件时使用默认值
//!
//! # 示例
//!
//! ```no_run
//! use echo_agent::config::{load_config, apply_env_overrides};
//! use echo_agent::prelude::*;
//!
//! let mut cfg = load_config(None);
//! apply_env_overrides(&mut cfg);
//! let agent = ReactAgent::new(cfg.to_agent_config());
//! ```

use crate::agent::AgentConfig;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

// ── 配置结构体 ─────────────────────────────────────────────────────

/// 顶层应用配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[derive(Default)]
pub struct AppConfig {
    /// 模型配置(名称、温度、最大 token 数)
    pub model: ModelConfig,
    /// Agent 行为配置(系统提示、迭代次数、启用功能)
    pub agent: AgentYamlConfig,
    /// MCP(模型上下文协议)配置
    pub mcp: McpYamlConfig,
    /// 即时通讯通道配置(QQ、飞书)
    pub channels: ChannelsConfig,
    /// 服务端配置(主机、端口)
    pub server: ServerConfig,
    /// 日志级别配置
    pub logging: LoggingConfig,
}

impl AppConfig {
    /// 转换为库的 AgentConfig(builder 风格)
    pub fn to_agent_config(&self) -> AgentConfig {
        AgentConfig::standard(
            &self.model.name,
            &self.agent.name,
            &self.agent.system_prompt,
        )
        .enable_tool(self.agent.enable_tools)
        .enable_memory(self.agent.enable_memory)
        .enable_human_in_loop(self.agent.enable_human_in_loop)
        .max_iterations(self.agent.max_iterations)
        .memory_path(&self.agent.memory_path)
        .temperature(self.model.temperature)
        .max_tokens(self.model.max_tokens)
        .tool_execution(crate::tools::ToolExecutionConfig {
            timeout_ms: self.agent.tool_timeout_ms,
            ..Default::default()
        })
    }
}

/// 模型配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ModelConfig {
    /// 模型名称(如 "qwen-plus", "gpt-4o", "claude-3.5-sonnet")
    pub name: String,
    /// 最大生成 token 数(None 表示使用模型默认值)
    pub max_tokens: Option<u32>,
    /// 温度参数(0.0 ~ 2.0,None 表示使用模型默认值)
    pub temperature: Option<f32>,
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            name: "qwen-plus".to_string(),
            max_tokens: None,
            temperature: None,
        }
    }
}

/// Agent 配置(YAML 映射)
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct AgentYamlConfig {
    /// Agent 名称(用于日志和工具描述)
    pub name: String,
    /// 系统提示词(影响 Agent 行为风格)
    pub system_prompt: String,
    /// 最大迭代次数(单轮对话内最多执行多少步思考)
    pub max_iterations: usize,
    /// 是否启用工具(False 时 Agent 只能进行纯文本对话)
    pub enable_tools: bool,
    /// 是否启用记忆存储(跨会话记忆)
    pub enable_memory: bool,
    /// 是否启用人工审批(敏感操作需要用户确认)
    pub enable_human_in_loop: bool,
    /// 记忆存储路径(SQLite 文件位置)
    pub memory_path: String,
    /// 工具执行超时(毫秒),默认 120_000(2 分钟),适用于 MCP 工具等长时间调用
    pub tool_timeout_ms: u64,
}

impl Default for AgentYamlConfig {
    fn default() -> Self {
        Self {
            name: "echo-assistant".to_string(),
            system_prompt: "你是一个智能助手,可以帮助用户回答问题、执行任务。".to_string(),
            max_iterations: 10,
            enable_tools: true,
            enable_memory: true,
            enable_human_in_loop: true,
            memory_path: "~/.echo-agent/memory".to_string(),
            tool_timeout_ms: 120_000,
        }
    }
}

/// MCP 配置
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(default)]
pub struct McpYamlConfig {
    /// MCP 配置文件路径(mcp.json)
    pub config_path: Option<String>,
}

/// IM 通道配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[derive(Default)]
pub struct ChannelsConfig {
    /// QQ 机器人配置
    pub qq: QqChannelConfig,
    /// 飞书机器人配置
    pub feishu: FeishuChannelConfig,
    /// 会话管理配置
    pub session: SessionYamlConfig,
}

/// QQ Bot 通道配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[derive(Default)]
pub struct QqChannelConfig {
    /// 是否启用 QQ 通道
    pub enabled: bool,
    /// QQ 开发者平台 App ID
    pub app_id: String,
    /// QQ 开发者平台 Client Secret
    pub client_secret: String,
}

/// 飞书通道配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct FeishuChannelConfig {
    /// 是否启用飞书通道
    pub enabled: bool,
    /// 飞书开发者平台 App ID
    pub app_id: String,
    /// 飞书开发者平台 App Secret
    pub app_secret: String,
    /// 连接模式: "long_poll"(长轮询)或 "webhook"(Webhook 回调)
    pub mode: String,
}

impl Default for FeishuChannelConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            app_id: String::new(),
            app_secret: String::new(),
            mode: "long_poll".to_string(),
        }
    }
}

/// IM 会话配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct SessionYamlConfig {
    /// 会话超时时间(分钟),超过此时间后会话自动重置
    pub timeout_minutes: u64,
    /// 触发会话重置的关键词列表(用户消息包含这些词时会重置会话)
    pub reset_keywords: Vec<String>,
    /// 触发会话重置的命令列表(用户消息以这些命令开头时会重置会话)
    pub reset_commands: Vec<String>,
}

impl Default for SessionYamlConfig {
    fn default() -> Self {
        Self {
            timeout_minutes: 60,
            reset_keywords: vec![
                "重置对话".to_string(),
                "新对话".to_string(),
                "清除记忆".to_string(),
            ],
            reset_commands: vec![
                "/reset".to_string(),
                "/clear".to_string(),
                "/new".to_string(),
            ],
        }
    }
}

/// 服务配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ServerConfig {
    /// 监听主机(如 "0.0.0.0" 或 "127.0.0.1")
    pub host: String,
    /// 监听端口
    pub port: u16,
    /// 请求体最大字节数(默认 1MB,用于 A2A HTTP 服务)
    pub max_body_bytes: usize,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 3000,
            max_body_bytes: 1024 * 1024, // 1MB
        }
    }
}

/// 日志配置
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LoggingConfig {
    /// 日志级别("debug", "info", "warn", "error")
    pub level: String,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
        }
    }
}

// ── 配置加载 ────────────────────────────────────────────────────────

/// 配置文件搜索路径
fn config_search_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    if let Ok(explicit) = std::env::var("ECHO_AGENT_CONFIG")
        && !explicit.trim().is_empty()
    {
        paths.push(PathBuf::from(explicit));
    }
    paths.push(PathBuf::from("echo-agent.yaml"));
    if let Ok(home) = std::env::var("HOME") {
        paths.push(PathBuf::from(home).join(".echo-agent").join("config.yaml"));
    }
    paths
}

fn load_from_file(path: &PathBuf) -> Result<AppConfig, String> {
    let content = std::fs::read_to_string(path).map_err(|e| format!("读取配置文件失败: {}", e))?;
    serde_yaml::from_str(&content).map_err(|e| format!("解析配置文件失败: {}", e))
}

/// 加载配置(搜索默认路径)
pub fn load_config(explicit_path: Option<&str>) -> AppConfig {
    if let Some(path_str) = explicit_path {
        let path = PathBuf::from(path_str);
        match load_from_file(&path) {
            Ok(config) => {
                tracing::info!("已加载配置: {}", path.display());
                return config;
            }
            Err(e) => {
                tracing::error!("加载配置文件 {} 失败: {}", path.display(), e);
                tracing::info!("使用默认配置");
                return AppConfig::default();
            }
        }
    }

    for path in config_search_paths() {
        if path.exists() {
            match load_from_file(&path) {
                Ok(config) => {
                    tracing::info!("已加载配置: {}", path.display());
                    return config;
                }
                Err(e) => {
                    tracing::warn!("加载配置文件 {} 失败: {}", path.display(), e);
                }
            }
        }
    }

    tracing::info!("未找到配置文件,使用默认配置");
    AppConfig::default()
}

/// 合并基础环境变量覆盖。
///
/// 仅保留配置文件路径、渠道密钥等基础引导项;模型选择必须来自 YAML。
pub fn apply_env_overrides(config: &mut AppConfig) {
    if let Ok(v) = std::env::var("QQ_APP_ID") {
        config.channels.qq.app_id = v;
        if !config.channels.qq.app_id.is_empty() {
            config.channels.qq.enabled = true;
        }
    }
    if let Ok(v) = std::env::var("QQ_CLIENT_SECRET") {
        config.channels.qq.client_secret = v;
    }
    if let Ok(v) = std::env::var("FEISHU_APP_ID") {
        config.channels.feishu.app_id = v;
        if !config.channels.feishu.app_id.is_empty() {
            config.channels.feishu.enabled = true;
        }
    }
    if let Ok(v) = std::env::var("FEISHU_APP_SECRET") {
        config.channels.feishu.app_secret = v;
    }
    if let Ok(v) = std::env::var("MCP_CONFIG_PATH") {
        config.mcp.config_path = Some(v);
    }
}

// ── 单元测试 ────────────────────────────────────────────────────────

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

    #[test]
    fn test_default_config() {
        let config = AppConfig::default();
        assert_eq!(config.model.name, "qwen-plus");
        assert_eq!(config.agent.name, "echo-assistant");
        assert_eq!(config.agent.max_iterations, 10);
        assert!(config.agent.enable_tools);
        assert!(config.agent.enable_memory);
        assert!(config.agent.enable_human_in_loop);
        assert!(!config.channels.qq.enabled);
        assert!(!config.channels.feishu.enabled);
        assert_eq!(config.server.port, 3000);
        assert_eq!(config.logging.level, "info");
    }

    #[test]
    fn test_to_agent_config() {
        let config = AppConfig::default();
        let agent_config = config.to_agent_config();
        assert_eq!(agent_config.get_model_name(), "qwen-plus");
        assert_eq!(agent_config.get_agent_name(), "echo-assistant");
        assert!(agent_config.is_tool_enabled());
        assert!(agent_config.is_memory_enabled());
        assert!(agent_config.is_human_in_loop_enabled());
        assert_eq!(agent_config.get_max_iterations(), 10);
    }

    #[test]
    fn test_load_config_no_file() {
        // An explicit but missing config path should fall back to defaults.
        let missing_path =
            std::env::temp_dir().join(format!("echo-agent-missing-config-{}.yaml", uuid()));
        let config = load_config(missing_path.to_str());
        assert_eq!(config.model.name, "qwen-plus");
    }

    #[test]
    fn test_yaml_roundtrip() {
        let config = AppConfig::default();
        let yaml = serde_yaml::to_string(&config).unwrap();
        let parsed: AppConfig = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(parsed.model.name, config.model.name);
        assert_eq!(parsed.agent.system_prompt, config.agent.system_prompt);
    }

    #[test]
    fn test_load_config_honors_echo_agent_config_env() {
        let temp_path =
            std::env::temp_dir().join(format!("echo-agent-config-{}.yaml", std::process::id()));
        std::fs::write(
            &temp_path,
            r#"
model:
  name: qwen-vl-max
"#,
        )
        .unwrap();

        unsafe { std::env::set_var("ECHO_AGENT_CONFIG", &temp_path) };
        let config = load_config(None);
        unsafe { std::env::remove_var("ECHO_AGENT_CONFIG") };
        std::fs::remove_file(&temp_path).unwrap();

        assert_eq!(config.model.name, "qwen-vl-max");
    }

    fn uuid() -> u128 {
        use std::time::{SystemTime, UNIX_EPOCH};

        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    }
}