1use std::collections::BTreeMap;
9use std::path::{Component, Path};
10
11use serde::Serialize;
12use serde_json::{Map, Value};
13
14pub const MANIFEST: &str = "byob-plugin.json";
16pub const OLD_MANIFEST: &str = "hob-plugin.json";
19
20const PROMPT_MAX: usize = 600;
22const PROMPT_MAX_BUILTIN: usize = 1500;
23
24#[derive(Debug, Clone, PartialEq, Serialize)]
26pub struct Manifest {
27 pub id: String,
29 pub name: String,
30 pub version: String,
32 pub description: String,
33 pub author: Option<String>,
34 pub icon: String,
36 pub permissions: Permissions,
37 pub starters: Vec<Starter>,
38 pub tools: Vec<ManifestTool>,
39 pub mcp_servers: BTreeMap<String, McpServerConfig>,
40 pub settings: Vec<Setting>,
41 pub prompt: Option<String>,
43 pub platforms: Option<Vec<String>>,
45 pub backend: Option<BackendDecl>,
48 pub requirements: Vec<String>,
50 pub views: Vec<ManifestView>,
52 pub fluid: Option<Value>,
55 pub locked: bool,
57 pub on_by_default: bool,
59 pub provides: Option<String>,
62 pub artifact_types: Vec<ManifestArtifactType>,
64 pub renderers: Vec<ManifestRenderer>,
66 pub system_prompt: Option<PromptSource>,
69 pub hooks: Vec<ManifestHook>,
71 pub environments: Vec<ManifestEnv>,
73}
74
75pub const HOOK_EVENTS: [&str; 5] = ["before_prompt", "before_request", "before_tool_call", "after_tool_call", "on_turn_end"];
77pub const MAX_HOOKS: usize = 16;
79pub const HOOK_TIMEOUT_MS: u64 = 2000;
81pub const MAX_HOOK_TIMEOUT_MS: u64 = 60_000;
82pub const DEFAULT_HOOK_PRIORITY: i64 = 100;
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
89pub struct ManifestHook {
90 pub event: String,
92 pub priority: i64,
94 pub native: Option<String>,
96 pub timeout_ms: u64,
98 pub fail_closed: bool,
101 pub tools: Vec<String>,
103}
104
105pub const MAX_ENVIRONMENTS: usize = 8;
107
108#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
114pub struct ManifestEnv {
115 pub id: String,
117 pub native: Option<String>,
118 pub label: String,
120 pub detect: Vec<String>,
122 pub inputs: Vec<String>,
124 pub command: Option<String>,
127 pub args: Vec<String>,
128}
129
130pub const MAX_TYPES: usize = 16;
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
137pub struct ManifestArtifactType {
138 pub content_type: String,
140 pub native: Option<String>,
142 pub suffixes: Option<Vec<String>>,
143 pub label: Option<String>,
144 pub describe: Option<String>,
145 pub pick: Option<String>,
146 pub guidance: Option<String>,
148 pub binary: bool,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
156pub struct ManifestRenderer {
157 pub content_type: String,
158 pub renderer: String,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
163pub enum PromptSource {
164 File(String),
166 Native(String),
168}
169
170pub const VIEW_SITES: [&str; 5] = ["pane", "settings", "status", "card", "artifact"];
172pub const MAX_VIEWS: usize = 16;
174
175#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
178pub struct ManifestView {
179 pub id: String,
181 pub site: String,
183 pub title: String,
185 pub icon: String,
186 pub html: String,
189}
190
191pub const MAX_REQUIREMENTS: usize = 64;
193pub const BACKEND_EVENTS: [&str; 5] = ["chat_opened", "turn_started", "turn_finished", "step_done", "artifact_updated"];
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
198pub struct BackendDecl {
199 pub run: BackendRun,
200 pub args: Vec<String>,
202 pub events: Vec<String>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
207pub enum BackendRun {
208 Python(String),
210 Command(String),
212 Native(String),
215}
216
217#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
218pub struct Permissions {
219 pub network: bool,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
224pub struct Starter {
225 pub title: String,
226 pub prompt: String,
227 pub file: bool,
229}
230
231#[derive(Debug, Clone, PartialEq, Serialize)]
233pub struct ManifestTool {
234 pub name: String,
236 pub description: String,
237 pub params: Value,
239 pub kind: ToolKind,
240 pub title: Option<String>,
242 pub optional: bool,
245 #[serde(skip)]
248 pub access: Option<byob_tools::Access>,
249 #[serde(skip)]
252 pub confirm: Option<Confirm>,
253}
254
255#[derive(Debug, Clone, PartialEq, Eq, Default)]
258pub struct Confirm {
259 pub warning: String,
261 pub when: Vec<String>,
264}
265
266impl Confirm {
267 pub fn applies(&self, args: &Value) -> Option<String> {
269 let given = |k: &String| match args.get(k) {
270 None | Some(Value::Null | Value::Bool(false)) => false,
271 Some(Value::String(s)) => !s.trim().is_empty(),
272 Some(Value::Array(a)) => !a.is_empty(),
273 Some(Value::Object(o)) => !o.is_empty(),
274 Some(_) => true,
275 };
276 (self.when.is_empty() || self.when.iter().any(given))
277 .then(|| if self.warning.is_empty() { "this call must be confirmed".to_owned() } else { self.warning.clone() })
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
282pub enum ToolKind {
283 Script(String),
285 Native(String),
288 Backend,
290}
291
292#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
294pub enum McpServerConfig {
295 Stdio { command: String, args: Vec<String>, env: BTreeMap<String, String> },
297 Url { url: String, sse: bool, headers: BTreeMap<String, String>, oauth: Option<OAuthClient> },
299}
300
301#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
302pub struct OAuthClient {
303 pub client_id: String,
304 pub client_secret: Option<String>,
305}
306
307impl McpServerConfig {
308 pub fn is_local(&self) -> bool {
310 matches!(self, Self::Stdio { .. })
311 }
312
313 pub fn with_settings(&self, values: &BTreeMap<String, String>) -> Self {
316 let fill = |s: &String| fill_placeholders(s, values);
317 let fill_map = |m: &BTreeMap<String, String>| m.iter().map(|(k, v)| (k.clone(), fill(v))).collect();
318 match self {
319 Self::Stdio { command, args, env } => Self::Stdio { command: fill(command), args: args.iter().map(fill).collect(), env: fill_map(env) },
320 Self::Url { url, sse, headers, oauth } => Self::Url { url: fill(url), sse: *sse, headers: fill_map(headers), oauth: oauth.clone() },
321 }
322 }
323}
324
325pub fn fill_placeholders(s: &str, values: &BTreeMap<String, String>) -> String {
327 let mut out = String::with_capacity(s.len());
328 let mut rest = s;
329 while let Some(start) = rest.find("${") {
330 out.push_str(&rest[..start]);
331 let after = &rest[start + 2..];
332 match after.find('}') {
333 Some(end) => {
334 let key = &after[..end];
335 match values.get(key) {
336 Some(v) => out.push_str(v),
337 None => {
338 out.push_str("${");
339 out.push_str(key);
340 out.push('}');
341 }
342 }
343 rest = &after[end + 1..];
344 }
345 None => {
346 out.push_str(&rest[start..]);
347 rest = "";
348 }
349 }
350 }
351 out.push_str(rest);
352 out
353}
354
355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
356pub enum SettingKind {
357 #[default]
358 Text,
359 Number,
360 Boolean,
361 Directory,
362 File,
363}
364
365impl SettingKind {
366 fn parse(s: &str) -> Option<Self> {
367 Some(match s {
368 "text" => Self::Text,
369 "number" => Self::Number,
370 "boolean" => Self::Boolean,
371 "directory" => Self::Directory,
372 "file" => Self::File,
373 _ => return None,
374 })
375 }
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
381pub struct Setting {
382 pub key: String,
384 pub label: String,
385 pub secret: bool,
386 pub help: Option<String>,
387 pub kind: SettingKind,
388 pub required: bool,
389 pub multiple: bool,
390 pub default: Option<String>,
392}
393
394#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
396#[error("{file}: {message}")]
397pub struct ManifestError {
398 pub file: String,
399 pub message: String,
400}
401
402#[derive(Debug, Clone, Copy, Default)]
404pub struct ParseOptions<'a> {
405 pub builtin: bool,
407 pub file: Option<&'a str>,
409}
410
411pub fn plugin_id_ok(id: &str) -> bool {
413 let b = id.as_bytes();
414 !b.is_empty() && b.len() <= 48 && is_lower_alnum(b[0]) && b.iter().all(|&c| is_lower_alnum(c) || c == b'-')
415}
416
417pub fn tool_name_ok(name: &str) -> bool {
419 let b = name.as_bytes();
420 !b.is_empty() && b.len() <= 64 && b[0].is_ascii_alphabetic() && b.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_')
421}
422
423pub fn setting_key_ok(key: &str) -> bool {
425 let b = key.as_bytes();
426 !b.is_empty() && b.len() <= 64 && b[0].is_ascii_uppercase() && b.iter().all(|&c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
427}
428
429fn is_lower_alnum(c: u8) -> bool {
430 c.is_ascii_lowercase() || c.is_ascii_digit()
431}
432
433pub fn path_inside(p: &str) -> bool {
435 let mut depth: usize = 0;
436 for c in Path::new(p).components() {
437 match c {
438 Component::Normal(_) => depth += 1,
439 Component::CurDir => {}
440 Component::ParentDir => match depth.checked_sub(1) {
441 Some(d) => depth = d,
442 None => return false,
443 },
444 Component::RootDir | Component::Prefix(_) => return false,
445 }
446 }
447 !(p.starts_with('\\') || p.as_bytes().get(1) == Some(&b':'))
449}
450
451pub fn parse_manifest(raw: &Value, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
453 let file = opts.file.unwrap_or(MANIFEST);
454 parse(raw, opts.builtin).map_err(|message| ManifestError { file: file.to_string(), message })
455}
456
457pub fn parse_manifest_str(text: &str, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
459 let file = opts.file.unwrap_or(MANIFEST);
460 let raw: Value = serde_json::from_str(text).map_err(|e| ManifestError { file: file.to_string(), message: format!("isn't valid JSON: {e}") })?;
461 parse_manifest(&raw, opts)
462}
463
464type R<T> = Result<T, String>;
465
466fn req_str(v: Option<&Value>, field: &str) -> R<String> {
468 match v {
469 Some(Value::String(s)) if !s.trim().is_empty() => Ok(s.trim().to_string()),
470 _ => Err(format!("{field} must be text")),
471 }
472}
473
474fn opt_str(v: Option<&Value>, field: &str) -> R<Option<String>> {
476 match v {
477 None => Ok(None),
478 Some(Value::String(s)) => Ok(Some(s.trim().to_string())),
479 Some(_) => Err(format!("{field} must be text")),
480 }
481}
482
483fn list<'a>(v: Option<&'a Value>, field: &str) -> R<&'a [Value]> {
484 match v {
485 None => Ok(&[]),
486 Some(Value::Array(a)) => Ok(a),
487 Some(_) => Err(format!("{field} must be a list")),
488 }
489}
490
491fn obj<'a>(v: &'a Value, field: &str) -> R<&'a Map<String, Value>> {
492 v.as_object().ok_or_else(|| format!("{field} must be an object"))
493}
494
495fn str_map(v: Option<&Value>, field: &str) -> R<BTreeMap<String, String>> {
496 let Some(v) = v else { return Ok(BTreeMap::new()) };
497 let bad = || format!("{field} must map names to text");
498 let m = v.as_object().ok_or_else(bad)?;
499 m.iter().map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(bad)).collect()
500}
501
502fn truthy(v: Option<&Value>) -> bool {
503 match v {
504 None | Some(Value::Null) => false,
505 Some(Value::Bool(b)) => *b,
506 Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
507 Some(Value::String(s)) => !s.is_empty(),
508 Some(_) => true,
509 }
510}
511
512fn truncate_chars(s: &str, max: usize) -> String {
513 s.chars().take(max).collect()
514}
515
516fn parse(raw: &Value, builtin: bool) -> R<Manifest> {
517 let r = raw.as_object().ok_or("must be a JSON object")?;
518 let id = req_str(r.get("id"), "id")?;
519 if !plugin_id_ok(&id) {
520 return Err("id must be lowercase letters, digits and dashes, like \"trip-planner\"".into());
521 }
522 let tools = list(r.get("tools"), "tools")?.iter().enumerate().map(|(i, t)| parse_tool(t, i)).collect::<R<Vec<_>>>()?;
523 let mcp_servers = parse_servers(r.get("mcpServers"))?;
524 let settings = list(r.get("settings"), "settings")?.iter().enumerate().map(|(i, s)| parse_setting(s, i)).collect::<R<Vec<_>>>()?;
525 let starters = list(r.get("starters"), "starters")?
526 .iter()
527 .enumerate()
528 .map(|(i, s)| {
529 let f = format!("starters[{i}]");
530 let s = obj(s, &f)?;
531 Ok(Starter {
532 title: req_str(s.get("title"), &format!("{f}.title"))?,
533 prompt: req_str(s.get("prompt"), &format!("{f}.prompt"))?,
534 file: s.get("file") == Some(&Value::Bool(true)),
535 })
536 })
537 .collect::<R<Vec<_>>>()?;
538 let network = r.get("permissions").and_then(Value::as_object).and_then(|p| p.get("network")) == Some(&Value::Bool(true));
539 let prompt = match r.get("prompt") {
540 None => None,
541 p => Some(truncate_chars(&req_str(p, "prompt")?, if builtin { PROMPT_MAX_BUILTIN } else { PROMPT_MAX })),
542 };
543 let platforms = r.get("platforms").and_then(Value::as_array).map(|a| a.iter().map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)).collect());
544 let author = match r.get("author") {
545 None => None,
546 a => Some(req_str(a, "author")?),
547 };
548 let backend = parse_backend(r.get("backend"))?;
549 if backend.is_none()
550 && let Some(i) = tools.iter().position(|t| t.kind == ToolKind::Backend)
551 {
552 return Err(format!("tools[{i}].run is \"backend\" but the plugin has no \"backend\""));
553 }
554 let requirements = parse_requirements(r.get("python"))?;
555 let hooks = parse_hooks(r.get("hooks"), backend.is_some())?;
556 let name = req_str(r.get("name"), "name")?;
557 let views = parse_views(r.get("views"), &name)?;
558 if backend.is_none() && views.iter().any(|v| v.html.is_empty()) {
559 return Err("views are drawn by the plugin's backend: add \"backend\": \"backend.py\" (or give the view an \"html\" file)".into());
560 }
561 let renderers = parse_renderers(r.get("renderers"))?;
562 for (i, d) in renderers.iter().enumerate() {
563 if let Some(v) = d.renderer.strip_prefix("view:")
564 && !views.iter().any(|x| x.id == v && x.site == "artifact")
565 {
566 return Err(format!("renderers[{i}].renderer: {:?} needs a view {{\"site\": \"artifact\", \"id\": \"{v}\"}} in \"views\"", d.renderer));
567 }
568 }
569 Ok(Manifest {
570 id,
571 name,
572 version: opt_str(r.get("version"), "version")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "0.0.0".into()),
573 description: opt_str(r.get("description"), "description")?.unwrap_or_default(),
574 author,
575 icon: opt_str(r.get("icon"), "icon")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "puzzle".into()),
576 permissions: Permissions { network },
577 starters,
578 tools,
579 mcp_servers,
580 settings,
581 prompt,
582 platforms,
583 backend,
584 requirements,
585 views,
586 fluid: match r.get("fluid") {
587 None | Some(Value::Null) => None,
588 Some(v @ Value::Object(_)) if v.to_string().len() <= 64 * 1024 => Some(v.clone()),
589 Some(Value::Object(_)) => return Err("fluid: at most 64 KB".into()),
590 Some(_) => return Err("fluid: an object of fluid changes, like {\"insert\": [...]}".into()),
591 },
592 locked: r.get("locked") == Some(&Value::Bool(true)),
593 on_by_default: r.get("enabled") != Some(&Value::Bool(false)),
594 provides: match opt_str(r.get("provides"), "provides")?.map(|p| p.trim().to_owned()).filter(|p| !p.is_empty()) {
595 Some(p) if !plugin_id_ok(&p) => return Err("provides must be lowercase letters, digits and dashes, like \"spreadsheets\"".into()),
596 p => p,
597 },
598 artifact_types: parse_artifact_types(r.get("artifact_types").or_else(|| r.get("content_types")))?,
599 renderers,
600 system_prompt: parse_prompt_source(r.get("system_prompt"))?,
601 hooks,
602 environments: parse_environments(r.get("environments"))?,
603 })
604}
605
606fn parse_hooks(v: Option<&Value>, has_backend: bool) -> R<Vec<ManifestHook>> {
608 let items = list(v, "hooks")?;
609 if items.len() > MAX_HOOKS {
610 return Err(format!("hooks: at most {MAX_HOOKS}"));
611 }
612 let mut out = Vec::new();
613 for (i, item) in items.iter().enumerate() {
614 let f = format!("hooks[{i}]");
615 let o = obj(item, &f)?;
616 let event = req_str(o.get("event"), &format!("{f}.event"))?;
617 if !HOOK_EVENTS.contains(&event.as_str()) {
618 return Err(format!("{f}.event must be one of {}", HOOK_EVENTS.join(", ")));
619 }
620 let priority = match o.get("priority") {
621 None | Some(Value::Null) => DEFAULT_HOOK_PRIORITY,
622 Some(p) => p.as_i64().filter(|p| p.abs() <= 1_000_000).ok_or_else(|| format!("{f}.priority must be a whole number"))?,
623 };
624 let native = opt_str(o.get("native"), &format!("{f}.native"))?;
625 if let Some(n) = &native
626 && !native_id_ok(n)
627 {
628 return Err(format!("{f}.native must be an id like \"compaction\""));
629 }
630 if native.is_none() && !has_backend {
631 return Err(format!("{f} is answered by the plugin's backend: add \"backend\": \"backend.py\" (or name in-tree code with \"native\")"));
632 }
633 let timeout_ms = match o.get("timeout_ms") {
634 None | Some(Value::Null) => HOOK_TIMEOUT_MS,
635 Some(t) => {
636 t.as_u64().filter(|t| (1..=MAX_HOOK_TIMEOUT_MS).contains(t)).ok_or_else(|| format!("{f}.timeout_ms must be 1 to {MAX_HOOK_TIMEOUT_MS}"))?
637 }
638 };
639 let fail_closed = match opt_str(o.get("fail"), &format!("{f}.fail"))?.as_deref() {
640 None | Some("open") => false,
641 Some("closed") => true,
642 Some(_) => return Err(format!("{f}.fail must be \"open\" or \"closed\"")),
643 };
644 let tools = list(o.get("tools"), &format!("{f}.tools"))?
645 .iter()
646 .enumerate()
647 .map(|(j, t)| t.as_str().map(str::trim).filter(|t| tool_name_ok(t)).map(str::to_owned).ok_or_else(|| format!("{f}.tools[{j}] must be a tool name")))
648 .collect::<R<Vec<_>>>()?;
649 if !tools.is_empty() && !matches!(event.as_str(), "before_tool_call" | "after_tool_call") {
650 return Err(format!("{f}.tools only applies to before_tool_call and after_tool_call"));
651 }
652 out.push(ManifestHook { event, priority, native, timeout_ms, fail_closed, tools });
653 }
654 Ok(out)
655}
656
657fn parse_environments(v: Option<&Value>) -> R<Vec<ManifestEnv>> {
659 let items = list(v, "environments")?;
660 if items.len() > MAX_ENVIRONMENTS {
661 return Err(format!("environments: at most {MAX_ENVIRONMENTS}"));
662 }
663 let mut out: Vec<ManifestEnv> = Vec::new();
664 for (i, item) in items.iter().enumerate() {
665 let f = format!("environments[{i}]");
666 let o = obj(item, &f)?;
667 let native = opt_str(o.get("native"), &format!("{f}.native"))?;
668 let id = match (&native, o.get("id")) {
669 (Some(n), None) => n.clone(),
670 (_, v) => req_str(v, &format!("{f}.id"))?,
671 };
672 let id_ok = (1..=32).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'));
673 if !id_ok || native.as_deref().is_some_and(|n| !native_id_ok(n)) {
674 return Err(format!("{f}.id must be lowercase letters, digits, _ or -, like \"conda\""));
675 }
676 if out.iter().any(|e| e.id == id) {
677 return Err(format!("{f}.id {id:?} is used twice"));
678 }
679 let files = |key: &str| -> R<Vec<String>> {
680 list(o.get(key), &format!("{f}.{key}"))?
681 .iter()
682 .enumerate()
683 .map(|(j, p)| match p.as_str().map(str::trim) {
684 Some(p) if !p.is_empty() && path_inside(p) => Ok(p.to_owned()),
685 _ => Err(format!("{f}.{key}[{j}] must be a file name inside the workspace, like \"environment.yml\"")),
686 })
687 .collect()
688 };
689 let detect = files("detect")?;
690 let inputs = files("inputs")?;
691 let command = opt_str(o.get("command"), &format!("{f}.command"))?.filter(|c| !c.is_empty());
692 let args = list(o.get("args"), &format!("{f}.args"))?
693 .iter()
694 .enumerate()
695 .map(|(j, a)| a.as_str().map(str::to_owned).ok_or_else(|| format!("{f}.args[{j}] must be text")))
696 .collect::<R<Vec<_>>>()?;
697 if native.is_none() && (detect.is_empty() || command.is_none()) {
698 return Err(format!("{f} needs \"native\" (built into byob) or \"detect\" (the workspace files) and \"command\" (prints the environment as JSON)"));
699 }
700 let label =
701 truncate_chars(&opt_str(o.get("label"), &format!("{f}.label"))?.filter(|l| !l.is_empty()).unwrap_or_else(|| format!("{id} environment")), 60);
702 out.push(ManifestEnv { id, native, label, detect, inputs, command, args });
703 }
704 Ok(out)
705}
706
707fn content_type_ok(t: &str) -> bool {
709 let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'+' | b'_' | b'-'));
710 t.len() <= 128 && t.split_once('/').is_some_and(|(a, b)| ok(a) && (ok(b) || b == "*"))
711}
712
713fn native_id_ok(id: &str) -> bool {
714 (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.'))
715}
716
717fn parse_artifact_types(v: Option<&Value>) -> R<Vec<ManifestArtifactType>> {
718 let items = list(v, "artifact_types")?;
719 if items.len() > MAX_TYPES {
720 return Err(format!("artifact_types: at most {MAX_TYPES}"));
721 }
722 let mut out: Vec<ManifestArtifactType> = Vec::new();
723 for (i, item) in items.iter().enumerate() {
724 let f = format!("artifact_types[{i}]");
725 let o = obj(item, &f)?;
726 let content_type = req_str(o.get("type"), &format!("{f}.type"))?.to_ascii_lowercase();
727 if !content_type_ok(&content_type) || content_type.ends_with("/*") {
728 return Err(format!("{f}.type must be a content type like \"text/csv\""));
729 }
730 if out.iter().any(|t| t.content_type == content_type) {
731 return Err(format!("{f}.type {content_type:?} is declared twice"));
732 }
733 let native = opt_str(o.get("native"), &format!("{f}.native"))?;
734 if let Some(n) = &native
735 && !native_id_ok(n)
736 {
737 return Err(format!("{f}.native must be an id like \"html_app\""));
738 }
739 let suffixes = match o.get("suffixes") {
740 None => None,
741 v => Some(
742 list(v, &format!("{f}.suffixes"))?
743 .iter()
744 .enumerate()
745 .map(|(j, s)| match s.as_str().map(str::trim) {
746 Some(s) if s.starts_with('.') && s.len() > 1 && s.len() <= 32 && !s.contains(['/', '\\']) => Ok(s.to_ascii_lowercase()),
747 _ => Err(format!("{f}.suffixes[{j}] must be a file name ending like \".csv\"")),
748 })
749 .collect::<R<Vec<_>>>()?,
750 ),
751 };
752 if native.is_none() && suffixes.as_ref().is_none_or(Vec::is_empty) {
753 return Err(format!("{f} needs \"native\" (a type built into byob) or \"suffixes\" (the file names it covers)"));
754 }
755 let guidance = opt_str(o.get("guidance"), &format!("{f}.guidance"))?;
756 if let Some(g) = &guidance
757 && (g.is_empty() || !path_inside(g))
758 {
759 return Err(format!("{f}.guidance must be a file inside the plugin folder, like \"guidance.md\""));
760 }
761 let short = |key: &str| -> R<Option<String>> { Ok(opt_str(o.get(key), &format!("{f}.{key}"))?.map(|s| truncate_chars(&s, 400))) };
762 let binary = match o.get("binary") {
763 None | Some(Value::Null) => false,
764 Some(Value::Bool(b)) => *b,
765 Some(_) => return Err(format!("{f}.binary must be true or false")),
766 };
767 out.push(ManifestArtifactType {
768 content_type,
769 native,
770 suffixes,
771 label: short("label")?,
772 describe: short("describe")?,
773 pick: short("pick")?,
774 guidance,
775 binary,
776 });
777 }
778 Ok(out)
779}
780
781fn parse_renderers(v: Option<&Value>) -> R<Vec<ManifestRenderer>> {
782 let items = list(v, "renderers")?;
783 if items.len() > MAX_TYPES {
784 return Err(format!("renderers: at most {MAX_TYPES}"));
785 }
786 items
787 .iter()
788 .enumerate()
789 .map(|(i, item)| {
790 let f = format!("renderers[{i}]");
791 let o = obj(item, &f)?;
792 let content_type = req_str(o.get("type"), &format!("{f}.type"))?.to_ascii_lowercase();
793 if !content_type_ok(&content_type) {
794 return Err(format!("{f}.type must be a content type like \"text/csv\" (or \"image/*\")"));
795 }
796 let renderer = req_str(o.get("renderer"), &format!("{f}.renderer"))?;
797 let web_file = renderer.strip_prefix("web:").map(str::trim);
798 let ok = matches!(renderer.as_str(), "web" | "text")
799 || renderer.strip_prefix("native:").is_some_and(native_id_ok)
800 || renderer.strip_prefix("view:").is_some_and(byob_view_id_ok)
801 || web_file.is_some_and(|p| !p.is_empty() && path_inside(p));
802 if !ok {
803 return Err(format!("{f}.renderer must be \"web\", \"web:<html file in the plugin>\", \"text\", \"native:<id>\" or \"view:<view id>\""));
804 }
805 Ok(ManifestRenderer { content_type, renderer })
806 })
807 .collect()
808}
809
810fn parse_prompt_source(v: Option<&Value>) -> R<Option<PromptSource>> {
811 let f = "system_prompt";
812 match v {
813 None | Some(Value::Null) => Ok(None),
814 Some(Value::String(s)) => {
815 let s = s.trim();
816 if s.is_empty() || !path_inside(s) {
817 return Err(format!("{f} must be a file inside the plugin folder, like \"prompt.md\""));
818 }
819 Ok(Some(PromptSource::File(s.to_owned())))
820 }
821 Some(v) => {
822 let o = obj(v, f)?;
823 let n = req_str(o.get("native"), &format!("{f}.native"))?;
824 if !native_id_ok(&n) {
825 return Err(format!("{f}.native must be an id like \"artifacts\""));
826 }
827 Ok(Some(PromptSource::Native(n)))
828 }
829 }
830}
831
832fn byob_view_id_ok(id: &str) -> bool {
834 (1..=48).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
835}
836
837fn parse_views(v: Option<&Value>, plugin_name: &str) -> R<Vec<ManifestView>> {
839 let items = list(v, "views")?;
840 if items.len() > MAX_VIEWS {
841 return Err(format!("views: at most {MAX_VIEWS}"));
842 }
843 let mut out: Vec<ManifestView> = Vec::new();
844 for (i, item) in items.iter().enumerate() {
845 let f = format!("views[{i}]");
846 let o = obj(item, &f)?;
847 let site = req_str(o.get("site"), &format!("{f}.site"))?;
848 if !VIEW_SITES.contains(&site.as_str()) {
849 return Err(format!("{f}.site must be one of {}", VIEW_SITES.join(", ")));
850 }
851 let id = match o.get("id") {
852 None => site.clone(),
853 v => req_str(v, &format!("{f}.id"))?,
854 };
855 if !byob_view_id_ok(&id) {
856 return Err(format!("{f}.id must be lowercase letters, digits, _ or -, like \"todo\""));
857 }
858 if out.iter().any(|x| x.id == id) {
859 return Err(format!("{f}.id {id:?} is used twice"));
860 }
861 let title = truncate_chars(&opt_str(o.get("title"), &format!("{f}.title"))?.filter(|t| !t.is_empty()).unwrap_or_else(|| plugin_name.to_owned()), 80);
862 let icon = opt_str(o.get("icon"), &format!("{f}.icon"))?.unwrap_or_default();
863 let html = opt_str(o.get("html"), &format!("{f}.html"))?.map(|h| h.trim().to_owned()).unwrap_or_default();
864 if !html.is_empty() && !path_inside(&html) {
865 return Err(format!("{f}.html must be a file inside the plugin folder, like \"ui/index.html\""));
866 }
867 if !html.is_empty() && !matches!(site.as_str(), "pane" | "card") {
868 return Err(format!("{f}: a web view (\"html\") goes in the pane or on a card"));
869 }
870 out.push(ManifestView { id, site, title, icon, html });
871 }
872 Ok(out)
873}
874
875fn parse_backend(v: Option<&Value>) -> R<Option<BackendDecl>> {
878 let f = "backend";
879 let script = |p: String| -> R<BackendRun> {
880 if !path_inside(&p) || p.is_empty() {
881 return Err(format!("{f}.run must be a path inside the plugin folder, like \"backend.py\""));
882 }
883 Ok(BackendRun::Python(p))
884 };
885 let o = match v {
886 None | Some(Value::Null) => return Ok(None),
887 Some(Value::String(s)) => return Ok(Some(BackendDecl { run: script(s.trim().to_string())?, args: Vec::new(), events: Vec::new() })),
888 Some(v) => obj(v, f)?,
889 };
890 let run = match (o.get("run"), o.get("command"), o.get("native")) {
891 (Some(r), None, None) => script(req_str(Some(r), &format!("{f}.run"))?)?,
892 (None, Some(c), None) => BackendRun::Command(req_str(Some(c), &format!("{f}.command"))?),
893 (None, None, Some(n)) => BackendRun::Native(req_str(Some(n), &format!("{f}.native"))?),
894 _ => return Err(format!("{f} needs \"run\" (a Python script), \"command\" (a program) or \"native\" (a backend built into byob), one of them")),
895 };
896 let strings = |key: &str| -> R<Vec<String>> {
897 list(o.get(key), &format!("{f}.{key}"))?
898 .iter()
899 .enumerate()
900 .map(|(i, a)| a.as_str().map(str::to_string).ok_or_else(|| format!("{f}.{key}[{i}] must be text")))
901 .collect()
902 };
903 let args = strings("args")?;
904 let events = strings("events")?;
905 if let Some(e) = events.iter().find(|e| !BACKEND_EVENTS.contains(&e.as_str())) {
906 return Err(format!("{f}.events: {e:?} isn't an engine event; use {}", BACKEND_EVENTS.join(", ")));
907 }
908 Ok(Some(BackendDecl { run, args, events }))
909}
910
911fn parse_requirements(v: Option<&Value>) -> R<Vec<String>> {
913 let Some(v) = v else { return Ok(Vec::new()) };
914 let o = obj(v, "python")?;
915 let reqs = list(o.get("requirements"), "python.requirements")?;
916 if reqs.len() > MAX_REQUIREMENTS {
917 return Err(format!("python.requirements: at most {MAX_REQUIREMENTS} packages"));
918 }
919 reqs.iter()
920 .enumerate()
921 .map(|(i, r)| {
922 let r = req_str(Some(r), &format!("python.requirements[{i}]"))?;
923 if r.starts_with('-') || r.contains(['\n', '\r']) || r.len() > 512 {
925 return Err(format!("python.requirements[{i}] must be one package spec like \"requests>=2.31\""));
926 }
927 Ok(r)
928 })
929 .collect()
930}
931
932fn parse_tool(t: &Value, i: usize) -> R<ManifestTool> {
933 let f = format!("tools[{i}]");
934 let t = obj(t, &f)?;
935 let native = match t.get("native") {
936 None => None,
937 n => Some(req_str(n, &format!("{f}.native"))?),
938 };
939 let name = match (&native, t.get("name")) {
941 (Some(n), None) => n.clone(),
942 (_, v) => req_str(v, &format!("{f}.name"))?,
943 };
944 if !tool_name_ok(&name) {
945 return Err(format!("{f}.name must be letters, digits or _, starting with a letter"));
946 }
947 let params = match t.get("params") {
948 None => serde_json::json!({ "type": "object", "properties": {} }),
949 Some(p @ Value::Object(_)) => p.clone(),
950 Some(_) => return Err(format!("{f}.params must be a JSON schema object")),
951 };
952 let run = match t.get("run") {
953 None => None,
954 Some(Value::String(s)) if s.trim() == "backend" => Some(String::new()),
955 v => {
956 let p = req_str(v, &format!("{f}.run"))?;
957 if !path_inside(&p) {
958 return Err(format!("{f}.run must be a path inside the plugin folder"));
959 }
960 Some(p)
961 }
962 };
963 let kind = match (run, native) {
964 (Some(r), _) if r.is_empty() => ToolKind::Backend,
965 (Some(r), _) => ToolKind::Script(r),
966 (None, Some(n)) => ToolKind::Native(n),
967 (None, None) => return Err(format!("{f}.run must name the Python script that runs this tool")),
968 };
969 let description = match (&kind, t.get("description")) {
970 (ToolKind::Native(_), None) => String::new(),
971 (_, d) => req_str(d, &format!("{f}.description"))?,
972 };
973 let title = match t.get("title") {
974 None => None,
975 v => Some(req_str(v, &format!("{f}.title"))?),
976 };
977 let optional = t.get("optional") == Some(&Value::Bool(true));
978 let access = match t.get("access") {
979 None | Some(Value::Null) => None,
980 a => Some(match req_str(a, &format!("{f}.access"))?.as_str() {
981 "read" => byob_tools::Access::Read,
982 "write" => byob_tools::Access::Write,
983 "network" => byob_tools::Access::Network,
984 "execute" => byob_tools::Access::Execute,
985 _ => return Err(format!("{f}.access must be one of read, write, network, execute")),
986 }),
987 };
988 let confirm = match t.get("confirm") {
989 None | Some(Value::Null | Value::Bool(false)) => None,
990 Some(Value::Bool(true)) => Some(Confirm::default()),
991 Some(Value::String(w)) => Some(Confirm { warning: w.trim().chars().take(300).collect(), when: Vec::new() }),
992 Some(Value::Object(c)) => {
993 let warning = match c.get("warning") {
994 None => String::new(),
995 w => req_str(w, &format!("{f}.confirm.warning"))?.chars().take(300).collect(),
996 };
997 let when = match c.get("when") {
998 None => Vec::new(),
999 Some(Value::Array(a)) => a
1000 .iter()
1001 .map(|v| v.as_str().map(str::to_owned))
1002 .collect::<Option<Vec<_>>>()
1003 .ok_or_else(|| format!("{f}.confirm.when must list argument names"))?,
1004 Some(_) => return Err(format!("{f}.confirm.when must list argument names")),
1005 };
1006 Some(Confirm { warning, when })
1007 }
1008 Some(_) => return Err(format!("{f}.confirm must be true, a warning, or {{\"warning\", \"when\"}}")),
1009 };
1010 if confirm.is_some() && matches!(kind, ToolKind::Native(_)) {
1011 return Err(format!("{f}.confirm is for script and backend tools (native tools bring their own)"));
1012 }
1013 Ok(ManifestTool { name, description, params, kind, title, optional, access, confirm })
1014}
1015
1016fn parse_servers(v: Option<&Value>) -> R<BTreeMap<String, McpServerConfig>> {
1017 let Some(v) = v else { return Ok(BTreeMap::new()) };
1018 let m = v.as_object().ok_or("mcpServers must be an object of servers")?;
1019 m.iter().map(|(k, v)| Ok((k.clone(), parse_server(v, &format!("mcpServers.{k}"))?))).collect()
1020}
1021
1022pub(crate) fn parse_server(v: &Value, f: &str) -> R<McpServerConfig> {
1024 let v = obj(v, f)?;
1025 let ty = v.get("type").and_then(Value::as_str);
1026 if v.get("url").is_some() || matches!(ty, Some("http" | "sse" | "streamable-http")) {
1027 let url = req_str(v.get("url"), &format!("{f}.url"))?;
1028 let lower = url.to_ascii_lowercase();
1029 let rest = lower.strip_prefix("https://").or_else(|| lower.strip_prefix("http://"));
1030 if !rest.is_some_and(|r| !r.is_empty() && !r.starts_with('/')) {
1031 return Err(format!("{f}.url must start with https://"));
1032 }
1033 let headers = str_map(v.get("headers"), &format!("{f}.headers"))?;
1034 let oauth = match v.get("oauth") {
1035 None => None,
1036 Some(o) => {
1037 let o = obj(o, &format!("{f}.oauth"))?;
1038 Some(OAuthClient {
1039 client_id: req_str(o.get("clientId"), &format!("{f}.oauth.clientId"))?,
1040 client_secret: match o.get("clientSecret") {
1041 None => None,
1042 s => Some(req_str(s, &format!("{f}.oauth.clientSecret"))?),
1043 },
1044 })
1045 }
1046 };
1047 return Ok(McpServerConfig::Url { url, sse: ty == Some("sse"), headers, oauth });
1048 }
1049 let args = list(v.get("args"), &format!("{f}.args"))?
1050 .iter()
1051 .enumerate()
1052 .map(|(i, a)| a.as_str().map(|s| s.trim().to_string()).ok_or_else(|| format!("{f}.args[{i}] must be text")))
1053 .collect::<R<Vec<_>>>()?;
1054 let env = str_map(v.get("env"), &format!("{f}.env"))?;
1055 Ok(McpServerConfig::Stdio { command: req_str(v.get("command"), &format!("{f}.command"))?, args, env })
1056}
1057
1058fn parse_setting(s: &Value, i: usize) -> R<Setting> {
1059 let f = format!("settings[{i}]");
1060 let s = obj(s, &f)?;
1061 let key = req_str(s.get("key"), &format!("{f}.key"))?;
1062 if !setting_key_ok(&key) {
1063 return Err(format!("{f}.key must be UPPER_CASE, like \"API_KEY\""));
1064 }
1065 let kind = match s.get("type") {
1066 None => SettingKind::Text,
1067 t => {
1068 let t = req_str(t, &format!("{f}.type"))?;
1069 SettingKind::parse(&t).ok_or_else(|| format!("{f}.type must be one of text, number, boolean, directory, file"))?
1070 }
1071 };
1072 let help = match s.get("help") {
1073 None => None,
1074 h => Some(req_str(h, &format!("{f}.help"))?),
1075 };
1076 let default = s.get("default").map(|d| match d {
1077 Value::Array(a) => a.iter().map(value_text).collect::<Vec<_>>().join("\n"),
1078 other => value_text(other),
1079 });
1080 Ok(Setting {
1081 key,
1082 label: req_str(s.get("label"), &format!("{f}.label"))?,
1083 secret: truthy(s.get("secret")),
1084 help,
1085 kind,
1086 required: truthy(s.get("required")),
1087 multiple: truthy(s.get("multiple")),
1088 default,
1089 })
1090}
1091
1092fn value_text(v: &Value) -> String {
1094 match v {
1095 Value::String(s) => s.clone(),
1096 Value::Null => "null".into(),
1097 other => other.to_string(),
1098 }
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104 use serde_json::json;
1105
1106 fn parse_user(v: Value) -> Result<Manifest, String> {
1107 parse_manifest(&v, ParseOptions::default()).map_err(|e| e.to_string())
1108 }
1109
1110 #[test]
1111 fn minimal_manifest_gets_defaults() {
1112 let m = parse_user(json!({"id": "recipe-helper", "name": "Recipe Helper", "extra": {"future": true}})).unwrap();
1113 assert_eq!(m.version, "0.0.0");
1114 assert_eq!(m.icon, "puzzle");
1115 assert!(!m.permissions.network);
1116 assert!(m.tools.is_empty() && m.mcp_servers.is_empty() && m.settings.is_empty());
1117 }
1118
1119 #[test]
1120 fn author_facing_errors() {
1121 let cases = [
1122 (json!([]), "byob-plugin.json: must be a JSON object"),
1123 (json!({"name": "x"}), "byob-plugin.json: id must be text"),
1124 (json!({"id": "Bad_Id", "name": "x"}), "byob-plugin.json: id must be lowercase letters, digits and dashes, like \"trip-planner\""),
1125 (json!({"id": "a", "name": "x", "tools": {}}), "byob-plugin.json: tools must be a list"),
1126 (
1127 json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "../escape.py"}]}),
1128 "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
1129 ),
1130 (
1131 json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "/abs.py"}]}),
1132 "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
1133 ),
1134 (
1135 json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d"}]}),
1136 "byob-plugin.json: tools[0].run must name the Python script that runs this tool",
1137 ),
1138 (
1139 json!({"id": "a", "name": "x", "tools": [{"name": "1t", "description": "d", "run": "t.py"}]}),
1140 "byob-plugin.json: tools[0].name must be letters, digits or _, starting with a letter",
1141 ),
1142 (
1143 json!({"id": "a", "name": "x", "artifact_types": [{"type": "csv"}]}),
1144 "byob-plugin.json: artifact_types[0].type must be a content type like \"text/csv\"",
1145 ),
1146 (
1147 json!({"id": "a", "name": "x", "artifact_types": [{"type": "text/csv"}]}),
1148 "byob-plugin.json: artifact_types[0] needs \"native\" (a type built into byob) or \"suffixes\" (the file names it covers)",
1149 ),
1150 (
1151 json!({"id": "a", "name": "x", "renderers": [{"type": "text/csv", "renderer": "wasm"}]}),
1152 "byob-plugin.json: renderers[0].renderer must be \"web\", \"web:<html file in the plugin>\", \"text\", \"native:<id>\" or \"view:<view id>\"",
1153 ),
1154 (
1155 json!({"id": "a", "name": "x", "system_prompt": "../p.md"}),
1156 "byob-plugin.json: system_prompt must be a file inside the plugin folder, like \"prompt.md\"",
1157 ),
1158 (
1159 json!({"id": "a", "name": "x", "settings": [{"key": "api_key", "label": "k"}]}),
1160 "byob-plugin.json: settings[0].key must be UPPER_CASE, like \"API_KEY\"",
1161 ),
1162 (
1163 json!({"id": "a", "name": "x", "settings": [{"key": "K", "label": "k", "type": "color"}]}),
1164 "byob-plugin.json: settings[0].type must be one of text, number, boolean, directory, file",
1165 ),
1166 (json!({"id": "a", "name": "x", "mcpServers": {"s": {"url": "ftp://x"}}}), "byob-plugin.json: mcpServers.s.url must start with https://"),
1167 (
1168 json!({"id": "a", "name": "x", "mcpServers": {"s": {"command": "x", "env": {"A": 1}}}}),
1169 "byob-plugin.json: mcpServers.s.env must map names to text",
1170 ),
1171 (json!({"id": "a", "name": "x", "mcpServers": {"s": {}}}), "byob-plugin.json: mcpServers.s.command must be text"),
1172 ];
1173 for (raw, want) in cases {
1174 assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1175 }
1176 }
1177
1178 #[test]
1179 fn python_tool_and_settings() {
1180 let m = parse_user(json!({
1181 "id": "text-stats", "name": "Text stats", "permissions": {"network": true},
1182 "tools": [{"name": "count_words", "description": "Count words.", "params": {"type": "object", "properties": {"file": {"type": "string"}}}, "run": "tools/count.py", "title": "Counted {file}"}],
1183 "settings": [{"key": "API_KEY", "label": "API key", "secret": true, "type": "directory", "multiple": true, "default": ["/a", "/b"]}],
1184 "starters": [{"title": "Go", "prompt": "/go", "file": true}],
1185 "prompt": "x".repeat(700),
1186 }))
1187 .unwrap();
1188 assert!(m.permissions.network);
1189 assert_eq!(m.tools[0].kind, ToolKind::Script("tools/count.py".into()));
1190 assert_eq!(m.tools[0].title.as_deref(), Some("Counted {file}"));
1191 assert_eq!(m.tools[0].access, None);
1192 let s = &m.settings[0];
1193 assert!(s.secret && s.multiple && !s.required);
1194 assert_eq!(s.kind, SettingKind::Directory);
1195 assert_eq!(s.default.as_deref(), Some("/a\n/b"));
1196 assert!(m.starters[0].file);
1197 assert_eq!(m.prompt.map(|p| p.chars().count()), Some(600));
1198 }
1199
1200 #[test]
1201 fn backends_and_requirements() {
1202 let m = parse_user(json!({"id": "a", "name": "x", "backend": "backend.py", "tools": [{"name": "t", "description": "d", "run": "backend"}],
1203 "python": {"requirements": ["requests>=2", "./wheels/w.whl"]}}))
1204 .unwrap();
1205 assert_eq!(m.backend.unwrap().run, BackendRun::Python("backend.py".into()));
1206 assert_eq!(m.tools[0].kind, ToolKind::Backend);
1207 assert_eq!(m.requirements, ["requests>=2", "./wheels/w.whl"]);
1208 let m =
1209 parse_user(json!({"id": "a", "name": "x", "backend": "b.py", "tools": [{"name": "t", "description": "d", "run": "backend", "access": "read"}]}))
1210 .unwrap();
1211 assert_eq!(m.tools[0].access, Some(byob_tools::Access::Read));
1212 let bad =
1213 parse_user(json!({"id": "a", "name": "x", "backend": "b.py", "tools": [{"name": "t", "description": "d", "run": "backend", "access": "root"}]}));
1214 assert_eq!(bad.unwrap_err(), "byob-plugin.json: tools[0].access must be one of read, write, network, execute");
1215 let tool = |confirm: Value| json!({"id": "a", "name": "x", "backend": "b.py", "tools": [{"name": "t", "description": "d", "run": "backend", "confirm": confirm}]});
1217 let always = parse_user(tool(json!(true))).unwrap().tools[0].confirm.clone().unwrap();
1218 assert_eq!(always.applies(&json!({})).as_deref(), Some("this call must be confirmed"));
1219 let when = parse_user(tool(json!({"warning": "emails people", "when": ["to", "cc"]}))).unwrap().tools[0].confirm.clone().unwrap();
1220 assert_eq!(when.applies(&json!({"to": [], "cc": " ", "x": 1})), None);
1221 assert_eq!(when.applies(&json!({"cc": ["b@x"]})).as_deref(), Some("emails people"));
1222 assert_eq!(parse_user(tool(json!(false))).unwrap().tools[0].confirm, None);
1223 assert!(parse_user(tool(json!({"when": "to"}))).unwrap_err().contains("confirm.when must list argument names"));
1224 assert_eq!(parse_user(tool(json!(" sends email "))).unwrap().tools[0].confirm.clone().unwrap().applies(&json!({})).as_deref(), Some("sends email"));
1225 assert!(parse_user(tool(json!(3))).unwrap_err().contains("confirm must be true, a warning"));
1226 let m = parse_user(json!({"id": "a", "name": "x", "backend": {"command": "node", "args": ["s.js"], "events": ["turn_finished"]}})).unwrap();
1227 let b = m.backend.unwrap();
1228 assert_eq!((b.run, b.args, b.events), (BackendRun::Command("node".into()), vec!["s.js".to_string()], vec!["turn_finished".to_string()]));
1229 let cases = [
1230 (
1231 json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "backend"}]}),
1232 "byob-plugin.json: tools[0].run is \"backend\" but the plugin has no \"backend\"",
1233 ),
1234 (
1235 json!({"id": "a", "name": "x", "backend": "../b.py"}),
1236 "byob-plugin.json: backend.run must be a path inside the plugin folder, like \"backend.py\"",
1237 ),
1238 (
1239 json!({"id": "a", "name": "x", "backend": {"run": "b.py", "command": "node"}}),
1240 "byob-plugin.json: backend needs \"run\" (a Python script), \"command\" (a program) or \"native\" (a backend built into byob), one of them",
1241 ),
1242 (
1243 json!({"id": "a", "name": "x", "provides": "Spread Sheets"}),
1244 "byob-plugin.json: provides must be lowercase letters, digits and dashes, like \"spreadsheets\"",
1245 ),
1246 (
1247 json!({"id": "a", "name": "x", "backend": {"run": "b.py", "events": ["tick"]}}),
1248 "byob-plugin.json: backend.events: \"tick\" isn't an engine event; use chat_opened, turn_started, turn_finished, step_done, artifact_updated",
1249 ),
1250 (
1251 json!({"id": "a", "name": "x", "python": {"requirements": ["--index-url=http://x"]}}),
1252 "byob-plugin.json: python.requirements[0] must be one package spec like \"requests>=2.31\"",
1253 ),
1254 ];
1255 for (raw, want) in cases {
1256 assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1257 }
1258 }
1259
1260 #[test]
1261 fn native_backends_default_switches_and_provides() {
1262 let m = parse_user(json!({"id": "a", "name": "x", "backend": {"native": "sheets"}, "enabled": false, "provides": "spreadsheets"})).unwrap();
1263 assert_eq!(m.backend.unwrap().run, BackendRun::Native("sheets".into()));
1264 assert!(!m.on_by_default);
1265 assert_eq!(m.provides.as_deref(), Some("spreadsheets"));
1266 let m = parse_user(json!({"id": "a", "name": "x"})).unwrap();
1267 assert!(m.on_by_default && m.provides.is_none());
1268 }
1269
1270 #[test]
1271 fn views_at_render_sites() {
1272 let m = parse_user(json!({"id": "a", "name": "Todo", "backend": "b.py",
1273 "views": [{"site": "pane", "id": "list", "title": "To do", "icon": "list"}, {"site": "status"}]}))
1274 .unwrap();
1275 assert_eq!(m.views[0], ManifestView { id: "list".into(), site: "pane".into(), title: "To do".into(), icon: "list".into(), html: String::new() });
1276 assert_eq!((m.views[1].id.as_str(), m.views[1].title.as_str()), ("status", "Todo"), "id defaults to the site, title to the name");
1277 let cases = [
1278 (
1279 json!({"id": "a", "name": "x", "views": [{"site": "pane"}]}),
1280 "byob-plugin.json: views are drawn by the plugin's backend: add \"backend\": \"backend.py\" (or give the view an \"html\" file)",
1281 ),
1282 (
1283 json!({"id": "a", "name": "x", "views": [{"site": "status", "html": "ui/x.html"}]}),
1284 "byob-plugin.json: views[0]: a web view (\"html\") goes in the pane or on a card",
1285 ),
1286 (
1287 json!({"id": "a", "name": "x", "views": [{"site": "pane", "html": "../x.html"}]}),
1288 "byob-plugin.json: views[0].html must be a file inside the plugin folder, like \"ui/index.html\"",
1289 ),
1290 (
1291 json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "sidebar"}]}),
1292 "byob-plugin.json: views[0].site must be one of pane, settings, status, card, artifact",
1293 ),
1294 (
1295 json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "pane", "id": "My View"}]}),
1296 "byob-plugin.json: views[0].id must be lowercase letters, digits, _ or -, like \"todo\"",
1297 ),
1298 (
1299 json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "pane"}, {"site": "pane"}]}),
1300 "byob-plugin.json: views[1].id \"pane\" is used twice",
1301 ),
1302 ];
1303 for (raw, want) in cases {
1304 assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1305 }
1306 let m = parse_user(json!({"id": "a", "name": "x", "views": [{"site": "pane", "id": "p", "html": "ui/index.html"}],
1308 "renderers": [{"type": "text/csv", "renderer": "web:ui/csv.html"}]}))
1309 .unwrap();
1310 assert_eq!((m.views[0].html.as_str(), m.renderers[0].renderer.as_str()), ("ui/index.html", "web:ui/csv.html"));
1311 assert!(parse_user(json!({"id": "a", "name": "x", "renderers": [{"type": "text/csv", "renderer": "web:/etc/x.html"}]})).is_err());
1312 }
1313
1314 #[test]
1315 fn native_bindings() {
1316 let raw = json!({"id": "code", "name": "Code", "locked": true,
1319 "tools": [{"native": "run_python"}, {"native": "install_packages", "optional": true}],
1320 "artifact_types": [{"type": "text/html", "native": "html_app", "guidance": "guidance.md"},
1321 {"type": "Text/CSV", "suffixes": [".CSV"], "label": "table", "pick": "a table → .csv"}],
1322 "renderers": [{"type": "text/html", "renderer": "web"}, {"type": "image/*", "renderer": "native:image"}],
1323 "system_prompt": {"native": "artifacts"}});
1324 let m = parse_user(raw).unwrap();
1325 assert_eq!(m.tools[0].name, "run_python");
1326 assert_eq!(m.tools[0].kind, ToolKind::Native("run_python".into()));
1327 assert!(!m.tools[0].optional && m.tools[1].optional && m.locked);
1328 assert_eq!(m.artifact_types[0].native.as_deref(), Some("html_app"));
1329 assert_eq!(m.artifact_types[0].guidance.as_deref(), Some("guidance.md"));
1330 assert_eq!((m.artifact_types[1].content_type.as_str(), m.artifact_types[1].suffixes.clone()), ("text/csv", Some(vec![".csv".to_string()])));
1331 assert_eq!(m.renderers[1], ManifestRenderer { content_type: "image/*".into(), renderer: "native:image".into() });
1332 assert_eq!(m.system_prompt, Some(PromptSource::Native("artifacts".into())));
1333 let m = parse_user(json!({"id": "a", "name": "x", "content_types": [{"type": "text/x", "native": "text"}], "system_prompt": "prompt.md"})).unwrap();
1334 assert_eq!(m.artifact_types[0].native.as_deref(), Some("text"));
1335 assert_eq!(m.system_prompt, Some(PromptSource::File("prompt.md".into())));
1336 }
1337
1338 #[test]
1339 fn server_configs() {
1340 let m = parse_user(json!({"id": "a", "name": "x", "mcpServers": {
1341 "mem": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"], "env": {"K": "${API_KEY}"}},
1342 "lin": {"url": "https://mcp.linear.app/mcp", "headers": {"Authorization": "Bearer ${API_KEY}"}, "oauth": {"clientId": "c"}},
1343 "old": {"url": "https://example.com/sse", "type": "sse"},
1344 }}))
1345 .unwrap();
1346 assert!(m.mcp_servers["mem"].is_local());
1347 assert!(!m.mcp_servers["lin"].is_local());
1348 assert!(matches!(&m.mcp_servers["old"], McpServerConfig::Url { sse: true, .. }));
1349 let vals = BTreeMap::from([("API_KEY".to_string(), "abc".to_string())]);
1350 match m.mcp_servers["lin"].with_settings(&vals) {
1351 McpServerConfig::Url { headers, oauth, .. } => {
1352 assert_eq!(headers["Authorization"], "Bearer abc");
1353 assert_eq!(oauth.map(|o| o.client_id).as_deref(), Some("c"));
1354 }
1355 other => panic!("{other:?}"),
1356 }
1357 }
1358
1359 #[test]
1360 fn placeholders() {
1361 let vals = BTreeMap::from([("A".to_string(), "1".to_string())]);
1362 assert_eq!(fill_placeholders("${A}-${B}-${A", &vals), "1-${B}-${A");
1363 assert_eq!(fill_placeholders("ünï${A}cødé", &vals), "ünï1cødé");
1364 }
1365
1366 #[test]
1367 fn inside_paths() {
1368 assert!(path_inside("tools/x.py") && path_inside("./a/../b.py"));
1369 assert!(!path_inside("../x") && !path_inside("a/../../x") && !path_inside("/x") && !path_inside("C:\\x") && !path_inside("\\x"));
1370 }
1371
1372 #[test]
1373 fn hooks_and_environments() {
1374 let parse = |extra: serde_json::Value| {
1375 let mut m = serde_json::json!({"id": "p", "name": "P"});
1376 for (k, v) in extra.as_object().unwrap() {
1377 m[k] = v.clone();
1378 }
1379 parse_manifest(&m, ParseOptions::default())
1380 };
1381 let m = parse(serde_json::json!({"backend": "b.py", "hooks": [
1382 {"event": "before_tool_call", "priority": -5, "tools": ["delete_file"], "fail": "closed", "timeout_ms": 500},
1383 {"event": "before_request", "native": "compaction"}
1384 ]}))
1385 .unwrap();
1386 assert_eq!(
1387 m.hooks[0],
1388 ManifestHook {
1389 event: "before_tool_call".into(),
1390 priority: -5,
1391 native: None,
1392 timeout_ms: 500,
1393 fail_closed: true,
1394 tools: vec!["delete_file".into()]
1395 }
1396 );
1397 assert_eq!((m.hooks[1].priority, m.hooks[1].timeout_ms, m.hooks[1].fail_closed), (DEFAULT_HOOK_PRIORITY, HOOK_TIMEOUT_MS, false));
1398 let err = |v| parse(v).unwrap_err().message;
1399 assert!(err(serde_json::json!({"hooks": [{"event": "before_lunch", "native": "x"}]})).contains("event must be one of"));
1400 assert!(err(serde_json::json!({"hooks": [{"event": "on_turn_end"}]})).contains("add \"backend\""));
1401 assert!(err(serde_json::json!({"hooks": [{"event": "before_prompt", "native": "x", "tools": ["a"]}]})).contains("tools only applies"));
1402 assert!(err(serde_json::json!({"backend": "b.py", "hooks": [{"event": "on_turn_end", "timeout_ms": 0}]})).contains("timeout_ms"));
1403 assert!(err(serde_json::json!({"backend": "b.py", "hooks": [{"event": "on_turn_end", "fail": "maybe"}]})).contains("\"open\" or \"closed\""));
1404 let m = parse(serde_json::json!({"environments": [
1405 {"native": "nix"},
1406 {"id": "conda", "detect": ["environment.yml"], "command": "python3", "args": ["env.py"]}
1407 ]}))
1408 .unwrap();
1409 assert_eq!((m.environments[0].id.as_str(), m.environments[0].native.as_deref()), ("nix", Some("nix")));
1410 assert_eq!((m.environments[1].label.as_str(), m.environments[1].command.as_deref()), ("conda environment", Some("python3")));
1411 assert!(err(serde_json::json!({"environments": [{"id": "x", "detect": ["a"]}]})).contains("needs \"native\""));
1412 assert!(err(serde_json::json!({"environments": [{"id": "x", "detect": ["../a"], "command": "c"}]})).contains("inside the workspace"));
1413 }
1414}