Skip to main content

mofa_kernel/agent/
core.rs

1//! MoFA Agent 核心接口 - 统一抽象
2//!
3//! 本模块定义了 MoFA 框架的统一 Agent 抽象,遵循微内核架构原则:
4//! - 核心统一:MoFAAgent 提供唯一的 Agent 接口
5//! - 可选扩展:通过扩展 trait 提供额外功能
6//! - 清晰层次:核心接口 + 可选扩展
7//!
8//! # 架构设计
9//!
10//! ```text
11//! ┌─────────────────────────────────────────────────────────────────────┐
12//! │                    MoFAAgent (统一核心接口)                          │
13//! │  • id(), name(), capabilities()                                     │
14//! │  • initialize(), execute(), shutdown()                              │
15//! │  • state()                                                          │
16//! └─────────────────────────────────────────────────────────────────────┘
17//!                               │
18//!         ┌─────────────────────┼─────────────────────┐
19//!         ▼                     ▼                     ▼
20//! ┌──────────────┐    ┌──────────────┐    ┌──────────────┐
21//! │AgentLifecycle│    │AgentMessaging│    │AgentPlugin   │
22//! │  (可选扩展)   │    │  (可选扩展)   │    │  (可选扩展)   │
23//! │              │    │              │    │   Support    │
24//! │• pause()     │    │• handle_     │    │              │
25//! │• resume()    │    │  message()   │    │• register_   │
26//! │              │    │• handle_     │    │  plugin()    │
27//! │              │    │  event()     │    │• unregister  │
28//! └──────────────┘    └──────────────┘    │  _plugin()   │
29//!                                         └──────────────┘
30//! ```
31
32pub use crate::agent::context::AgentEvent;
33use crate::agent::{
34    AgentCapabilities, AgentContext,
35    error::AgentResult,
36    types::{AgentInput, AgentOutput, AgentState, InterruptResult},
37};
38use async_trait::async_trait;
39
40// ============================================================================
41// MoFAAgent - 统一核心接口
42// ============================================================================
43
44/// MoFA Agent 统一接口
45///
46/// 这是 MoFA 框架中所有 Agent 必须实现的统一接口。
47/// 整合了之前的 AgentCore 和 MoFAAgent 功能,提供一致的抽象。
48///
49/// # 设计原则
50///
51/// 1. **统一接口**:所有 Agent 实现同一个 trait
52/// 2. **最小化核心**:只包含最基本的方法
53/// 3. **可选扩展**:通过扩展 trait 提供额外功能
54/// 4. **一致性**:统一接口与扩展约定
55///
56/// # 必须实现的方法
57///
58/// - `id()` - 唯一标识符
59/// - `name()` - 人类可读名称
60/// - `capabilities()` - 能力描述
61/// - `initialize()` - 初始化
62/// - `execute()` - 执行任务(核心方法)
63/// - `shutdown()` - 关闭
64/// - `state()` - 获取状态
65///
66/// # 示例
67///
68/// ```rust,ignore
69/// use mofa_kernel::agent::core::MoFAAgent;
70/// use mofa_kernel::agent::prelude::*;
71///
72/// struct MyAgent {
73///     id: String,
74///     name: String,
75///     capabilities: AgentCapabilities,
76///     state: AgentState,
77/// }
78///
79/// #[async_trait]
80/// impl MoFAAgent for MyAgent {
81///     fn id(&self) -> &str { &self.id }
82///     fn name(&self) -> &str { &self.name }
83///     fn capabilities(&self) -> &AgentCapabilities { &self.capabilities }
84///     fn state(&self) -> AgentState { self.state.clone() }
85///
86///     async fn initialize(&mut self, _ctx: &CoreAgentContext) -> AgentResult<()> {
87///         self.state = AgentState::Ready;
88///         Ok(())
89///     }
90///
91///     async fn execute(&mut self, input: AgentInput, _ctx: &CoreAgentContext) -> AgentResult<AgentOutput> {
92///         // 处理输入并返回输出
93///         Ok(AgentOutput::text("Response"))
94///     }
95///
96///     async fn shutdown(&mut self) -> AgentResult<()> {
97///         self.state = AgentState::Shutdown;
98///         Ok(())
99///     }
100/// }
101/// ```
102#[async_trait]
103pub trait MoFAAgent: Send + Sync + 'static {
104    // ========================================================================
105    // 标识和元数据
106    // ========================================================================
107
108    /// 获取唯一标识符
109    ///
110    /// ID 应该在 Agent 的整个生命周期内保持不变。
111    /// 用于在注册中心、日志、监控系统中唯一标识 Agent。
112    fn id(&self) -> &str;
113
114    /// 获取人类可读名称
115    ///
116    /// 名称用于显示和日志记录,不需要唯一。
117    fn name(&self) -> &str;
118
119    /// 获取能力描述
120    ///
121    /// 返回 Agent 支持的能力,用于:
122    /// - Agent 发现和路由
123    /// - 能力匹配和验证
124    /// - 多智能体协调
125    fn capabilities(&self) -> &AgentCapabilities;
126
127    // ========================================================================
128    // 核心生命周期
129    // ========================================================================
130
131    /// 初始化 Agent
132    ///
133    /// 在执行任务前调用,用于:
134    /// - 加载资源和配置
135    /// - 建立连接(数据库、网络等)
136    /// - 初始化内部状态
137    ///
138    /// # 参数
139    ///
140    /// - `ctx`: 执行上下文,提供配置、事件总线等
141    ///
142    /// # 状态转换
143    ///
144    /// Created -> Initializing -> Ready
145    async fn initialize(&mut self, ctx: &AgentContext) -> AgentResult<()>;
146
147    /// 执行任务 - 核心方法
148    ///
149    /// 这是 Agent 的主要执行方法,处理输入并返回输出。
150    ///
151    /// # 参数
152    ///
153    /// - `input`: 输入数据,支持多种格式(文本、JSON、二进制等)
154    /// - `ctx`: 执行上下文,提供状态、事件、中断等
155    ///
156    /// # 返回
157    ///
158    /// 返回执行结果,包含输出内容、元数据、工具使用等。
159    ///
160    /// # 状态转换
161    ///
162    /// Ready -> Executing -> Ready
163    async fn execute(&mut self, input: AgentInput, ctx: &AgentContext) -> AgentResult<AgentOutput>;
164
165    /// 关闭 Agent
166    ///
167    /// 优雅关闭,释放资源:
168    /// - 保存状态
169    /// - 关闭连接
170    /// - 清理资源
171    ///
172    /// # 状态转换
173    ///
174    /// * -> ShuttingDown -> Shutdown
175    async fn shutdown(&mut self) -> AgentResult<()>;
176
177    /// 中断 Agent
178    ///
179    /// 发送中断信号,Agent 可以选择如何响应:
180    /// - 立即停止
181    /// - 完成当前步骤后停止
182    /// - 忽略中断
183    ///
184    /// # 返回
185    ///
186    /// 返回中断处理结果。
187    ///
188    /// # 默认实现
189    ///
190    /// 默认返回 `InterruptResult::Acknowledged`。
191    ///
192    /// # 状态转换
193    ///
194    /// Executing -> Interrupted
195    async fn interrupt(&mut self) -> AgentResult<InterruptResult> {
196        Ok(InterruptResult::Acknowledged)
197    }
198
199    // ========================================================================
200    // 状态查询
201    // ========================================================================
202
203    /// 获取当前状态
204    ///
205    /// 返回 Agent 的当前状态,用于:
206    /// - 健康检查
207    /// - 状态监控
208    /// - 状态转换验证
209    fn state(&self) -> AgentState;
210}
211
212// ============================================================================
213// AgentLifecycle - 生命周期扩展
214// ============================================================================
215
216/// Agent 生命周期扩展
217///
218/// 提供额外的生命周期控制方法,用于需要更细粒度控制的场景。
219/// 这个 trait 是可选的,只有需要这些功能的 Agent 才需要实现。
220///
221/// # 提供的方法
222///
223/// - `pause()` - 暂停执行
224/// - `resume()` - 恢复执行
225///
226/// # 示例
227///
228/// ```rust,ignore
229/// use mofa_kernel::agent::core::AgentLifecycle;
230///
231/// #[async_trait]
232/// impl AgentLifecycle for MyAgent {
233///     async fn pause(&mut self) -> AgentResult<()> {
234///         self.state = AgentState::Paused;
235///         Ok(())
236///     }
237///
238///     async fn resume(&mut self) -> AgentResult<()> {
239///         self.state = AgentState::Ready;
240///         Ok(())
241///     }
242/// }
243/// ```
244#[async_trait]
245pub trait AgentLifecycle: MoFAAgent {
246    /// 暂停 Agent
247    ///
248    /// 暂停当前执行,保持状态以便后续恢复。
249    ///
250    /// # 状态转换
251    ///
252    /// Executing -> Paused
253    async fn pause(&mut self) -> AgentResult<()>;
254
255    /// 恢复 Agent
256    ///
257    /// 从暂停状态恢复执行。
258    ///
259    /// # 状态转换
260    ///
261    /// Paused -> Ready
262    async fn resume(&mut self) -> AgentResult<()>;
263}
264
265// ============================================================================
266// AgentMessaging - 消息处理扩展
267// ============================================================================
268
269/// Agent 消息处理扩展
270///
271/// 提供消息和事件处理能力,用于需要与其他 Agent 或系统交互的场景。
272/// 这个 trait 是可选的,只有需要消息处理的 Agent 才需要实现。
273///
274/// # 提供的方法
275///
276/// - `handle_message()` - 处理消息
277/// - `handle_event()` - 处理事件
278///
279/// # 示例
280///
281/// ```rust,ignore
282/// use mofa_kernel::agent::core::AgentMessaging;
283///
284/// #[async_trait]
285/// impl AgentMessaging for MyAgent {
286///     async fn handle_message(&mut self, msg: AgentMessage) -> AgentResult<AgentMessage> {
287///         // 处理消息并返回响应
288///         Ok(AgentMessage::new("response"))
289///     }
290///
291///     async fn handle_event(&mut self, event: AgentEvent) -> AgentResult<()> {
292///         // 处理事件
293///         Ok(())
294///     }
295/// }
296/// ```
297#[async_trait]
298pub trait AgentMessaging: MoFAAgent {
299    /// 处理消息
300    ///
301    /// 接收来自其他 Agent 或系统的消息,处理后返回响应。
302    ///
303    /// # 参数
304    ///
305    /// - `msg`: 接收到的消息
306    ///
307    /// # 返回
308    ///
309    /// 返回响应消息
310    async fn handle_message(&mut self, msg: AgentMessage) -> AgentResult<AgentMessage>;
311
312    /// 处理事件
313    ///
314    /// 处理来自事件总线的事件,用于响应系统级别的通知。
315    ///
316    /// # 参数
317    ///
318    /// - `event`: 事件对象
319    async fn handle_event(&mut self, event: AgentEvent) -> AgentResult<()>;
320}
321
322// ============================================================================
323// AgentPluginSupport - 插件支持扩展
324// ============================================================================
325
326/// Agent 插件支持扩展
327///
328/// 提供插件管理能力,允许在运行时动态扩展 Agent 功能。
329/// 这个 trait 是可选的,只有需要插件系统的 Agent 才需要实现。
330///
331/// # 提供的方法
332///
333/// - `register_plugin()` - 注册插件
334/// - `unregister_plugin()` - 注销插件
335///
336/// # 示例
337///
338/// ```rust,ignore
339/// use mofa_kernel::agent::core::AgentPluginSupport;
340///
341/// #[async_trait]
342/// impl AgentPluginSupport for MyAgent {
343///     fn register_plugin(&mut self, plugin: Box<dyn AgentPlugin>) -> AgentResult<()> {
344///         self.plugins.push(plugin);
345///         Ok(())
346///     }
347///
348///     fn unregister_plugin(&mut self, plugin_id: &str) -> AgentResult<()> {
349///         self.plugins.retain(|p| p.id() != plugin_id);
350///         Ok(())
351///     }
352/// }
353/// ```
354pub trait AgentPluginSupport: MoFAAgent {
355    /// 注册插件
356    ///
357    /// 向 Agent 注册一个新插件,扩展其功能。
358    ///
359    /// # 参数
360    ///
361    /// - `plugin`: 插件对象,实现 AgentPlugin trait
362    ///
363    /// # 返回
364    ///
365    /// 返回错误如果插件已存在或注册失败
366    fn register_plugin(&mut self, plugin: Box<dyn crate::plugin::AgentPlugin>) -> AgentResult<()>;
367
368    /// 注销插件
369    ///
370    /// 从 Agent 中移除一个插件。
371    ///
372    /// # 参数
373    ///
374    /// - `plugin_id`: 要移除的插件 ID
375    ///
376    /// # 返回
377    ///
378    /// 返回错误如果插件不存在
379    fn unregister_plugin(&mut self, plugin_id: &str) -> AgentResult<()>;
380}
381
382// ============================================================================
383// 辅助类型
384// ============================================================================
385
386/// Agent 消息
387///
388/// 用于 Agent 之间的通信
389#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
390pub struct AgentMessage {
391    /// 消息类型
392    #[serde(rename = "type")]
393    pub msg_type: String,
394
395    /// 消息内容
396    pub content: serde_json::Value,
397
398    /// 发送者 ID
399    pub sender_id: String,
400
401    /// 接收者 ID
402    pub recipient_id: String,
403
404    /// 时间戳
405    pub timestamp: i64,
406
407    /// 消息 ID
408    pub id: String,
409}
410
411impl AgentMessage {
412    /// 创建新消息
413    pub fn new(msg_type: impl Into<String>) -> Self {
414        let timestamp = std::time::SystemTime::now()
415            .duration_since(std::time::UNIX_EPOCH)
416            .unwrap()
417            .as_millis() as i64;
418
419        Self {
420            msg_type: msg_type.into(),
421            content: serde_json::json!({}),
422            sender_id: String::new(),
423            recipient_id: String::new(),
424            timestamp,
425            id: uuid::Uuid::new_v4().to_string(),
426        }
427    }
428
429    /// 设置内容
430    pub fn with_content(mut self, content: serde_json::Value) -> Self {
431        self.content = content;
432        self
433    }
434
435    /// 设置发送者
436    pub fn with_sender(mut self, sender_id: impl Into<String>) -> Self {
437        self.sender_id = sender_id.into();
438        self
439    }
440
441    /// 设置接收者
442    pub fn with_recipient(mut self, recipient_id: impl Into<String>) -> Self {
443        self.recipient_id = recipient_id.into();
444        self
445    }
446}