Skip to main content

matrixcode_core/command/
command_trait.rs

1//! 命令 trait 定义
2//!
3//! 每个命令实现此 trait 并注册到 CommandRegistry。
4
5use std::future::Future;
6use std::pin::Pin;
7
8use super::backend_context::BackendContext;
9
10/// 命令 trait,用于实现后端命令
11///
12/// 每个命令需要实现此 trait 并注册到 CommandRegistry。
13pub trait Command: Send + Sync {
14    /// 命令名称(不含前导 /)
15    fn name(&self) -> &'static str;
16
17    /// 命令别名(不含前导 /)
18    fn aliases(&self) -> &[&'static str] {
19        &[]
20    }
21
22    /// 命令帮助文本
23    fn help(&self) -> Option<&'static str> {
24        None
25    }
26
27    /// 检查命令是否匹配给定消息
28    ///
29    /// 默认匹配:
30    /// - 精确匹配:`/name`
31    /// - 带参数:`/name ...`
32    /// - 别名:`/alias` 或 `/alias ...`
33    fn matches(&self, msg: &str) -> bool {
34        let name = self.name();
35        if msg == format!("/{}", name) || msg.starts_with(&format!("/{} ", name)) {
36            return true;
37        }
38
39        for alias in self.aliases() {
40            if msg == format!("/{}", alias) || msg.starts_with(&format!("/{} ", alias)) {
41                return true;
42            }
43        }
44
45        false
46    }
47
48    /// 异步执行命令
49    ///
50    /// 返回值:
51    /// - `true`:消息继续转发给 agent
52    /// - `false`:命令已处理完毕,不再转发
53    fn execute<'a>(
54        &'a self,
55        ctx: &'a mut BackendContext<'_>,
56    ) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
57}