opentmd

AtomCode 插件运行时:atomcode-plexus

概述

atomcode-plexus 是 AtomCode 的“一切皆插件”运行时。Cargo.toml 里的描述是:“Spike: an everything-is-a-plugin runtime (Rust take on cordis) — service container, typed events, reversible effects, config-tree mounting”。它把 deepseek-harness 底层框架 cordis 的思路用 Rust 重写了一遍。核心主张出自 src/lib.rs 的头注释:

There is no privileged core to patch. Every part of the product — the model adapter, the tool registry, the approval policy, the agent loop itself — is a plugin mounted next to the others, and every registration it makes is a reversible effect.

全部源码约 2.1k 行,另有约 830 行测试,由以下五个机制组成:

  1. 插件:Plugin,声明 inject/uses/provides,在 apply(ctx, config) 中完成注册。
  2. 服务容器:用 marker 类型作为键(ServiceKey),在编译期确定类型,每个服务带一个 SeamMode 分类。
  3. 类型化事件:五种分发模式,分别是 Emit、Parallel、Serial、Bail、Waterfall。
  4. 可逆副作用:每个插件实例对应一个 fiber 账本,卸载时按逆序回放。
  5. 配置树:由若干 Layer 叠加成 ConfigTree,支持 insert、patch(含 swap、disable)、remove;运行中可以用 App::patch 热替换。

另外还有 realm(作用域树):服务表和事件总线共用同一棵 realm 树,可见性只向上。它是“一个会话对应一个 realm”(ADR 0023)和子 agent 隔离的基础。

plexus 本身不认识 LLM、工具或会话,这些都由 atomcode-harness 定义成服务和插件,详见 assembly.md。


1. 职责与定位

负责 不负责
把“行”(Entry{id,name,disabled,config})解析成插件实例,并按依赖关系激活 任何领域概念(LLM、工具、会话)
服务槽的提供、查找、撤销,以及冲突检测 配置文件的发现与路径(harness 的 profile.rs/launch.rs)
类型化事件总线(同步、异步、洋葱式 waterfall) 插件的动态加载:Rust 在编译期链接,可用插件的清单在构建时就确定了
可逆副作用账本,卸载时级联到子插件 卸载时的 quiescence(不会等待正在执行的调用结束,见 §11)
运行中 patch(卸载变化的行、重挂、补挂仍在等待的行) 配置变量展开(ADR 0017 提议在“折树时”统一处理,未实现)
声明与实际的一致性审计(App::audit) 生成能力图(harness 的 seam_map.rs 负责)

lib.rs 列出了与 cordis 的两处实质差异:


2. 依赖图位置

            tokio(rt, sync, time, macros) · async-trait · futures · serde(_json) · toml
                                      ▲
                              atomcode-plexus        ← 不依赖 atomcode-kernel,也不依赖任何领域 crate
                                      ▲
          ┌───────────────┬───────────┼─────────────┬──────────────┐
   atomcode-harness   atomcode-cli  atomcode-coding  atomcode-tree-host  atomcode-tui
   (定义缝、实现插件) (启动器)    (产品装配)     (宿主)            (ui-tui2 / 面板行)

plexus 处在依赖图的底层,是纯机制库。依赖 toml 只是为了支持 Layer::from_toml。


3. 模块地图

文件 行数 职责 主要公开项
src/lib.rs 115 再导出公开项,定义两个宏 plexus_service!、plexus_event!
src/plugin.rs 105 插件契约与注册表 Plugin、PluginRegistry
src/service.rs 236 类型化服务表 ServiceKey、SeamMode、ServiceTable(crate 内部)
src/realm.rs 90 realm 树 RealmId、ROOT_REALM=0、RealmTree::{fork, ancestry, visible_from}
src/event.rs 323 类型化事件与总线 Event、Mode、Next、Waterfall、Listener、EventBus
src/fiber.rs 226 插件实例生命周期与副作用账本 FiberId、ROOT_FIBER=0、FiberStatus、Disposable、FiberTable
src/context.rs 333 交给插件的句柄 Context
src/loader.rs 424 配置行、层、树 Entry、Op、Layer、ConfigTree
src/app.rs 451 运行时:挂载、patch、停止、审计、dump App、AuditFinding
src/error.rs 69 组合错误 PlexusError、Result
tests/runtime.rs 679 运行时语义测试 见 §10
tests/layer_builder.rs 155 Layer 构建器与 TOML 等价性测试 见 §10

4. 核心类型(签名摘录)

4.1 Plugin 与 PluginRegistry(src/plugin.rs)

#[async_trait]
pub trait Plugin: Send + Sync + 'static {
    fn name(&self) -> &'static str;                         // 配置行的 name 指向这里
    fn inject(&self)   -> &'static [&'static str] { &[] }   // 硬依赖:这些服务就绪后才激活
    fn uses(&self)     -> &'static [&'static str] { &[] }   // 软依赖:有就读,没有就降级(进入能力图)
    fn provides(&self) -> &'static [&'static str] { &[] }   // 声明自己填哪些槽(供审计和能力图使用)
    fn description(&self) -> &'static str { "" }
    async fn apply(&self, ctx: &Context, config: &Value) -> Result<(), String>;
}

#[derive(Default)]
pub struct PluginRegistry { plugins: HashMap<&'static str, Arc<dyn Plugin>> }
impl PluginRegistry {
    pub fn register(&mut self, plugin: Arc<dyn Plugin>) -> &mut Self; // 重名直接 panic(属于构建期错误)
    pub fn get(&self, name: &str) -> Option<Arc<dyn Plugin>>;
    pub fn names(&self) -> Vec<&'static str>;                         // 已排序
}

插件契约中值得注意的几点:

4.2 ServiceKey / SeamMode(src/service.rs)

pub enum SeamMode {
    Core,    // 主干:只有一个实现,替换它不是预期用法(注册表、日志、共享索引)
    Seam,    // 可替换能力:预期有多个提供方,消费方不得点名某个提供方
    Bundle,  // 组合点:本身没有行为,供其它行挂载内容
}

pub trait ServiceKey: Send + Sync + 'static {
    const NAME: &'static str;
    const MODE: SeamMode;
    const TITLE: &'static str;               // 用于自动生成的能力图
    type Face: ?Sized + Send + Sync + 'static; // 通常是 dyn Trait
}

// 宏:分类写在接口定义旁边,不另外维护表格
plexus_service!(Llm => dyn LlmProvider, "llm", Seam, "LLM adapter registry");

ServiceTable 的内部结构:

操作 语义
provide::<K>(realm, value, owner, label) 同一 realm 中已有该槽时返回 ServiceConflict,不会静默覆盖。替换必须先卸载现任,或者另开一个 realm
revoke::<K>(realm, owner) 只有当前 owner 是该 fiber 时才删除,防止卸载时误删别人重新提供的服务
get::<K>(realm) 沿 realm 父链向上查找
has_named(realm, name) 按字符串名做同样的查找
owned_by_in(owner, realm) 审计用:某个 fiber 在指定 realm 中填了哪些槽
visible_names(realm) 诊断用:从某个 realm 能看到的全部服务名

4.3 Realm(src/realm.rs)

pub type RealmId = u64;
pub const ROOT_REALM: RealmId = 0;
pub(crate) struct RealmTree { parents: RwLock<HashMap<RealmId, RealmId>>, next: AtomicU64 }
impl RealmTree {
    pub fn fork(&self, parent: RealmId) -> RealmId;
    pub fn ancestry(&self, realm: RealmId) -> Vec<RealmId>;            // 从近到远;带环保护
    pub fn visible_from(&self, owner: RealmId, viewer: RealmId) -> bool; // owner == viewer、owner 为 ROOT 或 owner 是 viewer 的祖先
}

可见性只朝一个方向,这是整个设计的关键:

4.4 Event / Mode / Waterfall(src/event.rs)

pub enum Mode { Emit, Parallel, Serial, Bail, Waterfall }

pub trait Event: Send + Sync + 'static {
    const NAME: &'static str;   // 例如 "agent/pre-step"
    const MODE: Mode;           // 一个事件只允许一种分发模式
    type Args:   Send + Sync + 'static;
    type Output: Send + Sync + 'static;
}

#[async_trait] pub trait Listener<E: Event>  { async fn call(&self, args: &E::Args) -> Option<E::Output>; }
#[async_trait] pub trait Waterfall<E: Event> { async fn handle(&self, args: &mut E::Args, next: Next<'_, E>) -> E::Output; }

pub struct Next<'a, E> { rest: &'a [Arc<dyn Waterfall<E>>], terminal: &'a Terminal<'a, E> } // Copy
impl Next { pub fn run<'b>(self, args: &'b mut E::Args) -> BoxFuture<'b, E::Output>; }

plexus_event!(PreToolCall, "tools/pre-execute", Waterfall, ToolCall => Decision);

五种模式的语义:

Mode 注册方法 分发方法 语义
Emit on_emit emit(&args) 同步广播,没有返回值
Bail on_bail bail(&args) -> Option<Out> 同步,按顺序调用,第一个返回 Some 的监听器决定结果
Parallel on_parallel parallel(&args).await 异步,用 join_all 并发执行,没有返回值
Serial on_serial serial(&args).await -> Option<Out> 异步,按顺序调用,第一个 Some 胜出
Waterfall on_waterfall(listener, prepend) waterfall(&mut args, terminal).await -> Out 洋葱式中间件:监听器可以在调用 next.run(args) 前后包装逻辑,也可以不调用 next 直接短路。terminal 是最内层的默认实现

4.5 Fiber 与 Disposable(src/fiber.rs)

pub type FiberId = u64;
pub const ROOT_FIBER: FiberId = 0;           // 宿主自己的注册,永远不会卸载
pub enum FiberStatus { Pending, Active, Disposed }

pub(crate) struct FiberState {
    pub id, pub entry: String /*行 id*/, pub plugin: String, pub parent: FiberId,
    ledger: Mutex<Vec<Option<Box<dyn FnOnce() + Send>>>>,
    status: Mutex<FiberStatus>,
}

#[must_use = "ignoring a Disposable is fine (the fiber owns the effect); bind it to `_` to say so"]
pub struct Disposable { fiber: Weak<FiberState>, slot: usize }
impl Disposable { pub fn dispose(self); }    // 提前撤销单个副作用;重复调用无效果

选择账本而不是 RAII guard 的原因:Disposable 只是一个句柄,drop 它不会产生任何效果,副作用仍然由 fiber 持有。插件即使忽略返回值,注册也仍然有效,cordis 的用法就是这样,而普通 RAII 做不到这一点。fiber 卸载时:

  1. 先递归卸载所有子 fiber(parent == id 的那些),子先父后。
  2. 再把自己的账本逆序回放,并把状态设为 Disposed。这个过程是幂等的。

4.6 Context(src/context.rs)

#[derive(Clone)]
pub struct Context { root: Arc<Root>, fiber: FiberId, realm: RealmId }
// Root { services: ServiceTable, events: EventBus, fibers: FiberTable, registry: PluginRegistry, realms: Arc<RealmTree> }

impl Context {
    // 身份
    pub fn entry(&self) -> String;
    // 任意副作用
    pub fn effect(&self, undo: impl FnOnce() + Send + 'static) -> Disposable;
    // 服务
    pub fn provide<K: ServiceKey>(&self, value: Arc<K::Face>) -> Result<Disposable>;
    pub fn service<K: ServiceKey>(&self) -> Option<Arc<K::Face>>;
    pub fn require<K: ServiceKey>(&self) -> Result<Arc<K::Face>>;      // 为空时返回 ServiceMissing
    pub fn has_service(&self, name: &str) -> bool;
    pub fn service_names(&self) -> Vec<&'static str>;
    pub fn isolate(&self) -> Self;                                    // fork 一个子 realm,保留同一个 fiber
    // 事件注册(每个都返回 Disposable 并登记到 fiber)
    pub fn on_emit / on_bail / on_parallel / on_serial / on_waterfall(.., prepend);
    // 事件分发
    pub fn emit / bail / parallel / serial / waterfall(args, terminal);
    pub fn listener_count<E>(&self) -> usize;
    // 子插件
    pub async fn plugin(&self, name: &str, config: Value) -> Result<FiberId>;          // 子 fiber 的 parent 是当前 fiber
    pub async fn plugin_isolated(&self, name, config) -> Result<(FiberId, Context)>;   // 挂进新的 realm
    pub fn unload(&self, fiber: FiberId);
}

4.7 Entry / Op / Layer / ConfigTree(src/loader.rs)

pub struct Entry {
    pub id: String,                 // 供 patch 寻址;缺省等于 name
    pub name: String,               // 插件名
    #[serde(default)] pub disabled: bool,   // 已挂上但不运行;保留在树中,方便后续层重新启用,也方便 dump 展示
    #[serde(default)] pub config: Value,    // 对运行时不透明
}
impl Entry { fn named(name); fn with_id(id, name); fn with(self, impl Serialize) -> Result<Self>; fn disabled(self); }

pub enum Op {
    Insert(Vec<Entry>),                                   // 追加;同 id 则整行替换
    Patch { id, config: Option<Value>, disabled: Option<bool>, name: Option<String> },
    Remove { id },
}

pub struct Layer { pub ops: Vec<Op> }
impl Layer {
    fn new(); fn insert(e); fn patch(id, cfg)?; fn swap(id, name); fn disable(id); fn enable(id);
    fn remove(id); fn then(other); fn maybe(Option<Layer>); fn when(cond, |l| ..);
    fn from_toml(src) -> Result<Layer>;
}

pub struct ConfigTree { pub entries: Vec<Entry> }
impl ConfigTree { fn from_layers(..); fn apply(&mut self, &Layer); fn active(); fn dump() -> String; }

swap 与 disable 都是 Op::Patch 的特例:


5. 关键流程

5.1 启动:依赖驱动的不动点挂载(App::start → mount_all)

rows = tree.active()                         // 过滤掉 disabled 的行
先检查:每行的 name 都在 registry 中?否 → UnknownPlugin(一行都不挂,不留半个系统)
loop {
    progressed = false
    for entry in pending:
        if 所有 plugin.inject() 的服务都已可见(在根 realm 查):
            fiber = fibers.create(entry.id, entry.name, ROOT_FIBER)
            match plugin.apply(ctx.for_fiber(fiber), &entry.config):
                Ok  → fiber 状态设为 Active;mounted[id] = fiber;progressed = true
                Err → fibers.unload(fiber)(回滚部分注册);返回 PlexusError::Apply{entry, message}
        else: still_pending.push(entry)
    if still_pending 为空 或 本轮没有进展: break
}
self.pending = still_pending
start():          pending 非空 → Deadlock{pending: [(row id, [缺少的服务...])]}
start_lenient():  允许 pending 留存(宿主之后自己填槽)

5.2 运行中 patch(App::patch)

flowchart TD
  A[before = 树快照] --> B[tree.apply layer]
  B --> C[after = 新树]
  C --> D{逐行对比 before → after}
  D -- 被删除 --> U1[unload_row]
  D -- 新为 disabled 且旧为 enabled --> U1
  D -- name/config 变化,或旧为 disabled --> U2[unload_row 并加入 to_mount]
  D -- 未变 --> K[保持运行,服务与监听器不受扰动]
  C --> E[after 中新增且未禁用的行 → to_mount]
  E --> F[之前 pending 的行,取当前形态 → to_mount]
  F --> G[按树中顺序排序,保证确定性]
  G --> H[mount_all to_mount]

5.3 卸载与停止

App::stop():   把 mounted 中的 fiber 按 id 从大到小逐个卸载(最新挂载的先卸)
FiberTable::unload(id): 递归卸载子 fiber → 移出表 → dispose_all()(逆序回放账本)
Drop for App:  调用 stop()

5.4 子 agent 的 realm 用法(摘自 docs/plexus-plugin-architecture.md §四)

let child = self.ctx.isolate();           // 一个自己的 realm
child.provide::<ToolsSvc>(restricted)?;   // 自己的工具目录,父 realm 不受影响
child.provide::<SessionSvc>(own_log)?;    // 自己的会话
child.plugin("agent-loop", cfg).await?;   // 把循环挂进这个 realm
ROOT_REALM ── llm, approval(凭据门), tools(全量), system-prompt …
   ├─ realm 1 (lead 会话)  ── sessions(lead 日志), cwd …
   │     └─ realm 3 (lead/alice 成员) ── tools(受限), sessions(成员日志)
   └─ realm 2 (task 子 agent) ── tools(只读), sessions(子日志)
查找方向:3 → 1 → 0(向上);0 看不到 1/2/3 添加的内容;2 和 3 互不可见

5.5 审计(App::audit_with(host_consumed, host_provided))

审计把每一行的声明与运行中的实际情况对照,报告四类不一致:

AuditFinding 含义 is_defect()
DeclaredButNotProvided{entry, service} 声明了 provides,但槽是空的,属于半挂载 ✔
ProvidedButNotDeclared{entry, service} 填了槽但没有声明(只看根 realm),能力图看不到它 ✔
InjectedButUnprovidable{service, consumers} inject/uses 了一个没有任何已注册插件能提供的服务,可能是拼写错误或漏了行 ✔
ProvidedButUnused{service} 提供了但没人消费 ✗(只是观察,不算缺陷)

6. 配置项与环境变量

plexus 本身不读任何环境变量和文件。配置的唯一输入是 ConfigTree。

层的 TOML 格式(Layer::from_toml):

[[insert]]
id = "llm-openai-compat"        # 可省略,缺省等于 name
name = "llm-openai-compat"
disabled = false                # 可省略
config = { model = "deepseek-chat" }   # 省略时为空对象 {}

[[patch]]
id = "approval"
config = { mode = "auto" }      # 整体替换!
# disabled = true               # 可选
# name = "approval-ask"         # 可选:swap 提供方

[[remove]]
id = "telemetry"

7. 持久化格式与协议

- <id>[ (disabled)][  <- <plugin name>(仅当 id != name 时显示)]
    <config 的 pretty JSON,每行缩进 4 格>(config 为 Null 或 {} 时省略)

8. 扩展点

扩展什么 怎么做
新能力(缝) 用 plexus_service!(Key => dyn Trait, "name", Seam/Core/Bundle, "title") 定义服务
新的提供方或消费方 实现 Plugin,在 PluginRegistry::register 中注册,然后在配置树中加一行
横切策略 用 plexus_event! 定义事件,在 apply 中用 ctx.on_waterfall 等方法挂监听器
替换实现 在 patch 层中执行 swap(id, new_name);运行中可用 App::patch
关闭某个功能 disable(id),或在 TOML 中写 [[patch]] disabled = true
隔离作用域 ctx.isolate(),或 ctx.plugin_isolated(name, cfg)
子组合 在 apply 中调用 ctx.plugin(name, cfg),卸载时会级联撤销
任意可逆副作用 ctx.effect(move \|\| undo())

ADR 0019 指出了一个缺口:工具、提示词片段等“往聚合体里塞东西”的贡献都写在 apply 内部,--dump-seams 只能看到 provide()。该 ADR 提议把贡献者也做成可以声明的“行”,状态为“提议”。


9. 错误语义(src/error.rs)

#[non_exhaustive]
pub enum PlexusError {
    UnknownPlugin   { entry: String, plugin: String },          // 同时给出行 id 和插件名,因为 patch 通常只写对其中一个
    ServiceConflict { name, held_by: String, claimed_by: String },
    ServiceMissing  { name },                                    // 运行时读到空槽(require)
    Deadlock        { pending: Vec<(String /*row*/, Vec<String> /*missing*/)> },
    Apply           { entry: String, message: String },          // 插件 apply 返回的 Err,包上行 id
    Config(String),                                              // 层解析失败、patch 指向不存在的行
}

10. 测试与判据

测试函数名本身就是判据,下面按文件列出。

tests/runtime.rs(约 30 个测试):

主张 测试
依赖关系决定激活顺序,与文件顺序无关 dependencies_drive_activation_not_file_order
运行中可以 swap 提供方 a_patch_swaps_a_provider_under_a_running_consumer
卸载恰好撤销插件注册过的东西 unloading_reverts_exactly_what_the_plugin_registered
挂载停滞时报出行和缺失的服务 a_stalled_mount_names_the_row_and_the_service_it_waits_for
同一槽有两个提供方会报错 two_providers_for_one_slot_is_an_error_not_a_silent_overwrite
realm 覆盖一个槽不影响父 realm a_realm_overrides_one_slot_without_disturbing_its_parent
五种事件模式 emit_and_parallel_reach_every_listener、serial_and_bail_stop_at_the_first_decision、bail_matches_on_its_own_predicate、waterfall_wraps_the_terminal_in_registration_order、a_waterfall_listener_can_own_the_decision
卸载会移除监听器 unloading_removes_the_listeners_a_plugin_attached
realm 对监听器的可见性 a_listener_in_a_realm_is_invisible_to_its_parent、a_listener_at_the_root_still_governs_every_realm、sibling_realms_do_not_see_each_other、root_policy_wraps_agent_policy_not_the_other_way_round、services_and_listeners_agree_on_what_a_realm_means、listener_counts_are_reported_per_realm
子插件与 realm a_plugin_can_be_mounted_into_its_own_realm、plugin_isolated_mounts_and_hands_back_the_scope
pending 语义 a_row_that_cannot_mount_yet_waits_instead_of_being_lost、strict_start_still_refuses_to_come_up_half_wired

tests/layer_builder.rs:

审计相关的测试位于 harness,文档称共有 11 个,其中包括两个故意“说谎”的插件。


11. 设计要点与陷阱

  1. Op::Patch.config 是整体替换,不做深合并(cordis 语义)。注释说这一点“已经造成三个真实 bug”:patch 时漏写的 key 不会保留旧值,插件会读到 serde 默认值,而且 --dump-config 也看不出有人改过。要改一个 key 就必须把其余 key 一起带上。atomcode-coding 中的 no_row_silently_loses_a_configured_field 测试就是为此而写。
  2. Entry::with 不做校验:NaN 会被转成 null。
  3. 不存在特权内核:agent 循环、前端(ui 行)、审批都是行,都可以被 swap 或 disable。代价是“为什么我的 agent 是这样”更难回答,所以 --dump-config、--dump-seams 和 --audit 是必需品,不是锦上添花。
  4. 卸载没有 quiescence:正在执行的调用靠 Arc 保证不出现悬垂引用,但运行时不会等它们完成(文档 §十一)。
  5. 服务不能缓存:消费方必须每次调用都重新解析服务,否则 swap 之后仍会拿着旧的提供方。
  6. 单一提供方的 Seam 只是名义上的缝:能力图会对“声明为 Seam 但提供方少于两个”的服务给出提示。
  7. realm 可见性必须对服务和事件同时成立,只做一半会造成虚假的隔离。
  8. Waterfall 的顺序:根上的策略先注册,所以包在外层;prepend=true 的监听器可以插到更前面。
  9. TOML 层内部的 op 顺序固定为 insert → patch → remove。
  10. 编译期插件清单:安装第三方插件仍需重新编译,除非走 MCP 等进程外桥接。

12. 对 OpenTMD(Go)可借鉴之处

OpenTMD 是一个模块化单体(见 .github/copilot-instructions.md)。目前各模块的组合是在 cmd/opentmd 和 internal/agent 里硬编码的,所以下面只建议引入轻量版机制:

plexus 机制 Go 版落地建议
ServiceKey + SeamMode 增加 internal/plug 包:type Key[T any] struct{ Name string; Mode SeamMode; Title string },内部用 map[string]any 加泛型 Get[T](ctx, key);在 key 的定义处写明 Core、Seam 或 Bundle
Plugin{Inject, Uses, Provides, Apply} type Plugin interface{ Name() string; Inject() []string; Provides() []string; Apply(ctx *Ctx, cfg json.RawMessage) error },用不动点循环挂载,文件中的顺序无关
fiber 账本 + Disposable ctx.Defer(func()) 记录撤销函数,卸载时逆序执行(与 Go 的 defer 语义相同);子插件挂在父插件下,卸载时级联
配置树 + Layer{insert, patch(swap/disable), remove} 在 ~/.opentmd/config.toml 之外支持 [[patch]] id="permission" name="permission-readonly",使 hooks、MCP、permission 策略、TUI 前端都能被替换或禁用;明确 config 是整体替换
App::audit 在测试中断言“声明的 Provides 都被填了槽”“Inject 都有提供方”,防止接线随时间腐化
realm 单向可见 子 agent(若将来实现)用 ctx.Isolate(),覆盖 tools 和 session;根上的 permission 和 hook 对子 agent 依旧生效,避免通过子 agent 绕过审批
Waterfall 事件 OpenTMD 的 PreToolUse hook 可以统一成 func(ctx, *Call, next) Decision 洋葱链;内置的 permission 检查作为根层,用户 hook 作为内层
--dump-config / --dump-seams 增加 opentmd config dump,打印最终生效的模块树和来源层

需要注意,在 Go 中引入完整的 plexus 成本较高。可以先只做“服务槽冲突即报错”和“可逆注册”这两项,它们能直接解决 MCP 工具动态挂载、卸载时容易出现的残留问题。