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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum PluginOrigin {
58 Bundled,
60 User,
62 Agent,
64 Repo,
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum ServerState {
73 Connecting,
75 Ready,
76 Failed,
77 Off,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct ServerInfo {
84 pub name: String,
85 pub state: ServerState,
86 #[serde(default)]
88 pub tools: u32,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub error: Option<String>,
91}
92
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
95pub struct BackendInfo {
96 pub state: String,
100 #[serde(default)]
102 pub starts: u32,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub error: Option<String>,
106 #[serde(default, skip_serializing_if = "Vec::is_empty")]
108 pub faults: Vec<String>,
109 #[serde(default, skip_serializing_if = "String::is_empty")]
111 pub stderr: String,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct PluginSetting {
118 pub key: String,
120 pub label: String,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub help: Option<String>,
123 pub secret: bool,
125 pub required: bool,
126 pub set: bool,
128}
129
130#[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 #[serde(default)]
140 pub icon: String,
141 pub scope: PluginScope,
142 pub origin: PluginOrigin,
143 pub dir: String,
145 pub enabled: bool,
147 pub enabled_from: Level,
149 pub trusted: bool,
153 #[serde(default)]
155 pub declined: bool,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub shadowed_by: Option<PluginScope>,
159 #[serde(default)]
161 pub tools: Vec<String>,
162 #[serde(default)]
163 pub skills: Vec<String>,
164 #[serde(default)]
166 pub agents: Vec<String>,
167 #[serde(default)]
169 pub commands: Vec<String>,
170 #[serde(default)]
171 pub servers: Vec<ServerInfo>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub backend: Option<BackendInfo>,
175 #[serde(default, skip_serializing_if = "Vec::is_empty")]
178 pub views: Vec<crate::ViewDecl>,
179 #[serde(default)]
180 pub settings: Vec<PluginSetting>,
181 #[serde(default)]
183 pub network: bool,
184 #[serde(default)]
187 pub problems: Vec<String>,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub last_error: Option<String>,
191 #[serde(default)]
193 pub fingerprint: String,
194 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
196 pub locked: bool,
197 #[serde(default, skip_serializing_if = "Vec::is_empty")]
199 pub renderers: Vec<RendererDecl>,
200 #[serde(default, skip_serializing_if = "Vec::is_empty")]
202 pub starters: Vec<StarterDecl>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub superseded_by: Option<String>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub fluid: Option<serde_json::Value>,
211 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
214 pub logo: bool,
215}
216
217impl PluginInfo {
218 pub fn in_use(&self) -> bool {
221 self.shadowed_by.is_none() && self.superseded_by.is_none()
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229pub struct RendererDecl {
230 pub content_type: String,
231 pub renderer: String,
232}
233
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct StarterDecl {
238 pub title: String,
239 pub prompt: String,
240}
241
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub struct PluginLoadError {
245 pub scope: PluginScope,
246 pub path: String,
248 pub message: String,
249}
250
251#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
253pub struct Extensions {
254 pub chat: Option<String>,
256 pub workspace: Option<String>,
258 pub plugins: Vec<PluginInfo>,
260 #[serde(default)]
261 pub errors: Vec<PluginLoadError>,
262 #[serde(default)]
265 pub slash: Vec<SlashItem>,
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub enum SlashKind {
272 Builtin,
274 Command,
277 Skill,
279 #[serde(other)]
281 Other,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct SlashItem {
287 pub name: String,
289 pub kind: SlashKind,
290 #[serde(default)]
291 pub description: String,
292 #[serde(default, skip_serializing_if = "String::is_empty")]
294 pub hint: String,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub scope: Option<PluginScope>,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub plugin: Option<String>,
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
305#[serde(rename_all = "snake_case")]
306pub enum PluginAction {
307 Made,
309 Edited,
311 Kept,
313 Removed,
315 #[serde(other)]
317 Other,
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322pub struct PluginTest {
323 pub ok: bool,
324 pub output: String,
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub struct PluginCard {
331 pub plugin: String,
332 pub scope: PluginScope,
333 pub action: PluginAction,
334 #[serde(default)]
336 pub tools: Vec<String>,
337 #[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 #[serde(default)]
346 pub problems: Vec<String>,
347 #[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
378pub(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}