atomcode-plexusatomcode-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 行测试,由以下五个机制组成:
Plugin,声明 inject/uses/provides,在 apply(ctx, config) 中完成注册。ServiceKey),在编译期确定类型,每个服务带一个 SeamMode 分类。Layer 叠加成 ConfigTree,支持 insert、patch(含 swap、disable)、remove;运行中可以用 App::patch 热替换。另外还有 realm(作用域树):服务表和事件总线共用同一棵 realm 树,可见性只向上。它是“一个会话对应一个 realm”(ADR 0023)和子 agent 隔离的基础。
plexus 本身不认识 LLM、工具或会话,这些都由 atomcode-harness 定义成服务和插件,详见 assembly.md。
| 负责 | 不负责 |
|---|---|
把“行”(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 的两处实质差异:
ctx.fs 的类型,Rust 没有这个机制,所以改用 marker 类型携带服务的接口类型(Face)。字符串名只保留在配置行、inject 声明和诊断信息中。 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。
| 文件 | 行数 | 职责 | 主要公开项 |
|---|---|---|---|
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 |
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>; // 已排序
}
插件契约中值得注意的几点:
apply 安装的所有副作用(服务、监听器、子插件)都必须通过 ctx 登记,这样卸载时才能撤销。注释原文是 “must not stash registrations anywhere the fiber cannot see”。apply 返回 Err 时,运行时会卸载该 fiber,回滚已登记的部分。所以插件应该先执行可能失败的步骤,再做注册。uses 和 inject 的区别在于激活时机,而不在于“是否需要”。两者都算消费,都会出现在能力图上。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 的内部结构:
slots: RwLock<HashMap<(RealmId, TypeId), Slot>>,其中 Slot{name, value: Box<dyn Any>, owner: FiberId, owner_label}。by_name: HashMap<&str, TypeId>。这个索引存在的唯一理由是回答 inject: ["llm"] 这类字符串形式的依赖查询。value 里存的是 Arc<K::Face>。Arc<dyn Trait> 本身是 Sized 的,所以即使 Face 是 unsized 类型,也能经过 Any 存取。| 操作 | 语义 |
|---|---|
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 能看到的全部服务名 |
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 的祖先
}
可见性只朝一个方向,这是整个设计的关键:
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 是最内层的默认实现 |
EventBus::on_* 中有 assert!,模式不匹配会 panic。分发处另有 debug_assert_eq!。prepend 分组,组内按注册序号(seq)排序,即 sort_by_key(|r| (!r.prepend, r.seq))。collect() 用 visible_from(r.realm, viewer) 过滤监听器,所以 realm 内的监听器对父 realm 不可见,而根上的监听器对所有 realm 都生效。测试 root_policy_wraps_agent_policy_not_the_other_way_round 断言了一点:由于根监听器先注册,在 waterfall 中根策略包在 agent 策略的外层。Next 是 Copy,所以中间件可以多次调用 next.run,例如用来重试下游。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 卸载时:
parent == id 的那些),子先父后。Disposed。这个过程是幂等的。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);
}
Context 可以低成本 clone,clone 后仍绑定同一个 fiber 和 realm。因此插件把 ctx 交给 tokio::spawn 出去的任务后,任务里做的注册仍然会在卸载时撤销。record 中的 unwrap_or_else)。Context::plugin 也会检查 inject,但不会等待:缺少依赖时立即返回 Deadlock 错误。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 的特例:
swap(id, name):只改 name,保留行地址和 config。从 patch 文件替换某个缝的提供方,用的就是这个操作。disable(id) / enable(id):只改 disabled。被禁用的行留在树里,dump() 中显示为 (disabled)。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 留存(宿主之后自己填槽)
dependencies_drive_activation_not_file_order)。inject。uses 不影响激活,插件在运行时按需解析软依赖。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]
ctx.service::<K>() 重新解析,所以 swap 提供方之后,正在运行的消费方会自动用上新的提供方(测试 a_patch_swaps_a_provider_under_a_running_consumer)。a_row_that_cannot_mount_yet_waits_instead_of_being_lost)。patch 内部调用 mount_all,不会调用 fail_on_pending。因此运行中的 patch 是宽松的,start 才是严格的(测试 strict_start_still_refuses_to_come_up_half_wired)。App::stop(): 把 mounted 中的 fiber 按 id 从大到小逐个卸载(最新挂载的先卸)
FiberTable::unload(id): 递归卸载子 fiber → 移出表 → dispose_all()(逆序回放账本)
Drop for App: 调用 stop()
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 互不可见
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} |
提供了但没人消费 | ✗(只是观察,不算缺陷) |
host_consumed 和 host_provided 让宿主声明自己读了哪些槽(例如 launcher 直接读 ui、agent-loop)、自己填了哪些槽(例如 reconfigure)。否则这些槽会被误报。provides,不要求该插件已挂载。缝的提供方没挂上只是配置选择,不算缺陷。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"
from_toml 中的组装)。需要跨类别控制顺序时,应拆成多个层,或者使用 Layer::then。$ATOMCODE_HOME/harness.patch.toml,最后是 --patch 指定的文件。Entry、Op、Layer 都派生了 serde,Op 使用 rename_all = "snake_case",所以层可以在 JSON 和 TOML 之间转换。测试 a_built_layer_serializes_back_to_what_it_means 验证了这一点。ConfigTree::dump() 的输出格式(供 --dump-config 使用):- <id>[ (disabled)][ <- <plugin name>(仅当 id != name 时显示)]
<config 的 pretty JSON,每行缩进 4 格>(config 为 Null 或 {} 时省略)
App::dump_runtime() 依次输出三段:config tree:、fibers:(- [id] entry <- plugin (Status))和 services:。| 扩展什么 | 怎么做 |
|---|---|
| 新能力(缝) | 用 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 提议把贡献者也做成可以声明的“行”,状态为“提议”。
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 指向不存在的行
}
ServiceConflict)。错误信息会提示“先卸载现任,或者另开一个 realm”。pending 中的行会保留下来,等后续 patch 提供依赖。Deadlock 会列出每一行缺哪些服务,便于区分“忘了挂提供方”和“inject 拼错了”。ServiceMissing 与 Deadlock 的区别:前者发生在运行时读取,后者发生在挂载时等待。Config("patch targets row x, which no earlier layer inserted")。PluginRegistry::register 遇到重名会 panic,on_* 注册时模式不匹配也会 panic。两者都属于构建期或编程错误。expect 直接 panic,不做恢复。测试函数名本身就是判据,下面按文件列出。
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:
an_insert_means_the_same_written_either_way、every_edit_means_the_same_written_either_way:Rust 构建器写法与 TOML 写法得到的树相同。a_non_finite_number_becomes_null_rather_than_an_error:钉住一个非校验行为,f32::NAN 会变成 null。a_built_layer_serializes_back_to_what_it_means。审计相关的测试位于 harness,文档称共有 11 个,其中包括两个故意“说谎”的插件。
Op::Patch.config 是整体替换,不做深合并(cordis 语义)。注释说这一点“已经造成三个真实 bug”:patch 时漏写的 key 不会保留旧值,插件会读到 serde 默认值,而且 --dump-config 也看不出有人改过。要改一个 key 就必须把其余 key 一起带上。atomcode-coding 中的 no_row_silently_loses_a_configured_field 测试就是为此而写。Entry::with 不做校验:NaN 会被转成 null。ui 行)、审批都是行,都可以被 swap 或 disable。代价是“为什么我的 agent 是这样”更难回答,所以 --dump-config、--dump-seams 和 --audit 是必需品,不是锦上添花。Arc 保证不出现悬垂引用,但运行时不会等它们完成(文档 §十一)。prepend=true 的监听器可以插到更前面。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 工具动态挂载、卸载时容易出现的残留问题。