Skip to main content

wordval_agent/
plugin.rs

1//! Agent 插件:把 Agent 框架接入 Wordval 插件生命周期
2//!
3//! 在 umbrella crate `wordval` 中通过 `extend_plugins_from_config()` 装配:
4//! 当 `plugins` 与 `agent` 两个 feature 同时开启,且配置中
5//! `plugins.enabled` 包含 `"agent"` 时自动加入 `PluginManager`。
6//!
7//! ```toml
8//! [plugins]
9//! enabled = ["scheduler", "cache", "agent"]
10//! ```
11//!
12//! start 时:
13//! - 初始化全局成功会话池(`success_pool()`,会话成功时可 push `SuccessfulRun`)
14//! - 注册默认后台任务(技能沉淀 skill-distill,每 10 分钟扫描会话池)并启动调度循环
15//!
16//! stop 时:中止调度循环,清理后台任务。
17
18use std::sync::{Arc, Mutex, OnceLock};
19use std::time::Duration;
20
21use async_trait::async_trait;
22
23use crate::core::learn::{self, SkillCurator, SuccessfulRun};
24use crate::prelude::*;
25
26/// 全局成功会话池(自学习输入;会话成功时由使用方 push)
27static SUCCESS_POOL: OnceLock<Arc<Mutex<Vec<SuccessfulRun>>>> = OnceLock::new();
28
29/// 全局成功会话池访问入口(AgentPlugin start 后可用)
30pub fn success_pool() -> &'static Arc<Mutex<Vec<SuccessfulRun>>> {
31    SUCCESS_POOL.get_or_init(|| Arc::new(Mutex::new(Vec::new())))
32}
33
34/// Agent 插件 —— 管理 Agent 框架的全局后台资源
35pub struct AgentPlugin {
36    /// 调度循环句柄(stop 时中止)
37    handles: Mutex<Vec<tokio::task::JoinHandle<()>>>,
38}
39
40impl AgentPlugin {
41    pub fn new() -> Self {
42        Self {
43            handles: Mutex::new(Vec::new()),
44        }
45    }
46}
47
48impl Default for AgentPlugin {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54#[async_trait]
55impl Plugin for AgentPlugin {
56    fn name(&self) -> &str {
57        "agent"
58    }
59
60    fn priority(&self) -> i32 {
61        80
62    }
63
64    async fn start(&self) -> Result<()> {
65        // 1. 初始化成功会话池
66        success_pool();
67
68        // 2. 注册默认后台任务(技能沉淀)并启动调度循环
69        let curator = SkillCurator::shared();
70        learn::register_default_tasks(curator, success_pool().clone());
71        // 重复 start 先中止旧循环(P2-8):防止任务双跑与句柄泄漏
72        let mut slot = self.handles.lock().unwrap();
73        for h in slot.drain(..) {
74            h.abort();
75        }
76        *slot = learn::scheduler().start();
77
78        tracing::info!(
79            "agent 插件启动:技能沉淀任务已注册(skill-distill,间隔 {}s)",
80            Duration::from_secs(600).as_secs()
81        );
82        Ok(())
83    }
84
85    async fn stop(&self) -> Result<()> {
86        for h in self.handles.lock().unwrap().drain(..) {
87            h.abort();
88        }
89        tracing::info!("agent 插件停止:后台任务已中止");
90        Ok(())
91    }
92}