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    /// Changes to the screen while it's on (experimental fluid ops: `set`, `insert`).
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub fluid: Option<serde_json::Value>,
211    /// Its folder has a logo (`logo.png` or `logo.jpg`); ask for it with
212    /// [`crate::ClientMsg::GetPluginLogo`] (17+, cap [`crate::version::CAP_PLUGIN_LOGOS`]).
213    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
214    pub logo: bool,
215}
216
217impl PluginInfo {
218    /// This copy is the one in use when switched on: not shadowed by a more specific copy,
219    /// not superseded by another plugin providing the same thing.
220    pub fn in_use(&self) -> bool {
221        self.shadowed_by.is_none() && self.superseded_by.is_none()
222    }
223}
224
225/// A plugin's renderer for one content type: `renderer` is `web` (the web surface), `text`
226/// (the source) or `native:<id>` (one of the client's in-tree renderers). A client that
227/// doesn't have it shows the text source.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229pub struct RendererDecl {
230    pub content_type: String,
231    pub renderer: String,
232}
233
234/// A suggestion for an empty chat: `title` on the button, `prompt` sent (or put in the
235/// composer).
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct StarterDecl {
238    pub title: String,
239    pub prompt: String,
240}
241
242/// A plugin folder that couldn't load at all (bad manifest, duplicate id).
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub struct PluginLoadError {
245    pub scope: PluginScope,
246    /// The folder.
247    pub path: String,
248    pub message: String,
249}
250
251/// Every plugin the chat in view can see (also the new chat a client is about to start).
252#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
253pub struct Extensions {
254    /// `None`: the new chat this client is about to start.
255    pub chat: Option<String>,
256    /// Its workspace, if registered.
257    pub workspace: Option<String>,
258    /// Chat scope first, then workspace, then global; by id within a scope.
259    pub plugins: Vec<PluginInfo>,
260    #[serde(default)]
261    pub errors: Vec<PluginLoadError>,
262    /// What the composer's `/` menu offers: built-in commands, then plugin commands, then
263    /// skills (the same name only once).
264    #[serde(default)]
265    pub slash: Vec<SlashItem>,
266}
267
268/// What a `/name` at the start of a message is.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub enum SlashKind {
272    /// Built into byob (`/compact`).
273    Builtin,
274    /// A plugin's `commands/<name>.md`: its prompt template, with the arguments filled in,
275    /// is what the model gets.
276    Command,
277    /// A skill: the model is told to use it, the arguments are the task.
278    Skill,
279    /// A kind a newer engine sends that this client doesn't know (offered like a command).
280    #[serde(other)]
281    Other,
282}
283
284/// One entry of the `/` menu.
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct SlashItem {
287    /// What follows the `/`.
288    pub name: String,
289    pub kind: SlashKind,
290    #[serde(default)]
291    pub description: String,
292    /// What to type after the name, e.g. `<file> [focus]`.
293    #[serde(default, skip_serializing_if = "String::is_empty")]
294    pub hint: String,
295    /// Where it comes from (`None`: built in).
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub scope: Option<PluginScope>,
298    /// The plugin that brings it (`None`: built in, or a standalone skill).
299    #[serde(default, skip_serializing_if = "Option::is_none")]
300    pub plugin: Option<String>,
301}
302
303/// What a step did to a plugin.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
305#[serde(rename_all = "snake_case")]
306pub enum PluginAction {
307    /// `make_tool`: a tool was added or replaced.
308    Made,
309    /// `edit_plugin` / `write_plugin_file`.
310    Edited,
311    /// `keep_plugin`: copied into a workspace or everywhere.
312    Kept,
313    /// `remove_plugin`.
314    Removed,
315    /// An action a newer engine reports that this client doesn't know ("changed").
316    #[serde(other)]
317    Other,
318}
319
320/// The result of running a tool once with test arguments (`make_tool`'s `try_args`).
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322pub struct PluginTest {
323    pub ok: bool,
324    /// The output, or the end of the traceback (bounded).
325    pub output: String,
326}
327
328/// A "plugin card" on a step that changed a plugin ([`crate::Step::plugin`]).
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub struct PluginCard {
331    pub plugin: String,
332    pub scope: PluginScope,
333    pub action: PluginAction,
334    /// The plugin's tools after the change (model-facing names).
335    #[serde(default)]
336    pub tools: Vec<String>,
337    /// Tools that appeared or went away with this change.
338    #[serde(default)]
339    pub added: Vec<String>,
340    #[serde(default)]
341    pub removed: Vec<String>,
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub test: Option<PluginTest>,
344    /// The loader's problems after the change.
345    #[serde(default)]
346    pub problems: Vec<String>,
347    /// Labels of required settings without a value (show the settings field).
348    #[serde(default)]
349    pub missing_settings: Vec<String>,
350}
351
352impl crate::ViewData for PluginCard {
353    const KIND: &'static str = "byob.plugin_card";
354    const V: u32 = 1;
355
356    fn fallback(&self) -> String {
357        let action = match self.action {
358            PluginAction::Made => "tool made",
359            PluginAction::Edited => "edited",
360            PluginAction::Kept => "kept",
361            PluginAction::Removed => "removed",
362            PluginAction::Other => "changed",
363        };
364        let mut out = format!("**Plugin {}** ({}) · {action}", self.plugin, self.scope.label());
365        if !self.tools.is_empty() {
366            out.push_str(&format!("\n\nTools: {}", self.tools.join(", ")));
367        }
368        if let Some(t) = &self.test {
369            out.push_str(if t.ok { "\n\nTest run passed" } else { "\n\nTest run failed" });
370        }
371        for p in &self.problems {
372            out.push_str(&format!("\n\n⚠ {p}"));
373        }
374        out
375    }
376}
377
378/// The plugin messages' size checks (see [`crate::ClientMsg::check_sizes`]).
379pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
380    use crate::ClientMsg;
381    let id =
382        |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>())) };
383    match msg {
384        ClientMsg::SetPluginEnabled { scope, plugin, .. } => {
385            if let ConfigScope::Workspace { id: w } = scope
386                && (w.is_empty() || w.len() > crate::workspace::MAX_ID_CHARS)
387            {
388                return Err("bad id".into());
389            }
390            id(plugin)
391        }
392        ClientMsg::SetPluginSetting { plugin, key, value } => {
393            id(plugin)?;
394            if key.is_empty() || key.len() > 64 {
395                return Err("bad setting name".into());
396            }
397            if value.as_ref().is_some_and(|v| v.chars().count() > MAX_SETTING_VALUE_CHARS || v.contains('\0')) {
398                return Err(format!("a setting's value can be at most {MAX_SETTING_VALUE_CHARS} characters"));
399            }
400            Ok(())
401        }
402        ClientMsg::KeepPlugin { plugin, new_id, .. } => {
403            id(plugin)?;
404            new_id.as_deref().map_or(Ok(()), id)
405        }
406        ClientMsg::RemovePlugin { plugin, .. } => id(plugin),
407        ClientMsg::TrustPlugins { workspace, plugins, .. } => {
408            if workspace.is_empty() || workspace.len() > crate::workspace::MAX_ID_CHARS {
409                return Err("bad id".into());
410            }
411            if plugins.len() > MAX_TRUSTED_AT_ONCE {
412                return Err("too many plugins".into());
413            }
414            plugins.iter().try_for_each(|p| id(p))
415        }
416        _ => Ok(()),
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423    use crate::{ClientMsg, ServerMsg};
424
425    fn info() -> PluginInfo {
426        PluginInfo {
427            id: "weather".into(),
428            name: "Weather".into(),
429            version: "0.1.0".into(),
430            description: String::new(),
431            icon: "puzzle".into(),
432            scope: PluginScope::Chat,
433            origin: PluginOrigin::Agent,
434            dir: "/d/chats/c1/plugins/weather".into(),
435            enabled: true,
436            enabled_from: Level::Default,
437            trusted: true,
438            declined: false,
439            shadowed_by: None,
440            tools: vec!["weather".into()],
441            skills: vec![],
442            agents: vec![],
443            commands: vec![],
444            servers: vec![ServerInfo { name: "s".into(), state: ServerState::Connecting, tools: 0, error: None }],
445            backend: None,
446            views: vec![],
447            settings: vec![PluginSetting { key: "API_KEY".into(), label: "API key".into(), help: None, secret: true, required: true, set: false }],
448            network: true,
449            problems: vec!["tools/x.py is missing".into()],
450            last_error: Some("boom".into()),
451            fingerprint: "00ff".into(),
452            locked: false,
453            renderers: vec![],
454            starters: vec![],
455            superseded_by: None,
456            fluid: None,
457            logo: false,
458        }
459    }
460
461    #[test]
462    fn plugin_messages_round_trip_and_are_checked() {
463        let ext = Extensions {
464            chat: Some("c1".into()),
465            workspace: Some("w1".into()),
466            plugins: vec![info()],
467            errors: vec![PluginLoadError { scope: PluginScope::Global, path: "/p".into(), message: "bad".into() }],
468            slash: vec![SlashItem {
469                name: "review".into(),
470                kind: SlashKind::Command,
471                description: "Review a file".into(),
472                hint: "<file>".into(),
473                scope: Some(PluginScope::Workspace),
474                plugin: Some("code".into()),
475            }],
476        };
477        let m = ServerMsg::Extensions(Box::new(ext));
478        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
479        let ok = vec![
480            ClientMsg::GetExtensions,
481            ClientMsg::ReloadPlugins,
482            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "weather".into(), enabled: Some(false) },
483            ClientMsg::SetPluginEnabled { scope: ConfigScope::Workspace { id: "w1".into() }, plugin: "weather".into(), enabled: None },
484            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "API_KEY".into(), value: Some("sk".into()) },
485            ClientMsg::KeepPlugin { plugin: "scratch".into(), scope: PluginScope::Workspace, new_id: Some("weather".into()) },
486            ClientMsg::RemovePlugin { plugin: "weather".into(), scope: PluginScope::Chat },
487            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec![], trust: true },
488        ];
489        for m in ok {
490            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
491            assert!(m.check_sizes().is_ok(), "{}", m.to_json());
492        }
493        for bad in [
494            ClientMsg::SetPluginEnabled { scope: ConfigScope::Chat, plugin: "../x".into(), enabled: Some(true) },
495            ClientMsg::SetPluginSetting { plugin: "weather".into(), key: "K".into(), value: Some("x".repeat(MAX_SETTING_VALUE_CHARS + 1)) },
496            ClientMsg::KeepPlugin { plugin: "a".into(), scope: PluginScope::Global, new_id: Some("Bad".into()) },
497            ClientMsg::TrustPlugins { workspace: "w1".into(), plugins: vec!["ok".into(); MAX_TRUSTED_AT_ONCE + 1], trust: true },
498        ] {
499            assert!(bad.check_sizes().is_err(), "{}", bad.to_json());
500        }
501        let card = PluginCard {
502            plugin: "scratch".into(),
503            scope: PluginScope::Chat,
504            action: PluginAction::Made,
505            tools: vec!["weather".into()],
506            added: vec!["weather".into()],
507            removed: vec![],
508            test: Some(PluginTest { ok: false, output: "Traceback…".into() }),
509            problems: vec![],
510            missing_settings: vec!["API key".into()],
511        };
512        let json = serde_json::to_string(&card).unwrap();
513        assert_eq!(serde_json::from_str::<PluginCard>(&json).unwrap(), card);
514    }
515}