1use serde::{Deserialize, Serialize};
22
23use crate::workspace::{ConfigScope, Level};
24
25pub const MAX_SETTING_VALUE_CHARS: usize = 8192;
27pub const MAX_TRUSTED_AT_ONCE: usize = 200;
29
30#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum PluginOrigin {
53 Bundled,
55 User,
57 Agent,
59 Repo,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum ServerState {
68 Connecting,
70 Ready,
71 Failed,
72 Off,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct ServerInfo {
79 pub name: String,
80 pub state: ServerState,
81 #[serde(default)]
83 pub tools: u32,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub error: Option<String>,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct PluginSetting {
92 pub key: String,
94 pub label: String,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub help: Option<String>,
97 pub secret: bool,
99 pub required: bool,
100 pub set: bool,
102}
103
104#[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 #[serde(default)]
114 pub icon: String,
115 pub scope: PluginScope,
116 pub origin: PluginOrigin,
117 pub dir: String,
119 pub enabled: bool,
121 pub enabled_from: Level,
123 pub trusted: bool,
127 #[serde(default)]
129 pub declined: bool,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub shadowed_by: Option<PluginScope>,
133 #[serde(default)]
135 pub tools: Vec<String>,
136 #[serde(default)]
137 pub skills: Vec<String>,
138 #[serde(default)]
140 pub agents: Vec<String>,
141 #[serde(default)]
143 pub commands: Vec<String>,
144 #[serde(default)]
145 pub servers: Vec<ServerInfo>,
146 #[serde(default)]
147 pub settings: Vec<PluginSetting>,
148 #[serde(default)]
150 pub network: bool,
151 #[serde(default)]
154 pub problems: Vec<String>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub last_error: Option<String>,
158 #[serde(default)]
160 pub fingerprint: String,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165pub struct PluginLoadError {
166 pub scope: PluginScope,
167 pub path: String,
169 pub message: String,
170}
171
172#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174pub struct Extensions {
175 pub chat: Option<String>,
177 pub workspace: Option<String>,
179 pub plugins: Vec<PluginInfo>,
181 #[serde(default)]
182 pub errors: Vec<PluginLoadError>,
183 #[serde(default)]
186 pub slash: Vec<SlashItem>,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum SlashKind {
193 Builtin,
195 Command,
198 Skill,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct SlashItem {
205 pub name: String,
207 pub kind: SlashKind,
208 #[serde(default)]
209 pub description: String,
210 #[serde(default, skip_serializing_if = "String::is_empty")]
212 pub hint: String,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub scope: Option<PluginScope>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub plugin: Option<String>,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
223#[serde(rename_all = "snake_case")]
224pub enum PluginAction {
225 Made,
227 Edited,
229 Kept,
231 Removed,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct PluginTest {
238 pub ok: bool,
239 pub output: String,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245pub struct PluginCard {
246 pub plugin: String,
247 pub scope: PluginScope,
248 pub action: PluginAction,
249 #[serde(default)]
251 pub tools: Vec<String>,
252 #[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 #[serde(default)]
261 pub problems: Vec<String>,
262 #[serde(default)]
264 pub missing_settings: Vec<String>,
265}
266
267pub(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}