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    /// Ships inside byob (13.4+, cap [`crate::version::CAP_BUNDLED_SCOPE`]; older clients
35    /// are told `global` with origin `bundled`). The least specific: any other copy with
36    /// the same id wins (a fork).
37    Bundled,
38    Global,
39    Workspace,
40    Chat,
41}
42
43impl PluginScope {
44    pub fn label(self) -> &'static str {
45        match self {
46            Self::Bundled => "built in",
47            Self::Global => "everywhere",
48            Self::Workspace => "this workspace",
49            Self::Chat => "this chat",
50        }
51    }
52}
53
54/// Who wrote a plugin.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum PluginOrigin {
58    /// Ships with byob.
59    Bundled,
60    /// The user installed or wrote it (global plugins byob didn't make).
61    User,
62    /// byob made it: the model in a chat, possibly kept into a workspace or everywhere.
63    Agent,
64    /// It arrived with the workspace folder (a clone or pull). Its tools and servers wait
65    /// for the user's OK ([`PluginInfo::trusted`]).
66    Repo,
67}
68
69/// The state of one of a plugin's MCP servers.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum ServerState {
73    /// Starting in the background; its tools come in a later round.
74    Connecting,
75    Ready,
76    Failed,
77    /// Not started: the plugin is off, not trusted, or misses a setting.
78    Off,
79}
80
81/// One of a plugin's MCP servers.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct ServerInfo {
84    pub name: String,
85    pub state: ServerState,
86    /// Tools it offers (when ready).
87    #[serde(default)]
88    pub tools: u32,
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub error: Option<String>,
91}
92
93/// A plugin's long-lived backend process (13.2+; see `docs/plugins-backend.md`).
94#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
95pub struct BackendInfo {
96    /// `idle` (starts on first use), `starting`, `running`, `crashed` (restarting),
97    /// `failed` (given up until the plugin reloads), `stopped`, `off` (missing settings),
98    /// or a state a newer engine knows.
99    pub state: String,
100    /// Times it was started in this engine run.
101    #[serde(default)]
102    pub starts: u32,
103    /// Why it isn't running.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub error: Option<String>,
106    /// The newest problems it reported (`fault`) or byob found in its output.
107    #[serde(default, skip_serializing_if = "Vec::is_empty")]
108    pub faults: Vec<String>,
109    /// The end of its stderr (≤ 4 KiB).
110    #[serde(default, skip_serializing_if = "String::is_empty")]
111    pub stderr: String,
112}
113
114/// A value a plugin asks the user for (an API key, a folder). The value itself never
115/// reaches clients.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct PluginSetting {
118    /// The environment variable it becomes, e.g. `WEATHER_API_KEY`.
119    pub key: String,
120    pub label: String,
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub help: Option<String>,
123    /// Kept in secrets.json; show a password field.
124    pub secret: bool,
125    pub required: bool,
126    /// It has a value (the user's or a default).
127    pub set: bool,
128}
129
130/// One plugin a chat can see.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132pub struct PluginInfo {
133    pub id: String,
134    pub name: String,
135    pub version: String,
136    #[serde(default)]
137    pub description: String,
138    /// A lucide icon name.
139    #[serde(default)]
140    pub icon: String,
141    pub scope: PluginScope,
142    pub origin: PluginOrigin,
143    /// Its folder on the engine's machine, for display.
144    pub dir: String,
145    /// Switched on for this chat (the plugin switches, global → workspace → chat).
146    pub enabled: bool,
147    /// The level whose switch decides [`Self::enabled`] (`Default`: nobody switched it; on).
148    pub enabled_from: Level,
149    /// Its tools and servers may run. False for a [`PluginOrigin::Repo`] plugin until the
150    /// user trusts it ([`crate::ClientMsg::TrustPlugins`]); until then only its skills,
151    /// prompt line and subagents are used.
152    pub trusted: bool,
153    /// The user declined to trust it (not asked again).
154    #[serde(default)]
155    pub declined: bool,
156    /// A plugin with the same id in a more specific scope is used instead of this one.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub shadowed_by: Option<PluginScope>,
159    /// Tool names as the model sees them (Python tools and MCP tools), when in use.
160    #[serde(default)]
161    pub tools: Vec<String>,
162    #[serde(default)]
163    pub skills: Vec<String>,
164    /// Subagent names.
165    #[serde(default)]
166    pub agents: Vec<String>,
167    /// Slash commands (`commands/*.md`, Claude Code's format).
168    #[serde(default)]
169    pub commands: Vec<String>,
170    #[serde(default)]
171    pub servers: Vec<ServerInfo>,
172    /// Its backend process, if it declares one.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub backend: Option<BackendInfo>,
175    /// The views it declares (13.3+), shown at their sites while it is on (see
176    /// [`crate::sites`]).
177    #[serde(default, skip_serializing_if = "Vec::is_empty")]
178    pub views: Vec<crate::ViewDecl>,
179    #[serde(default)]
180    pub settings: Vec<PluginSetting>,
181    /// Its tools may use the internet (`permissions.network`).
182    #[serde(default)]
183    pub network: bool,
184    /// What doesn't work (a missing script, a bad skill, a missing setting); the parts that
185    /// work are still used. Messages are the loader's, for the plugin's author.
186    #[serde(default)]
187    pub problems: Vec<String>,
188    /// The last failed run of one of its tools in this engine run.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub last_error: Option<String>,
191    /// Changes whenever a file of the plugin changes (hex).
192    #[serde(default)]
193    pub fingerprint: String,
194    /// Always on: its switch can't turn it off (13.4+; core bundled plugins and their forks).
195    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
196    pub locked: bool,
197    /// Which renderer draws a content type while it is on (13.4+).
198    #[serde(default, skip_serializing_if = "Vec::is_empty")]
199    pub renderers: Vec<RendererDecl>,
200    /// Prompt suggestions for an empty chat (13.4+).
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub starters: Vec<StarterDecl>,
203    /// Switched on, but another switched-on plugin providing the same thing (its id) is used
204    /// instead (13.7+; manifest `provides`): this one contributes nothing until one of them
205    /// is switched off.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub superseded_by: Option<String>,
208}
209
210impl PluginInfo {
211    /// This copy is the one in use when switched on: not shadowed by a more specific copy,
212    /// not superseded by another plugin providing the same thing.
213    pub fn in_use(&self) -> bool {
214        self.shadowed_by.is_none() && self.superseded_by.is_none()
215    }
216}
217
218/// A plugin's renderer for one content type: `renderer` is `web` (the web surface), `text`
219/// (the source) or `native:<id>` (one of the client's in-tree renderers). A client that
220/// doesn't have it shows the text source.
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222pub struct RendererDecl {
223    pub content_type: String,
224    pub renderer: String,
225}
226
227/// A suggestion for an empty chat: `title` on the button, `prompt` sent (or put in the
228/// composer).
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct StarterDecl {
231    pub title: String,
232    pub prompt: String,
233}
234
235/// A plugin folder that couldn't load at all (bad manifest, duplicate id).
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct PluginLoadError {
238    pub scope: PluginScope,
239    /// The folder.
240    pub path: String,
241    pub message: String,
242}
243
244/// Every plugin the chat in view can see (also the new chat a client is about to start).
245#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
246pub struct Extensions {
247    /// `None`: the new chat this client is about to start.
248    pub chat: Option<String>,
249    /// Its workspace, if registered.
250    pub workspace: Option<String>,
251    /// Chat scope first, then workspace, then global; by id within a scope.
252    pub plugins: Vec<PluginInfo>,
253    #[serde(default)]
254    pub errors: Vec<PluginLoadError>,
255    /// What the composer's `/` menu offers: built-in commands, then plugin commands, then
256    /// skills (the same name only once).
257    #[serde(default)]
258    pub slash: Vec<SlashItem>,
259}
260
261/// What a `/name` at the start of a message is.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "snake_case")]
264pub enum SlashKind {
265    /// Built into byob (`/compact`).
266    Builtin,
267    /// A plugin's `commands/<name>.md`: its prompt template, with the arguments filled in,
268    /// is what the model gets.
269    Command,
270    /// A skill: the model is told to use it, the arguments are the task.
271    Skill,
272    /// A kind a newer engine sends that this client doesn't know (offered like a command).
273    #[serde(other)]
274    Other,
275}
276
277/// One entry of the `/` menu.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct SlashItem {
280    /// What follows the `/`.
281    pub name: String,
282    pub kind: SlashKind,
283    #[serde(default)]
284    pub description: String,
285    /// What to type after the name, e.g. `<file> [focus]`.
286    #[serde(default, skip_serializing_if = "String::is_empty")]
287    pub hint: String,
288    /// Where it comes from (`None`: built in).
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub scope: Option<PluginScope>,
291    /// The plugin that brings it (`None`: built in, or a standalone skill).
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub plugin: Option<String>,
294}
295
296/// What a step did to a plugin.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "snake_case")]
299pub enum PluginAction {
300    /// `make_tool`: a tool was added or replaced.
301    Made,
302    /// `edit_plugin` / `write_plugin_file`.
303    Edited,
304    /// `keep_plugin`: copied into a workspace or everywhere.
305    Kept,
306    /// `remove_plugin`.
307    Removed,
308    /// An action a newer engine reports that this client doesn't know ("changed").
309    #[serde(other)]
310    Other,
311}
312
313/// The result of running a tool once with test arguments (`make_tool`'s `try_args`).
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct PluginTest {
316    pub ok: bool,
317    /// The output, or the end of the traceback (bounded).
318    pub output: String,
319}
320
321/// A "plugin card" on a step that changed a plugin ([`crate::Step::plugin`]).
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323pub struct PluginCard {
324    pub plugin: String,
325    pub scope: PluginScope,
326    pub action: PluginAction,
327    /// The plugin's tools after the change (model-facing names).
328    #[serde(default)]
329    pub tools: Vec<String>,
330    /// Tools that appeared or went away with this change.
331    #[serde(default)]
332    pub added: Vec<String>,
333    #[serde(default)]
334    pub removed: Vec<String>,
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub test: Option<PluginTest>,
337    /// The loader's problems after the change.
338    #[serde(default)]
339    pub problems: Vec<String>,
340    /// Labels of required settings without a value (show the settings field).
341    #[serde(default)]
342    pub missing_settings: Vec<String>,
343}
344
345impl crate::ViewData for PluginCard {
346    const KIND: &'static str = "byob.plugin_card";
347    const V: u32 = 1;
348
349    fn fallback(&self) -> String {
350        let action = match self.action {
351            PluginAction::Made => "tool made",
352            PluginAction::Edited => "edited",
353            PluginAction::Kept => "kept",
354            PluginAction::Removed => "removed",
355            PluginAction::Other => "changed",
356        };
357        let mut out = format!("**Plugin {}** ({}) · {action}", self.plugin, self.scope.label());
358        if !self.tools.is_empty() {
359            out.push_str(&format!("\n\nTools: {}", self.tools.join(", ")));
360        }
361        if let Some(t) = &self.test {
362            out.push_str(if t.ok { "\n\nTest run passed" } else { "\n\nTest run failed" });
363        }
364        for p in &self.problems {
365            out.push_str(&format!("\n\n⚠ {p}"));
366        }
367        out
368    }
369}
370
371/// The plugin messages' size checks (see [`crate::ClientMsg::check_sizes`]).
372pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
373    use crate::ClientMsg;
374    let id =
375        |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>())) };
376    match msg {
377        ClientMsg::SetPluginEnabled { scope, plugin, .. } => {
378            if let ConfigScope::Workspace { id: w } = scope
379                && (w.is_empty() || w.len() > crate::workspace::MAX_ID_CHARS)
380            {
381                return Err("bad id".into());
382            }
383            id(plugin)
384        }
385        ClientMsg::SetPluginSetting { plugin, key, value } => {
386            id(plugin)?;
387            if key.is_empty() || key.len() > 64 {
388                return Err("bad setting name".into());
389            }
390            if value.as_ref().is_some_and(|v| v.chars().count() > MAX_SETTING_VALUE_CHARS || v.contains('\0')) {
391                return Err(format!("a setting's value can be at most {MAX_SETTING_VALUE_CHARS} characters"));
392            }
393            Ok(())
394        }
395        ClientMsg::KeepPlugin { plugin, new_id, .. } => {
396            id(plugin)?;
397            new_id.as_deref().map_or(Ok(()), id)
398        }
399        ClientMsg::RemovePlugin { plugin, .. } => id(plugin),
400        ClientMsg::TrustPlugins { workspace, plugins, .. } => {
401            if workspace.is_empty() || workspace.len() > crate::workspace::MAX_ID_CHARS {
402                return Err("bad id".into());
403            }
404            if plugins.len() > MAX_TRUSTED_AT_ONCE {
405                return Err("too many plugins".into());
406            }
407            plugins.iter().try_for_each(|p| id(p))
408        }
409        _ => Ok(()),
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use crate::{ClientMsg, ServerMsg};
417
418    fn info() -> PluginInfo {
419        PluginInfo {
420            id: "weather".into(),
421            name: "Weather".into(),
422            version: "0.1.0".into(),
423            description: String::new(),
424            icon: "puzzle".into(),
425            scope: PluginScope::Chat,
426            origin: PluginOrigin::Agent,
427            dir: "/d/chats/c1/plugins/weather".into(),
428            enabled: true,
429            enabled_from: Level::Default,
430            trusted: true,
431            declined: false,
432            shadowed_by: None,
433            tools: vec!["weather".into()],
434            skills: vec![],
435            agents: vec![],
436            commands: vec![],
437            servers: vec![ServerInfo { name: "s".into(), state: ServerState::Connecting, tools: 0, error: None }],
438            backend: None,
439            views: vec![],
440            settings: vec![PluginSetting { key: "API_KEY".into(), label: "API key".into(), help: None, secret: true, required: true, set: false }],
441            network: true,
442            problems: vec!["tools/x.py is missing".into()],
443            last_error: Some("boom".into()),
444            fingerprint: "00ff".into(),
445            locked: false,
446            renderers: vec![],
447            starters: vec![],
448            superseded_by: None,
449        }
450    }
451
452    #[test]
453    fn plugin_messages_round_trip_and_are_checked() {
454        let ext = Extensions {
455            chat: Some("c1".into()),
456            workspace: Some("w1".into()),
457            plugins: vec![info()],
458            errors: vec![PluginLoadError { scope: PluginScope::Global, path: "/p".into(), message: "bad".into() }],
459            slash: vec![SlashItem {
460                name: "review".into(),
461                kind: SlashKind::Command,
462                description: "Review a file".into(),
463                hint: "<file>".into(),
464                scope: Some(PluginScope::Workspace),
465                plugin: Some("code".into()),
466            }],
467        };
468        let m = ServerMsg::Extensions(Box::new(ext));
469        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
470        let ok = vec![
471            ClientMsg::GetExtensions,
472            ClientMsg::ReloadPlugins,
473            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "weather".into(), enabled: Some(false) },
474            ClientMsg::SetPluginEnabled { scope: ConfigScope::Workspace { id: "w1".into() }, plugin: "weather".into(), enabled: None },
475            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "API_KEY".into(), value: Some("sk".into()) },
476            ClientMsg::KeepPlugin { plugin: "scratch".into(), scope: PluginScope::Workspace, new_id: Some("weather".into()) },
477            ClientMsg::RemovePlugin { plugin: "weather".into(), scope: PluginScope::Chat },
478            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec![], trust: true },
479        ];
480        for m in ok {
481            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
482            assert!(m.check_sizes().is_ok(), "{}", m.to_json());
483        }
484        for bad in [
485            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "../x".into(), enabled: Some(true) },
486            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "K".into(), value: Some("x".repeat(MAX_SETTING_VALUE_CHARS + 1)) },
487            ClientMsg::KeepPlugin { plugin: "a".into(), scope: PluginScope::Global, new_id: Some("Bad".into()) },
488            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec!["ok".into(); MAX_TRUSTED_AT_ONCE + 1], trust: true },
489        ] {
490            assert!(bad.check_sizes().is_err(), "{}", bad.to_json());
491        }
492        let card = PluginCard {
493            plugin: "scratch".into(),
494            scope: PluginScope::Chat,
495            action: PluginAction::Made,
496            tools: vec!["weather".into()],
497            added: vec!["weather".into()],
498            removed: vec![],
499            test: Some(PluginTest { ok: false, output: "Traceback…".into() }),
500            problems: vec![],
501            missing_settings: vec!["API key".into()],
502        };
503        let json = serde_json::to_string(&card).unwrap();
504        assert_eq!(serde_json::from_str::<PluginCard>(&json).unwrap(), card);
505    }
506}