//! ## 工具系统类型定义 //! //! 定义了工具系统的核心类型: //! //! - `RiskLevel` — 工具的安全级别(Low/High) //! - `SkillSpec` — 工具的元数据描述(名称、参数、风险等级) //! - `SkillResult` — 工具执行结果 //! - `ExecutionContext` — 工具执行时的上下文环境 //! - `WechatSender` — 微信发送回调类型别名 use serde::{Deserialize, Serialize}; use std::future::Future; use std::pin::Pin; use std::sync::Arc; /// ## 风险等级 —— 工具的安全级别 /// /// * `Low` — 低风险,直接执行(如天气查询、日期时间) /// * `High` — 高风险,需要用户输入确认码审批(如写备忘录、发消息) #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RiskLevel { Low, High, } impl RiskLevel {} /// ## 工具元数据(SkillSpec)—— 工具的自描述信息 /// /// 用于给 LLM 展示"有什么工具可用、怎么用"。 /// * `name` — 工具名称 /// * `description` — 工具描述 /// * `risk_level` — 风险等级(Low/High) /// * `parameters` — JSON Schema 格式的参数定义 /// * `timeout_secs` — 执行超时时间 #[derive(Debug, Clone, Deserialize)] pub struct SkillSpec { pub name: String, pub description: String, #[serde(default = "default_risk_level")] pub risk_level: RiskLevel, #[serde(default)] pub parameters: serde_json::Value, #[serde(default = "default_timeout")] #[allow(dead_code)] pub timeout_secs: u64, } fn default_risk_level() -> RiskLevel { RiskLevel::Low } fn default_timeout() -> u64 { 30 } /// ## 工具执行结果 /// /// * `success` — 执行是否成功 /// * `output` — 可读的输出文本(将返回给 LLM) /// * `data` — 结构化数据(可选),用于后续处理 #[derive(Debug, Clone, Serialize)] pub struct SkillResult { pub success: bool, pub output: String, #[serde(skip_serializing_if = "Option::is_none")] pub data: Option, } impl SkillResult { pub fn ok(output: impl Into) -> Self { Self { success: true, output: output.into(), data: None, } } pub fn ok_with_data(output: impl Into, data: serde_json::Value) -> Self { Self { success: true, output: output.into(), data: Some(data), } } pub fn rejected(skill_name: &str) -> Self { Self { success: false, output: format!("用户拒绝了你的调用:{}", skill_name), data: None, } } #[allow(dead_code)] pub fn expired(skill_name: &str) -> Self { Self { success: false, output: format!("用户没有确认操作:{}", skill_name), data: None, } } pub fn error(msg: impl Into) -> Self { Self { success: false, output: msg.into(), data: None, } } } /// ## 执行上下文 —— 工具执行时需要的环境信息 /// /// 当工具在 daemon 上下文中执行时,携带以下信息: /// * `user_id` — 触发工具的用户 /// * `approval_manager` — 审批管理器(高风险工具需要) /// * `send_wechat` — 微信发送回调(用于向用户发送审批提示) pub type WechatSender = Arc< dyn Fn(&str, &str) -> Pin> + Send>> + Send + Sync, >; pub struct ExecutionContext { pub user_id: String, pub approval_manager: Option>, pub send_wechat: Option, } impl ExecutionContext { pub fn new(user_id: impl Into) -> Self { Self { user_id: user_id.into(), approval_manager: None, send_wechat: None, } } pub fn with_approval(mut self, mgr: Arc) -> Self { self.approval_manager = Some(mgr); self } pub fn with_wechat(mut self, send: WechatSender) -> Self { self.send_wechat = Some(send); self } }