Skip to main content

byob_protocol/
plugins.rs

1//! Plugins as clients see them: what a chat can use, where each plugin comes from, whether
2//! it is on, which settings it still needs, and what went wrong loading it.
3//!
4//! A plugin is a folder with a `byob-plugin.json` (tools, skills, subagents, MCP servers,
5//! settings). It lives in one of three scopes; the same id resolves chat > workspace >
6//! global, and the less specific copy is listed with [`PluginInfo::shadowed_by`]:
7//!
8//! - **chat** (scratch): `<data>/chats/<chat>/plugins/<id>`; what the model made in this
9//!   chat with `make_tool` and friends. Never asked about; gone with the chat.
10//! - **workspace**: `<workspace>/.byob/plugins/<id>`, committed with the repo.
11//! - **global**: `<config>/plugins/<id>` (plus `settings.json` `plugin_dirs` and `--plugin`).
12//!
13//! The engine sends [`ServerMsg::Extensions`](crate::ServerMsg::Extensions) for the chat a
14//! client looks at after [`ServerMsg::ChatOpened`](crate::ServerMsg::ChatOpened), and again
15//! whenever something changes (a reload, a switch, a setting, a server connecting). Setting
16//! values never leave the engine: clients only learn whether each one is set.
17//!
18//! [`Extensions::slash`] lists what a message may start with (`/name args`): the engine
19//! expands it when the turn starts (see [`SlashKind`]).
20
21use serde::{Deserialize, Serialize};
22
23use crate::workspace::{ConfigScope, Level};
24
25/// Most characters of a plugin setting's value.
26pub const MAX_SETTING_VALUE_CHARS: usize = 8192;
27/// Most plugins one [`crate::ClientMsg::TrustPlugins`] may name.
28pub const MAX_TRUSTED_AT_ONCE: usize = 200;
29
30/// Where a plugin lives (see the module docs).
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum PluginScope {
34    Global,
35    Workspace,
36    Chat,
37}
38
39impl PluginScope {
40    pub fn label(self) -> &'static str {
41        match self {
42            Self::Global => "everywhere",
43            Self::Workspace => "this workspace",
44            Self::Chat => "this chat",
45        }
46    }
47}
48
49/// Who wrote a plugin.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum PluginOrigin {
53    /// Ships with byob.
54    Bundled,
55    /// The user installed or wrote it (global plugins byob didn't make).
56    User,
57    /// byob made it: the model in a chat, possibly kept into a workspace or everywhere.
58    Agent,
59    /// It arrived with the workspace folder (a clone or pull). Its tools and servers wait
60    /// for the user's OK ([`PluginInfo::trusted`]).
61    Repo,
62}
63
64/// The state of one of a plugin's MCP servers.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum ServerState {
68    /// Starting in the background; its tools come in a later round.
69    Connecting,
70    Ready,
71    Failed,
72    /// Not started: the plugin is off, not trusted, or misses a setting.
73    Off,
74}
75
76/// One of a plugin's MCP servers.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct ServerInfo {
79    pub name: String,
80    pub state: ServerState,
81    /// Tools it offers (when ready).
82    #[serde(default)]
83    pub tools: u32,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub error: Option<String>,
86}
87
88/// A value a plugin asks the user for (an API key, a folder). The value itself never
89/// reaches clients.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct PluginSetting {
92    /// The environment variable it becomes, e.g. `WEATHER_API_KEY`.
93    pub key: String,
94    pub label: String,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub help: Option<String>,
97    /// Kept in secrets.json; show a password field.
98    pub secret: bool,
99    pub required: bool,
100    /// It has a value (the user's or a default).
101    pub set: bool,
102}
103
104/// One plugin a chat can see.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct PluginInfo {
107    pub id: String,
108    pub name: String,
109    pub version: String,
110    #[serde(default)]
111    pub description: String,
112    /// A lucide icon name.
113    #[serde(default)]
114    pub icon: String,
115    pub scope: PluginScope,
116    pub origin: PluginOrigin,
117    /// Its folder on the engine's machine, for display.
118    pub dir: String,
119    /// Switched on for this chat (the plugin switches, global → workspace → chat).
120    pub enabled: bool,
121    /// The level whose switch decides [`Self::enabled`] (`Default`: nobody switched it; on).
122    pub enabled_from: Level,
123    /// Its tools and servers may run. False for a [`PluginOrigin::Repo`] plugin until the
124    /// user trusts it ([`crate::ClientMsg::TrustPlugins`]); until then only its skills,
125    /// prompt line and subagents are used.
126    pub trusted: bool,
127    /// The user declined to trust it (not asked again).
128    #[serde(default)]
129    pub declined: bool,
130    /// A plugin with the same id in a more specific scope is used instead of this one.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub shadowed_by: Option<PluginScope>,
133    /// Tool names as the model sees them (Python tools and MCP tools), when in use.
134    #[serde(default)]
135    pub tools: Vec<String>,
136    #[serde(default)]
137    pub skills: Vec<String>,
138    /// Subagent names.
139    #[serde(default)]
140    pub agents: Vec<String>,
141    /// Slash commands (`commands/*.md`, Claude Code's format).
142    #[serde(default)]
143    pub commands: Vec<String>,
144    #[serde(default)]
145    pub servers: Vec<ServerInfo>,
146    #[serde(default)]
147    pub settings: Vec<PluginSetting>,
148    /// Its tools may use the internet (`permissions.network`).
149    #[serde(default)]
150    pub network: bool,
151    /// What doesn't work (a missing script, a bad skill, a missing setting); the parts that
152    /// work are still used. Messages are the loader's, for the plugin's author.
153    #[serde(default)]
154    pub problems: Vec<String>,
155    /// The last failed run of one of its tools in this engine run.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub last_error: Option<String>,
158    /// Changes whenever a file of the plugin changes (hex).
159    #[serde(default)]
160    pub fingerprint: String,
161}
162
163/// A plugin folder that couldn't load at all (bad manifest, duplicate id).
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165pub struct PluginLoadError {
166    pub scope: PluginScope,
167    /// The folder.
168    pub path: String,
169    pub message: String,
170}
171
172/// Every plugin the chat in view can see (also the new chat a client is about to start).
173#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174pub struct Extensions {
175    /// `None`: the new chat this client is about to start.
176    pub chat: Option<String>,
177    /// Its workspace, if registered.
178    pub workspace: Option<String>,
179    /// Chat scope first, then workspace, then global; by id within a scope.
180    pub plugins: Vec<PluginInfo>,
181    #[serde(default)]
182    pub errors: Vec<PluginLoadError>,
183    /// What the composer's `/` menu offers: built-in commands, then plugin commands, then
184    /// skills (the same name only once).
185    #[serde(default)]
186    pub slash: Vec<SlashItem>,
187}
188
189/// What a `/name` at the start of a message is.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum SlashKind {
193    /// Built into byob (`/compact`).
194    Builtin,
195    /// A plugin's `commands/<name>.md`: its prompt template, with the arguments filled in,
196    /// is what the model gets.
197    Command,
198    /// A skill: the model is told to use it, the arguments are the task.
199    Skill,
200}
201
202/// One entry of the `/` menu.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct SlashItem {
205    /// What follows the `/`.
206    pub name: String,
207    pub kind: SlashKind,
208    #[serde(default)]
209    pub description: String,
210    /// What to type after the name, e.g. `<file> [focus]`.
211    #[serde(default, skip_serializing_if = "String::is_empty")]
212    pub hint: String,
213    /// Where it comes from (`None`: built in).
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub scope: Option<PluginScope>,
216    /// The plugin that brings it (`None`: built in, or a standalone skill).
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub plugin: Option<String>,
219}
220
221/// What a step did to a plugin.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
223#[serde(rename_all = "snake_case")]
224pub enum PluginAction {
225    /// `make_tool`: a tool was added or replaced.
226    Made,
227    /// `edit_plugin` / `write_plugin_file`.
228    Edited,
229    /// `keep_plugin`: copied into a workspace or everywhere.
230    Kept,
231    /// `remove_plugin`.
232    Removed,
233}
234
235/// The result of running a tool once with test arguments (`make_tool`'s `try_args`).
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct PluginTest {
238    pub ok: bool,
239    /// The output, or the end of the traceback (bounded).
240    pub output: String,
241}
242
243/// A "plugin card" on a step that changed a plugin ([`crate::Step::plugin`]).
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245pub struct PluginCard {
246    pub plugin: String,
247    pub scope: PluginScope,
248    pub action: PluginAction,
249    /// The plugin's tools after the change (model-facing names).
250    #[serde(default)]
251    pub tools: Vec<String>,
252    /// Tools that appeared or went away with this change.
253    #[serde(default)]
254    pub added: Vec<String>,
255    #[serde(default)]
256    pub removed: Vec<String>,
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub test: Option<PluginTest>,
259    /// The loader's problems after the change.
260    #[serde(default)]
261    pub problems: Vec<String>,
262    /// Labels of required settings without a value (show the settings field).
263    #[serde(default)]
264    pub missing_settings: Vec<String>,
265}
266
267/// The plugin messages' size checks (see [`crate::ClientMsg::check_sizes`]).
268pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
269    use crate::ClientMsg;
270    let id =
271        |s: &str| if byob_types::config::plugin_id_ok(s) { Ok(()) } else { Err(format!("{:?} isn't a plugin id", s.chars().take(60).collect::<String>())) };
272    match msg {
273        ClientMsg::SetPluginEnabled { scope, plugin, .. } => {
274            if let ConfigScope::Workspace { id: w } = scope
275                && (w.is_empty() || w.len() > crate::workspace::MAX_ID_CHARS)
276            {
277                return Err("bad id".into());
278            }
279            id(plugin)
280        }
281        ClientMsg::SetPluginSetting { plugin, key, value } => {
282            id(plugin)?;
283            if key.is_empty() || key.len() > 64 {
284                return Err("bad setting name".into());
285            }
286            if value.as_ref().is_some_and(|v| v.chars().count() > MAX_SETTING_VALUE_CHARS || v.contains('\0')) {
287                return Err(format!("a setting's value can be at most {MAX_SETTING_VALUE_CHARS} characters"));
288            }
289            Ok(())
290        }
291        ClientMsg::KeepPlugin { plugin, new_id, .. } => {
292            id(plugin)?;
293            new_id.as_deref().map_or(Ok(()), id)
294        }
295        ClientMsg::RemovePlugin { plugin, .. } => id(plugin),
296        ClientMsg::TrustPlugins { workspace, plugins, .. } => {
297            if workspace.is_empty() || workspace.len() > crate::workspace::MAX_ID_CHARS {
298                return Err("bad id".into());
299            }
300            if plugins.len() > MAX_TRUSTED_AT_ONCE {
301                return Err("too many plugins".into());
302            }
303            plugins.iter().try_for_each(|p| id(p))
304        }
305        _ => Ok(()),
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312    use crate::{ClientMsg, ServerMsg};
313
314    fn info() -> PluginInfo {
315        PluginInfo {
316            id: "weather".into(),
317            name: "Weather".into(),
318            version: "0.1.0".into(),
319            description: String::new(),
320            icon: "puzzle".into(),
321            scope: PluginScope::Chat,
322            origin: PluginOrigin::Agent,
323            dir: "/d/chats/c1/plugins/weather".into(),
324            enabled: true,
325            enabled_from: Level::Default,
326            trusted: true,
327            declined: false,
328            shadowed_by: None,
329            tools: vec!["weather".into()],
330            skills: vec![],
331            agents: vec![],
332            commands: vec![],
333            servers: vec![ServerInfo { name: "s".into(), state: ServerState::Connecting, tools: 0, error: None }],
334            settings: vec![PluginSetting { key: "API_KEY".into(), label: "API key".into(), help: None, secret: true, required: true, set: false }],
335            network: true,
336            problems: vec!["tools/x.py is missing".into()],
337            last_error: Some("boom".into()),
338            fingerprint: "00ff".into(),
339        }
340    }
341
342    #[test]
343    fn plugin_messages_round_trip_and_are_checked() {
344        let ext = Extensions {
345            chat: Some("c1".into()),
346            workspace: Some("w1".into()),
347            plugins: vec![info()],
348            errors: vec![PluginLoadError { scope: PluginScope::Global, path: "/p".into(), message: "bad".into() }],
349            slash: vec![SlashItem {
350                name: "review".into(),
351                kind: SlashKind::Command,
352                description: "Review a file".into(),
353                hint: "<file>".into(),
354                scope: Some(PluginScope::Workspace),
355                plugin: Some("code".into()),
356            }],
357        };
358        let m = ServerMsg::Extensions(Box::new(ext));
359        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
360        let ok = vec![
361            ClientMsg::GetExtensions,
362            ClientMsg::ReloadPlugins,
363            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "weather".into(), enabled: Some(false) },
364            ClientMsg::SetPluginEnabled { scope: ConfigScope::Workspace { id: "w1".into() }, plugin: "weather".into(), enabled: None },
365            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "API_KEY".into(), value: Some("sk".into()) },
366            ClientMsg::KeepPlugin { plugin: "scratch".into(), scope: PluginScope::Workspace, new_id: Some("weather".into()) },
367            ClientMsg::RemovePlugin { plugin: "weather".into(), scope: PluginScope::Chat },
368            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec![], trust: true },
369        ];
370        for m in ok {
371            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
372            assert!(m.check_sizes().is_ok(), "{}", m.to_json());
373        }
374        for bad in [
375            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "../x".into(), enabled: Some(true) },
376            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "K".into(), value: Some("x".repeat(MAX_SETTING_VALUE_CHARS + 1)) },
377            ClientMsg::KeepPlugin { plugin: "a".into(), scope: PluginScope::Global, new_id: Some("Bad".into()) },
378            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec!["ok".into(); MAX_TRUSTED_AT_ONCE + 1], trust: true },
379        ] {
380            assert!(bad.check_sizes().is_err(), "{}", bad.to_json());
381        }
382        let card = PluginCard {
383            plugin: "scratch".into(),
384            scope: PluginScope::Chat,
385            action: PluginAction::Made,
386            tools: vec!["weather".into()],
387            added: vec!["weather".into()],
388            removed: vec![],
389            test: Some(PluginTest { ok: false, output: "Traceback…".into() }),
390            problems: vec![],
391            missing_settings: vec!["API key".into()],
392        };
393        let json = serde_json::to_string(&card).unwrap();
394        assert_eq!(serde_json::from_str::<PluginCard>(&json).unwrap(), card);
395    }
396}