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}
209
210impl PluginInfo {
211 pub fn in_use(&self) -> bool {
214 self.shadowed_by.is_none() && self.superseded_by.is_none()
215 }
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222pub struct RendererDecl {
223 pub content_type: String,
224 pub renderer: String,
225}
226
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct StarterDecl {
231 pub title: String,
232 pub prompt: String,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct PluginLoadError {
238 pub scope: PluginScope,
239 pub path: String,
241 pub message: String,
242}
243
244#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
246pub struct Extensions {
247 pub chat: Option<String>,
249 pub workspace: Option<String>,
251 pub plugins: Vec<PluginInfo>,
253 #[serde(default)]
254 pub errors: Vec<PluginLoadError>,
255 #[serde(default)]
258 pub slash: Vec<SlashItem>,
259}
260
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "snake_case")]
264pub enum SlashKind {
265 Builtin,
267 Command,
270 Skill,
272 #[serde(other)]
274 Other,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct SlashItem {
280 pub name: String,
282 pub kind: SlashKind,
283 #[serde(default)]
284 pub description: String,
285 #[serde(default, skip_serializing_if = "String::is_empty")]
287 pub hint: String,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub scope: Option<PluginScope>,
291 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub plugin: Option<String>,
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "snake_case")]
299pub enum PluginAction {
300 Made,
302 Edited,
304 Kept,
306 Removed,
308 #[serde(other)]
310 Other,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct PluginTest {
316 pub ok: bool,
317 pub output: String,
319}
320
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323pub struct PluginCard {
324 pub plugin: String,
325 pub scope: PluginScope,
326 pub action: PluginAction,
327 #[serde(default)]
329 pub tools: Vec<String>,
330 #[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 #[serde(default)]
339 pub problems: Vec<String>,
340 #[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
371pub(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}