Skip to main content

byob_plugins/
manifest.rs

1//! `byob-plugin.json`: the plugin manifest.
2//!
3//! Parsing mirrors hob's `parseManifest`: the same required fields, defaults and limits,
4//! and error messages written for the plugin's author (e.g.
5//! `byob-plugin.json: tools[0].run must be a path inside the plugin folder`). Unknown fields
6//! are ignored so newer manifests still load.
7
8use std::collections::BTreeMap;
9use std::path::{Component, Path};
10
11use serde::Serialize;
12use serde_json::{Map, Value};
13
14/// The manifest file name.
15pub const MANIFEST: &str = "byob-plugin.json";
16/// The manifest's old name (from hob, which byob started as a rewrite of). Not read: a
17/// folder with only this file gets a warning to rename it.
18pub const OLD_MANIFEST: &str = "hob-plugin.json";
19
20/// Prompt length caps (characters), as in hob: built-in plugins carry longer how-tos.
21const PROMPT_MAX: usize = 600;
22const PROMPT_MAX_BUILTIN: usize = 1500;
23
24/// A checked plugin manifest with defaults filled in.
25#[derive(Debug, Clone, PartialEq, Serialize)]
26pub struct Manifest {
27    /// `[a-z0-9][a-z0-9-]{0,47}`.
28    pub id: String,
29    pub name: String,
30    /// `0.0.0` when left out.
31    pub version: String,
32    pub description: String,
33    pub author: Option<String>,
34    /// A lucide icon name; `puzzle` when left out.
35    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    /// A line added to the system prompt while the plugin is on.
42    pub prompt: Option<String>,
43    /// Node `process.platform` names (`darwin`, `linux`, `win32`); everywhere when `None`.
44    pub platforms: Option<Vec<String>>,
45    /// A long-lived process the engine talks to in JSON lines (`backend`), see
46    /// `docs/plugins-backend.md`.
47    pub backend: Option<BackendDecl>,
48    /// Python packages its scripts and backend need (`python.requirements`, pip specs).
49    pub requirements: Vec<String>,
50    /// Live views its backend draws at render sites (`views`).
51    pub views: Vec<ManifestView>,
52    /// Can't be switched off (`locked`; honoured for bundled plugins and their forks).
53    pub locked: bool,
54    /// On until someone switches it (`"enabled": false` ships it switched off).
55    pub on_by_default: bool,
56    /// What it offers that another plugin may offer too (`provides`, e.g. `"spreadsheets"`):
57    /// of the switched-on plugins providing the same thing only one is used.
58    pub provides: Option<String>,
59    /// Artifact content types it adds (`artifact_types`, also `content_types`).
60    pub artifact_types: Vec<ManifestArtifactType>,
61    /// Which renderer draws a content type on clients (`renderers`).
62    pub renderers: Vec<ManifestRenderer>,
63    /// A section of the system prompt (`system_prompt`): a file of the plugin, or text an
64    /// in-tree builder makes.
65    pub system_prompt: Option<PromptSource>,
66    /// Places in the turn pipeline it sits in (`hooks`), see [`ManifestHook`].
67    pub hooks: Vec<ManifestHook>,
68    /// Workspace environment providers it adds (`environments`), see [`ManifestEnv`].
69    pub environments: Vec<ManifestEnv>,
70}
71
72/// The turn pipeline's hook points, in the order a turn reaches them.
73pub const HOOK_EVENTS: [&str; 5] = ["before_prompt", "before_request", "before_tool_call", "after_tool_call", "on_turn_end"];
74/// Most hooks one plugin declares.
75pub const MAX_HOOKS: usize = 16;
76/// A backend hook's default and longest timeout (milliseconds).
77pub const HOOK_TIMEOUT_MS: u64 = 2000;
78pub const MAX_HOOK_TIMEOUT_MS: u64 = 60_000;
79/// Hooks run by priority, lowest first; this when left out.
80pub const DEFAULT_HOOK_PRIORITY: i64 = 100;
81
82/// A place in the turn pipeline (`hooks[]`): `{"event": "before_tool_call", "priority": 50,
83/// "backend": true, "timeout_ms": 2000, "fail": "closed", "tools": ["delete_file"]}`, or
84/// `{"event": "before_request", "native": "compaction"}` (in-tree code by id).
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86pub struct ManifestHook {
87    /// One of [`HOOK_EVENTS`].
88    pub event: String,
89    /// Lower runs first ([`DEFAULT_HOOK_PRIORITY`] when left out).
90    pub priority: i64,
91    /// In-tree code by id (`None`: the plugin's backend answers a `hook` request).
92    pub native: Option<String>,
93    /// How long a backend may take (ms).
94    pub timeout_ms: u64,
95    /// `"fail": "closed"`: a backend that faults or times out stops the stage (a tool call is
96    /// denied, a request isn't made); the default (open) carries on as if it said continue.
97    pub fail_closed: bool,
98    /// `before_tool_call` / `after_tool_call` only for these tools (empty: every tool).
99    pub tools: Vec<String>,
100}
101
102/// Most environment providers one plugin declares.
103pub const MAX_ENVIRONMENTS: usize = 8;
104
105/// A workspace environment provider (`environments[]`): in-tree (`{"native": "nix"}`), or a
106/// command that prints the environment as JSON when the workspace has one of `detect`:
107/// `{"id": "conda", "label": "conda environment", "detect": ["environment.yml"], "inputs":
108/// ["environment.yml"], "command": "python3", "args": ["conda_env.py"]}`. Loading it is asked
109/// once per workspace, like the built-in ones.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
111pub struct ManifestEnv {
112    /// `[a-z0-9_-]{1,32}` (the native id when native).
113    pub id: String,
114    pub native: Option<String>,
115    /// For messages: "conda environment".
116    pub label: String,
117    /// Files that make a workspace use it (the first one found is named).
118    pub detect: Vec<String>,
119    /// Files whose contents key its cache (`detect` too).
120    pub inputs: Vec<String>,
121    /// The program (on `PATH`, or a file of the plugin) and its arguments (a file of the
122    /// plugin is passed as its full path). It runs in the workspace, sandboxed, with network.
123    pub command: Option<String>,
124    pub args: Vec<String>,
125}
126
127/// Most artifact types or renderers one plugin declares.
128pub const MAX_TYPES: usize = 16;
129
130/// An artifact type a plugin adds: `{"type": "text/html", "native": "html_app", "guidance":
131/// "guidance.md"}`, or a declarative text type `{"type": "text/csv", "suffixes": [".csv"],
132/// "label": "table", "describe": ".csv (a table)", "pick": "a table → .csv"}`.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
134pub struct ManifestArtifactType {
135    /// The content type, e.g. `text/html`.
136    pub content_type: String,
137    /// An in-tree type (hooks, defaults) by id; the fields below override its defaults.
138    pub native: Option<String>,
139    pub suffixes: Option<Vec<String>>,
140    pub label: Option<String>,
141    pub describe: Option<String>,
142    pub pick: Option<String>,
143    /// A file of the plugin with the type's system-prompt guidance.
144    pub guidance: Option<String>,
145    /// `"binary": true`: its versions aren't text (`create_artifact` / `update_artifact` /
146    /// `read_artifact` don't take them; the plugin's own tools write them).
147    pub binary: bool,
148}
149
150/// `{"type": "text/html", "renderer": "web" | "text" | "native:<id>" | "view:<view id>"}`
151/// (`view:` names one of the plugin's views with `"site": "artifact"`).
152#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
153pub struct ManifestRenderer {
154    pub content_type: String,
155    pub renderer: String,
156}
157
158/// Where a plugin's system-prompt section comes from.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
160pub enum PromptSource {
161    /// A file of the plugin (`"system_prompt": "prompt.md"`).
162    File(String),
163    /// An in-tree builder by id (`"system_prompt": {"native": "artifacts"}`).
164    Native(String),
165}
166
167/// Render sites a view may declare.
168pub const VIEW_SITES: [&str; 5] = ["pane", "settings", "status", "card", "artifact"];
169/// Most views one plugin declares.
170pub const MAX_VIEWS: usize = 16;
171
172/// A view the plugin's backend draws (`views[]`): `{"site": "pane", "id": "todo",
173/// "title": "To do", "icon": "list"}`.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
175pub struct ManifestView {
176    /// `[a-z0-9_-]{1,48}`, unique in the plugin.
177    pub id: String,
178    /// One of [`VIEW_SITES`].
179    pub site: String,
180    /// The plugin's name when left out.
181    pub title: String,
182    pub icon: String,
183    /// A web view: its HTML file in the plugin folder (`"html": "ui/index.html"`), shown on
184    /// a web surface instead of a tree the backend draws. Empty for tree views.
185    pub html: String,
186}
187
188/// Most `python.requirements` entries.
189pub const MAX_REQUIREMENTS: usize = 64;
190/// Engine events a backend may subscribe to (`backend.events`, or `subscribe` at run time).
191pub const BACKEND_EVENTS: [&str; 5] = ["chat_opened", "turn_started", "turn_finished", "step_done", "artifact_updated"];
192
193/// How to start a plugin's backend.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
195pub struct BackendDecl {
196    pub run: BackendRun,
197    /// Extra arguments after the script (or the command).
198    pub args: Vec<String>,
199    /// Engine events it gets from the start (`subscribe` adds more at run time).
200    pub events: Vec<String>,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
204pub enum BackendRun {
205    /// A Python script in the plugin folder, run with the plugin's interpreter.
206    Python(String),
207    /// Any program (on `PATH`, or relative to the plugin folder), run in the plugin folder.
208    Command(String),
209    /// In-tree Rust registered by id (`{"native": "sheets"}`), run in byob's own process on
210    /// a thread of its own ([`crate::native`]).
211    Native(String),
212}
213
214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
215pub struct Permissions {
216    /// Python tools (and skills' scripts) may use the internet.
217    pub network: bool,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
221pub struct Starter {
222    pub title: String,
223    pub prompt: String,
224    /// The starter asks the user for a file first.
225    pub file: bool,
226}
227
228/// A tool a plugin declares.
229#[derive(Debug, Clone, PartialEq, Serialize)]
230pub struct ManifestTool {
231    /// `[A-Za-z][A-Za-z0-9_]{0,63}`.
232    pub name: String,
233    pub description: String,
234    /// JSON Schema object for the arguments.
235    pub params: Value,
236    pub kind: ToolKind,
237    /// Step title with `{arg}` placeholders.
238    pub title: Option<String>,
239    /// A native tool this build may not have (e.g. `install_packages` without a package
240    /// manager): missing isn't a problem.
241    pub optional: bool,
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
245pub enum ToolKind {
246    /// A Python script, relative to the plugin folder.
247    Script(String),
248    /// One of the app's own (in-tree) tools, by name. A name this build doesn't have is a
249    /// problem of the plugin.
250    Native(String),
251    /// Served by the plugin's long-lived backend (`"run": "backend"`).
252    Backend,
253}
254
255/// How to reach one MCP server.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
257pub enum McpServerConfig {
258    /// A program on this computer, spoken to over stdio.
259    Stdio { command: String, args: Vec<String>, env: BTreeMap<String, String> },
260    /// A server at a URL (Streamable HTTP, or legacy HTTP+SSE).
261    Url { url: String, sse: bool, headers: BTreeMap<String, String>, oauth: Option<OAuthClient> },
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
265pub struct OAuthClient {
266    pub client_id: String,
267    pub client_secret: Option<String>,
268}
269
270impl McpServerConfig {
271    /// Stdio servers run unsandboxed local code; URL servers only talk to the network.
272    pub fn is_local(&self) -> bool {
273        matches!(self, Self::Stdio { .. })
274    }
275
276    /// Fill `${KEY}` placeholders in args, env values, the URL and headers from the
277    /// plugin's settings. Unknown keys are left as they are.
278    pub fn with_settings(&self, values: &BTreeMap<String, String>) -> Self {
279        let fill = |s: &String| fill_placeholders(s, values);
280        let fill_map = |m: &BTreeMap<String, String>| m.iter().map(|(k, v)| (k.clone(), fill(v))).collect();
281        match self {
282            Self::Stdio { command, args, env } => Self::Stdio { command: fill(command), args: args.iter().map(fill).collect(), env: fill_map(env) },
283            Self::Url { url, sse, headers, oauth } => Self::Url { url: fill(url), sse: *sse, headers: fill_map(headers), oauth: oauth.clone() },
284        }
285    }
286}
287
288/// `"Bearer ${API_KEY}"` + `{API_KEY: "abc"}` → `"Bearer abc"`.
289pub fn fill_placeholders(s: &str, values: &BTreeMap<String, String>) -> String {
290    let mut out = String::with_capacity(s.len());
291    let mut rest = s;
292    while let Some(start) = rest.find("${") {
293        out.push_str(&rest[..start]);
294        let after = &rest[start + 2..];
295        match after.find('}') {
296            Some(end) => {
297                let key = &after[..end];
298                match values.get(key) {
299                    Some(v) => out.push_str(v),
300                    None => {
301                        out.push_str("${");
302                        out.push_str(key);
303                        out.push('}');
304                    }
305                }
306                rest = &after[end + 1..];
307            }
308            None => {
309                out.push_str(&rest[start..]);
310                rest = "";
311            }
312        }
313    }
314    out.push_str(rest);
315    out
316}
317
318#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
319pub enum SettingKind {
320    #[default]
321    Text,
322    Number,
323    Boolean,
324    Directory,
325    File,
326}
327
328impl SettingKind {
329    fn parse(s: &str) -> Option<Self> {
330        Some(match s {
331            "text" => Self::Text,
332            "number" => Self::Number,
333            "boolean" => Self::Boolean,
334            "directory" => Self::Directory,
335            "file" => Self::File,
336            _ => return None,
337        })
338    }
339}
340
341/// A value the user fills in on the plugin's card; passed to tools and servers as an
342/// environment variable named `key`.
343#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
344pub struct Setting {
345    /// `[A-Z][A-Z0-9_]{0,63}`.
346    pub key: String,
347    pub label: String,
348    pub secret: bool,
349    pub help: Option<String>,
350    pub kind: SettingKind,
351    pub required: bool,
352    pub multiple: bool,
353    /// Lists are joined with newlines, as hob does.
354    pub default: Option<String>,
355}
356
357/// Why a manifest was rejected; the message is meant for the plugin's author.
358#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
359#[error("{file}: {message}")]
360pub struct ManifestError {
361    pub file: String,
362    pub message: String,
363}
364
365/// Options for [`parse_manifest`].
366#[derive(Debug, Clone, Copy, Default)]
367pub struct ParseOptions<'a> {
368    /// Ships with the app: may use `native` tools and a longer prompt.
369    pub builtin: bool,
370    /// File name used in error messages; [`MANIFEST`] when `None`.
371    pub file: Option<&'a str>,
372}
373
374/// `[a-z0-9][a-z0-9-]{0,47}`
375pub fn plugin_id_ok(id: &str) -> bool {
376    let b = id.as_bytes();
377    !b.is_empty() && b.len() <= 48 && is_lower_alnum(b[0]) && b.iter().all(|&c| is_lower_alnum(c) || c == b'-')
378}
379
380/// `[A-Za-z][A-Za-z0-9_]{0,63}`
381pub fn tool_name_ok(name: &str) -> bool {
382    let b = name.as_bytes();
383    !b.is_empty() && b.len() <= 64 && b[0].is_ascii_alphabetic() && b.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_')
384}
385
386/// `[A-Z][A-Z0-9_]{0,63}`
387pub fn setting_key_ok(key: &str) -> bool {
388    let b = key.as_bytes();
389    !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'_')
390}
391
392fn is_lower_alnum(c: u8) -> bool {
393    c.is_ascii_lowercase() || c.is_ascii_digit()
394}
395
396/// A relative path that stays inside its folder (`tools/x.py`, not `/x` or `../x`).
397pub fn path_inside(p: &str) -> bool {
398    let mut depth: usize = 0;
399    for c in Path::new(p).components() {
400        match c {
401            Component::Normal(_) => depth += 1,
402            Component::CurDir => {}
403            Component::ParentDir => match depth.checked_sub(1) {
404                Some(d) => depth = d,
405                None => return false,
406            },
407            Component::RootDir | Component::Prefix(_) => return false,
408        }
409    }
410    // Windows-style absolute paths on other systems.
411    !(p.starts_with('\\') || p.as_bytes().get(1) == Some(&b':'))
412}
413
414/// Check a parsed `byob-plugin.json` and fill in defaults.
415pub fn parse_manifest(raw: &Value, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
416    let file = opts.file.unwrap_or(MANIFEST);
417    parse(raw, opts.builtin).map_err(|message| ManifestError { file: file.to_string(), message })
418}
419
420/// Parse manifest text (JSON).
421pub fn parse_manifest_str(text: &str, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
422    let file = opts.file.unwrap_or(MANIFEST);
423    let raw: Value = serde_json::from_str(text).map_err(|e| ManifestError { file: file.to_string(), message: format!("isn't valid JSON: {e}") })?;
424    parse_manifest(&raw, opts)
425}
426
427type R<T> = Result<T, String>;
428
429/// Required text: present, a string, not blank. Trimmed.
430fn req_str(v: Option<&Value>, field: &str) -> R<String> {
431    match v {
432        Some(Value::String(s)) if !s.trim().is_empty() => Ok(s.trim().to_string()),
433        _ => Err(format!("{field} must be text")),
434    }
435}
436
437/// Optional text: absent → `None`; present must be a string.
438fn opt_str(v: Option<&Value>, field: &str) -> R<Option<String>> {
439    match v {
440        None => Ok(None),
441        Some(Value::String(s)) => Ok(Some(s.trim().to_string())),
442        Some(_) => Err(format!("{field} must be text")),
443    }
444}
445
446fn list<'a>(v: Option<&'a Value>, field: &str) -> R<&'a [Value]> {
447    match v {
448        None => Ok(&[]),
449        Some(Value::Array(a)) => Ok(a),
450        Some(_) => Err(format!("{field} must be a list")),
451    }
452}
453
454fn obj<'a>(v: &'a Value, field: &str) -> R<&'a Map<String, Value>> {
455    v.as_object().ok_or_else(|| format!("{field} must be an object"))
456}
457
458fn str_map(v: Option<&Value>, field: &str) -> R<BTreeMap<String, String>> {
459    let Some(v) = v else { return Ok(BTreeMap::new()) };
460    let bad = || format!("{field} must map names to text");
461    let m = v.as_object().ok_or_else(bad)?;
462    m.iter().map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(bad)).collect()
463}
464
465fn truthy(v: Option<&Value>) -> bool {
466    match v {
467        None | Some(Value::Null) => false,
468        Some(Value::Bool(b)) => *b,
469        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
470        Some(Value::String(s)) => !s.is_empty(),
471        Some(_) => true,
472    }
473}
474
475fn truncate_chars(s: &str, max: usize) -> String {
476    s.chars().take(max).collect()
477}
478
479fn parse(raw: &Value, builtin: bool) -> R<Manifest> {
480    let r = raw.as_object().ok_or("must be a JSON object")?;
481    let id = req_str(r.get("id"), "id")?;
482    if !plugin_id_ok(&id) {
483        return Err("id must be lowercase letters, digits and dashes, like \"trip-planner\"".into());
484    }
485    let tools = list(r.get("tools"), "tools")?.iter().enumerate().map(|(i, t)| parse_tool(t, i)).collect::<R<Vec<_>>>()?;
486    let mcp_servers = parse_servers(r.get("mcpServers"))?;
487    let settings = list(r.get("settings"), "settings")?.iter().enumerate().map(|(i, s)| parse_setting(s, i)).collect::<R<Vec<_>>>()?;
488    let starters = list(r.get("starters"), "starters")?
489        .iter()
490        .enumerate()
491        .map(|(i, s)| {
492            let f = format!("starters[{i}]");
493            let s = obj(s, &f)?;
494            Ok(Starter {
495                title: req_str(s.get("title"), &format!("{f}.title"))?,
496                prompt: req_str(s.get("prompt"), &format!("{f}.prompt"))?,
497                file: s.get("file") == Some(&Value::Bool(true)),
498            })
499        })
500        .collect::<R<Vec<_>>>()?;
501    let network = r.get("permissions").and_then(Value::as_object).and_then(|p| p.get("network")) == Some(&Value::Bool(true));
502    let prompt = match r.get("prompt") {
503        None => None,
504        p => Some(truncate_chars(&req_str(p, "prompt")?, if builtin { PROMPT_MAX_BUILTIN } else { PROMPT_MAX })),
505    };
506    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());
507    let author = match r.get("author") {
508        None => None,
509        a => Some(req_str(a, "author")?),
510    };
511    let backend = parse_backend(r.get("backend"))?;
512    if backend.is_none()
513        && let Some(i) = tools.iter().position(|t| t.kind == ToolKind::Backend)
514    {
515        return Err(format!("tools[{i}].run is \"backend\" but the plugin has no \"backend\""));
516    }
517    let requirements = parse_requirements(r.get("python"))?;
518    let hooks = parse_hooks(r.get("hooks"), backend.is_some())?;
519    let name = req_str(r.get("name"), "name")?;
520    let views = parse_views(r.get("views"), &name)?;
521    if backend.is_none() && views.iter().any(|v| v.html.is_empty()) {
522        return Err("views are drawn by the plugin's backend: add \"backend\": \"backend.py\" (or give the view an \"html\" file)".into());
523    }
524    let renderers = parse_renderers(r.get("renderers"))?;
525    for (i, d) in renderers.iter().enumerate() {
526        if let Some(v) = d.renderer.strip_prefix("view:")
527            && !views.iter().any(|x| x.id == v && x.site == "artifact")
528        {
529            return Err(format!("renderers[{i}].renderer: {:?} needs a view {{\"site\": \"artifact\", \"id\": \"{v}\"}} in \"views\"", d.renderer));
530        }
531    }
532    Ok(Manifest {
533        id,
534        name,
535        version: opt_str(r.get("version"), "version")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "0.0.0".into()),
536        description: opt_str(r.get("description"), "description")?.unwrap_or_default(),
537        author,
538        icon: opt_str(r.get("icon"), "icon")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "puzzle".into()),
539        permissions: Permissions { network },
540        starters,
541        tools,
542        mcp_servers,
543        settings,
544        prompt,
545        platforms,
546        backend,
547        requirements,
548        views,
549        locked: r.get("locked") == Some(&Value::Bool(true)),
550        on_by_default: r.get("enabled") != Some(&Value::Bool(false)),
551        provides: match opt_str(r.get("provides"), "provides")?.map(|p| p.trim().to_owned()).filter(|p| !p.is_empty()) {
552            Some(p) if !plugin_id_ok(&p) => return Err("provides must be lowercase letters, digits and dashes, like \"spreadsheets\"".into()),
553            p => p,
554        },
555        artifact_types: parse_artifact_types(r.get("artifact_types").or_else(|| r.get("content_types")))?,
556        renderers,
557        system_prompt: parse_prompt_source(r.get("system_prompt"))?,
558        hooks,
559        environments: parse_environments(r.get("environments"))?,
560    })
561}
562
563/// `"hooks": [{"event", "priority"?, "native"? | "backend": true, "timeout_ms"?, "fail"?, "tools"?}]`.
564fn parse_hooks(v: Option<&Value>, has_backend: bool) -> R<Vec<ManifestHook>> {
565    let items = list(v, "hooks")?;
566    if items.len() > MAX_HOOKS {
567        return Err(format!("hooks: at most {MAX_HOOKS}"));
568    }
569    let mut out = Vec::new();
570    for (i, item) in items.iter().enumerate() {
571        let f = format!("hooks[{i}]");
572        let o = obj(item, &f)?;
573        let event = req_str(o.get("event"), &format!("{f}.event"))?;
574        if !HOOK_EVENTS.contains(&event.as_str()) {
575            return Err(format!("{f}.event must be one of {}", HOOK_EVENTS.join(", ")));
576        }
577        let priority = match o.get("priority") {
578            None | Some(Value::Null) => DEFAULT_HOOK_PRIORITY,
579            Some(p) => p.as_i64().filter(|p| p.abs() <= 1_000_000).ok_or_else(|| format!("{f}.priority must be a whole number"))?,
580        };
581        let native = opt_str(o.get("native"), &format!("{f}.native"))?;
582        if let Some(n) = &native
583            && !native_id_ok(n)
584        {
585            return Err(format!("{f}.native must be an id like \"compaction\""));
586        }
587        if native.is_none() && !has_backend {
588            return Err(format!("{f} is answered by the plugin's backend: add \"backend\": \"backend.py\" (or name in-tree code with \"native\")"));
589        }
590        let timeout_ms = match o.get("timeout_ms") {
591            None | Some(Value::Null) => HOOK_TIMEOUT_MS,
592            Some(t) => {
593                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}"))?
594            }
595        };
596        let fail_closed = match opt_str(o.get("fail"), &format!("{f}.fail"))?.as_deref() {
597            None | Some("open") => false,
598            Some("closed") => true,
599            Some(_) => return Err(format!("{f}.fail must be \"open\" or \"closed\"")),
600        };
601        let tools = list(o.get("tools"), &format!("{f}.tools"))?
602            .iter()
603            .enumerate()
604            .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")))
605            .collect::<R<Vec<_>>>()?;
606        if !tools.is_empty() && !matches!(event.as_str(), "before_tool_call" | "after_tool_call") {
607            return Err(format!("{f}.tools only applies to before_tool_call and after_tool_call"));
608        }
609        out.push(ManifestHook { event, priority, native, timeout_ms, fail_closed, tools });
610    }
611    Ok(out)
612}
613
614/// `"environments": [{"native": "nix"}, {"id", "label", "detect", "inputs"?, "command", "args"?}]`.
615fn parse_environments(v: Option<&Value>) -> R<Vec<ManifestEnv>> {
616    let items = list(v, "environments")?;
617    if items.len() > MAX_ENVIRONMENTS {
618        return Err(format!("environments: at most {MAX_ENVIRONMENTS}"));
619    }
620    let mut out: Vec<ManifestEnv> = Vec::new();
621    for (i, item) in items.iter().enumerate() {
622        let f = format!("environments[{i}]");
623        let o = obj(item, &f)?;
624        let native = opt_str(o.get("native"), &format!("{f}.native"))?;
625        let id = match (&native, o.get("id")) {
626            (Some(n), None) => n.clone(),
627            (_, v) => req_str(v, &format!("{f}.id"))?,
628        };
629        let id_ok = (1..=32).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'));
630        if !id_ok || native.as_deref().is_some_and(|n| !native_id_ok(n)) {
631            return Err(format!("{f}.id must be lowercase letters, digits, _ or -, like \"conda\""));
632        }
633        if out.iter().any(|e| e.id == id) {
634            return Err(format!("{f}.id {id:?} is used twice"));
635        }
636        let files = |key: &str| -> R<Vec<String>> {
637            list(o.get(key), &format!("{f}.{key}"))?
638                .iter()
639                .enumerate()
640                .map(|(j, p)| match p.as_str().map(str::trim) {
641                    Some(p) if !p.is_empty() && path_inside(p) => Ok(p.to_owned()),
642                    _ => Err(format!("{f}.{key}[{j}] must be a file name inside the workspace, like \"environment.yml\"")),
643                })
644                .collect()
645        };
646        let detect = files("detect")?;
647        let inputs = files("inputs")?;
648        let command = opt_str(o.get("command"), &format!("{f}.command"))?.filter(|c| !c.is_empty());
649        let args = list(o.get("args"), &format!("{f}.args"))?
650            .iter()
651            .enumerate()
652            .map(|(j, a)| a.as_str().map(str::to_owned).ok_or_else(|| format!("{f}.args[{j}] must be text")))
653            .collect::<R<Vec<_>>>()?;
654        if native.is_none() && (detect.is_empty() || command.is_none()) {
655            return Err(format!("{f} needs \"native\" (built into byob) or \"detect\" (the workspace files) and \"command\" (prints the environment as JSON)"));
656        }
657        let label =
658            truncate_chars(&opt_str(o.get("label"), &format!("{f}.label"))?.filter(|l| !l.is_empty()).unwrap_or_else(|| format!("{id} environment")), 60);
659        out.push(ManifestEnv { id, native, label, detect, inputs, command, args });
660    }
661    Ok(out)
662}
663
664/// `type/subtype`, lowercase (what `byob_protocol::artifact::valid_content_type` takes).
665fn content_type_ok(t: &str) -> bool {
666    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'-'));
667    t.len() <= 128 && t.split_once('/').is_some_and(|(a, b)| ok(a) && (ok(b) || b == "*"))
668}
669
670fn native_id_ok(id: &str) -> bool {
671    (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.'))
672}
673
674fn parse_artifact_types(v: Option<&Value>) -> R<Vec<ManifestArtifactType>> {
675    let items = list(v, "artifact_types")?;
676    if items.len() > MAX_TYPES {
677        return Err(format!("artifact_types: at most {MAX_TYPES}"));
678    }
679    let mut out: Vec<ManifestArtifactType> = Vec::new();
680    for (i, item) in items.iter().enumerate() {
681        let f = format!("artifact_types[{i}]");
682        let o = obj(item, &f)?;
683        let content_type = req_str(o.get("type"), &format!("{f}.type"))?.to_ascii_lowercase();
684        if !content_type_ok(&content_type) || content_type.ends_with("/*") {
685            return Err(format!("{f}.type must be a content type like \"text/csv\""));
686        }
687        if out.iter().any(|t| t.content_type == content_type) {
688            return Err(format!("{f}.type {content_type:?} is declared twice"));
689        }
690        let native = opt_str(o.get("native"), &format!("{f}.native"))?;
691        if let Some(n) = &native
692            && !native_id_ok(n)
693        {
694            return Err(format!("{f}.native must be an id like \"html_app\""));
695        }
696        let suffixes = match o.get("suffixes") {
697            None => None,
698            v => Some(
699                list(v, &format!("{f}.suffixes"))?
700                    .iter()
701                    .enumerate()
702                    .map(|(j, s)| match s.as_str().map(str::trim) {
703                        Some(s) if s.starts_with('.') && s.len() > 1 && s.len() <= 32 && !s.contains(['/', '\\']) => Ok(s.to_ascii_lowercase()),
704                        _ => Err(format!("{f}.suffixes[{j}] must be a file name ending like \".csv\"")),
705                    })
706                    .collect::<R<Vec<_>>>()?,
707            ),
708        };
709        if native.is_none() && suffixes.as_ref().is_none_or(Vec::is_empty) {
710            return Err(format!("{f} needs \"native\" (a type built into byob) or \"suffixes\" (the file names it covers)"));
711        }
712        let guidance = opt_str(o.get("guidance"), &format!("{f}.guidance"))?;
713        if let Some(g) = &guidance
714            && (g.is_empty() || !path_inside(g))
715        {
716            return Err(format!("{f}.guidance must be a file inside the plugin folder, like \"guidance.md\""));
717        }
718        let short = |key: &str| -> R<Option<String>> { Ok(opt_str(o.get(key), &format!("{f}.{key}"))?.map(|s| truncate_chars(&s, 400))) };
719        let binary = match o.get("binary") {
720            None | Some(Value::Null) => false,
721            Some(Value::Bool(b)) => *b,
722            Some(_) => return Err(format!("{f}.binary must be true or false")),
723        };
724        out.push(ManifestArtifactType {
725            content_type,
726            native,
727            suffixes,
728            label: short("label")?,
729            describe: short("describe")?,
730            pick: short("pick")?,
731            guidance,
732            binary,
733        });
734    }
735    Ok(out)
736}
737
738fn parse_renderers(v: Option<&Value>) -> R<Vec<ManifestRenderer>> {
739    let items = list(v, "renderers")?;
740    if items.len() > MAX_TYPES {
741        return Err(format!("renderers: at most {MAX_TYPES}"));
742    }
743    items
744        .iter()
745        .enumerate()
746        .map(|(i, item)| {
747            let f = format!("renderers[{i}]");
748            let o = obj(item, &f)?;
749            let content_type = req_str(o.get("type"), &format!("{f}.type"))?.to_ascii_lowercase();
750            if !content_type_ok(&content_type) {
751                return Err(format!("{f}.type must be a content type like \"text/csv\" (or \"image/*\")"));
752            }
753            let renderer = req_str(o.get("renderer"), &format!("{f}.renderer"))?;
754            let web_file = renderer.strip_prefix("web:").map(str::trim);
755            let ok = matches!(renderer.as_str(), "web" | "text")
756                || renderer.strip_prefix("native:").is_some_and(native_id_ok)
757                || renderer.strip_prefix("view:").is_some_and(byob_view_id_ok)
758                || web_file.is_some_and(|p| !p.is_empty() && path_inside(p));
759            if !ok {
760                return Err(format!("{f}.renderer must be \"web\", \"web:<html file in the plugin>\", \"text\", \"native:<id>\" or \"view:<view id>\""));
761            }
762            Ok(ManifestRenderer { content_type, renderer })
763        })
764        .collect()
765}
766
767fn parse_prompt_source(v: Option<&Value>) -> R<Option<PromptSource>> {
768    let f = "system_prompt";
769    match v {
770        None | Some(Value::Null) => Ok(None),
771        Some(Value::String(s)) => {
772            let s = s.trim();
773            if s.is_empty() || !path_inside(s) {
774                return Err(format!("{f} must be a file inside the plugin folder, like \"prompt.md\""));
775            }
776            Ok(Some(PromptSource::File(s.to_owned())))
777        }
778        Some(v) => {
779            let o = obj(v, f)?;
780            let n = req_str(o.get("native"), &format!("{f}.native"))?;
781            if !native_id_ok(&n) {
782                return Err(format!("{f}.native must be an id like \"artifacts\""));
783            }
784            Ok(Some(PromptSource::Native(n)))
785        }
786    }
787}
788
789/// A view id: `[a-z0-9_-]{1,48}`.
790fn byob_view_id_ok(id: &str) -> bool {
791    (1..=48).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
792}
793
794/// `"views": [{"site": "pane", "id": "todo", "title": "To do", "icon": "list"}]`.
795fn parse_views(v: Option<&Value>, plugin_name: &str) -> R<Vec<ManifestView>> {
796    let items = list(v, "views")?;
797    if items.len() > MAX_VIEWS {
798        return Err(format!("views: at most {MAX_VIEWS}"));
799    }
800    let mut out: Vec<ManifestView> = Vec::new();
801    for (i, item) in items.iter().enumerate() {
802        let f = format!("views[{i}]");
803        let o = obj(item, &f)?;
804        let site = req_str(o.get("site"), &format!("{f}.site"))?;
805        if !VIEW_SITES.contains(&site.as_str()) {
806            return Err(format!("{f}.site must be one of {}", VIEW_SITES.join(", ")));
807        }
808        let id = match o.get("id") {
809            None => site.clone(),
810            v => req_str(v, &format!("{f}.id"))?,
811        };
812        if !byob_view_id_ok(&id) {
813            return Err(format!("{f}.id must be lowercase letters, digits, _ or -, like \"todo\""));
814        }
815        if out.iter().any(|x| x.id == id) {
816            return Err(format!("{f}.id {id:?} is used twice"));
817        }
818        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);
819        let icon = opt_str(o.get("icon"), &format!("{f}.icon"))?.unwrap_or_default();
820        let html = opt_str(o.get("html"), &format!("{f}.html"))?.map(|h| h.trim().to_owned()).unwrap_or_default();
821        if !html.is_empty() && !path_inside(&html) {
822            return Err(format!("{f}.html must be a file inside the plugin folder, like \"ui/index.html\""));
823        }
824        if !html.is_empty() && !matches!(site.as_str(), "pane" | "card") {
825            return Err(format!("{f}: a web view (\"html\") goes in the pane or on a card"));
826        }
827        out.push(ManifestView { id, site, title, icon, html });
828    }
829    Ok(out)
830}
831
832/// `"backend": "backend.py"`, `{"run": "backend.py", "args": [], "events": []}` or
833/// `{"command": "node", "args": ["server.js"]}`.
834fn parse_backend(v: Option<&Value>) -> R<Option<BackendDecl>> {
835    let f = "backend";
836    let script = |p: String| -> R<BackendRun> {
837        if !path_inside(&p) || p.is_empty() {
838            return Err(format!("{f}.run must be a path inside the plugin folder, like \"backend.py\""));
839        }
840        Ok(BackendRun::Python(p))
841    };
842    let o = match v {
843        None | Some(Value::Null) => return Ok(None),
844        Some(Value::String(s)) => return Ok(Some(BackendDecl { run: script(s.trim().to_string())?, args: Vec::new(), events: Vec::new() })),
845        Some(v) => obj(v, f)?,
846    };
847    let run = match (o.get("run"), o.get("command"), o.get("native")) {
848        (Some(r), None, None) => script(req_str(Some(r), &format!("{f}.run"))?)?,
849        (None, Some(c), None) => BackendRun::Command(req_str(Some(c), &format!("{f}.command"))?),
850        (None, None, Some(n)) => BackendRun::Native(req_str(Some(n), &format!("{f}.native"))?),
851        _ => return Err(format!("{f} needs \"run\" (a Python script), \"command\" (a program) or \"native\" (a backend built into byob), one of them")),
852    };
853    let strings = |key: &str| -> R<Vec<String>> {
854        list(o.get(key), &format!("{f}.{key}"))?
855            .iter()
856            .enumerate()
857            .map(|(i, a)| a.as_str().map(str::to_string).ok_or_else(|| format!("{f}.{key}[{i}] must be text")))
858            .collect()
859    };
860    let args = strings("args")?;
861    let events = strings("events")?;
862    if let Some(e) = events.iter().find(|e| !BACKEND_EVENTS.contains(&e.as_str())) {
863        return Err(format!("{f}.events: {e:?} isn't an engine event; use {}", BACKEND_EVENTS.join(", ")));
864    }
865    Ok(Some(BackendDecl { run, args, events }))
866}
867
868/// `"python": {"requirements": ["requests>=2", "./wheels/x.whl"]}`.
869fn parse_requirements(v: Option<&Value>) -> R<Vec<String>> {
870    let Some(v) = v else { return Ok(Vec::new()) };
871    let o = obj(v, "python")?;
872    let reqs = list(o.get("requirements"), "python.requirements")?;
873    if reqs.len() > MAX_REQUIREMENTS {
874        return Err(format!("python.requirements: at most {MAX_REQUIREMENTS} packages"));
875    }
876    reqs.iter()
877        .enumerate()
878        .map(|(i, r)| {
879            let r = req_str(Some(r), &format!("python.requirements[{i}]"))?;
880            // one pip spec each, never options (--index-url …)
881            if r.starts_with('-') || r.contains(['\n', '\r']) || r.len() > 512 {
882                return Err(format!("python.requirements[{i}] must be one package spec like \"requests>=2.31\""));
883            }
884            Ok(r)
885        })
886        .collect()
887}
888
889fn parse_tool(t: &Value, i: usize) -> R<ManifestTool> {
890    let f = format!("tools[{i}]");
891    let t = obj(t, &f)?;
892    let native = match t.get("native") {
893        None => None,
894        n => Some(req_str(n, &format!("{f}.native"))?),
895    };
896    // native tools bring their own name, description and parameters
897    let name = match (&native, t.get("name")) {
898        (Some(n), None) => n.clone(),
899        (_, v) => req_str(v, &format!("{f}.name"))?,
900    };
901    if !tool_name_ok(&name) {
902        return Err(format!("{f}.name must be letters, digits or _, starting with a letter"));
903    }
904    let params = match t.get("params") {
905        None => serde_json::json!({ "type": "object", "properties": {} }),
906        Some(p @ Value::Object(_)) => p.clone(),
907        Some(_) => return Err(format!("{f}.params must be a JSON schema object")),
908    };
909    let run = match t.get("run") {
910        None => None,
911        Some(Value::String(s)) if s.trim() == "backend" => Some(String::new()),
912        v => {
913            let p = req_str(v, &format!("{f}.run"))?;
914            if !path_inside(&p) {
915                return Err(format!("{f}.run must be a path inside the plugin folder"));
916            }
917            Some(p)
918        }
919    };
920    let kind = match (run, native) {
921        (Some(r), _) if r.is_empty() => ToolKind::Backend,
922        (Some(r), _) => ToolKind::Script(r),
923        (None, Some(n)) => ToolKind::Native(n),
924        (None, None) => return Err(format!("{f}.run must name the Python script that runs this tool")),
925    };
926    let description = match (&kind, t.get("description")) {
927        (ToolKind::Native(_), None) => String::new(),
928        (_, d) => req_str(d, &format!("{f}.description"))?,
929    };
930    let title = match t.get("title") {
931        None => None,
932        v => Some(req_str(v, &format!("{f}.title"))?),
933    };
934    let optional = t.get("optional") == Some(&Value::Bool(true));
935    Ok(ManifestTool { name, description, params, kind, title, optional })
936}
937
938fn parse_servers(v: Option<&Value>) -> R<BTreeMap<String, McpServerConfig>> {
939    let Some(v) = v else { return Ok(BTreeMap::new()) };
940    let m = v.as_object().ok_or("mcpServers must be an object of servers")?;
941    m.iter().map(|(k, v)| Ok((k.clone(), parse_server(v, &format!("mcpServers.{k}"))?))).collect()
942}
943
944/// One entry of an `mcpServers` object (manifest or pasted Claude/Cursor config).
945pub(crate) fn parse_server(v: &Value, f: &str) -> R<McpServerConfig> {
946    let v = obj(v, f)?;
947    let ty = v.get("type").and_then(Value::as_str);
948    if v.get("url").is_some() || matches!(ty, Some("http" | "sse" | "streamable-http")) {
949        let url = req_str(v.get("url"), &format!("{f}.url"))?;
950        let lower = url.to_ascii_lowercase();
951        let rest = lower.strip_prefix("https://").or_else(|| lower.strip_prefix("http://"));
952        if !rest.is_some_and(|r| !r.is_empty() && !r.starts_with('/')) {
953            return Err(format!("{f}.url must start with https://"));
954        }
955        let headers = str_map(v.get("headers"), &format!("{f}.headers"))?;
956        let oauth = match v.get("oauth") {
957            None => None,
958            Some(o) => {
959                let o = obj(o, &format!("{f}.oauth"))?;
960                Some(OAuthClient {
961                    client_id: req_str(o.get("clientId"), &format!("{f}.oauth.clientId"))?,
962                    client_secret: match o.get("clientSecret") {
963                        None => None,
964                        s => Some(req_str(s, &format!("{f}.oauth.clientSecret"))?),
965                    },
966                })
967            }
968        };
969        return Ok(McpServerConfig::Url { url, sse: ty == Some("sse"), headers, oauth });
970    }
971    let args = list(v.get("args"), &format!("{f}.args"))?
972        .iter()
973        .enumerate()
974        .map(|(i, a)| a.as_str().map(|s| s.trim().to_string()).ok_or_else(|| format!("{f}.args[{i}] must be text")))
975        .collect::<R<Vec<_>>>()?;
976    let env = str_map(v.get("env"), &format!("{f}.env"))?;
977    Ok(McpServerConfig::Stdio { command: req_str(v.get("command"), &format!("{f}.command"))?, args, env })
978}
979
980fn parse_setting(s: &Value, i: usize) -> R<Setting> {
981    let f = format!("settings[{i}]");
982    let s = obj(s, &f)?;
983    let key = req_str(s.get("key"), &format!("{f}.key"))?;
984    if !setting_key_ok(&key) {
985        return Err(format!("{f}.key must be UPPER_CASE, like \"API_KEY\""));
986    }
987    let kind = match s.get("type") {
988        None => SettingKind::Text,
989        t => {
990            let t = req_str(t, &format!("{f}.type"))?;
991            SettingKind::parse(&t).ok_or_else(|| format!("{f}.type must be one of text, number, boolean, directory, file"))?
992        }
993    };
994    let help = match s.get("help") {
995        None => None,
996        h => Some(req_str(h, &format!("{f}.help"))?),
997    };
998    let default = s.get("default").map(|d| match d {
999        Value::Array(a) => a.iter().map(value_text).collect::<Vec<_>>().join("\n"),
1000        other => value_text(other),
1001    });
1002    Ok(Setting {
1003        key,
1004        label: req_str(s.get("label"), &format!("{f}.label"))?,
1005        secret: truthy(s.get("secret")),
1006        help,
1007        kind,
1008        required: truthy(s.get("required")),
1009        multiple: truthy(s.get("multiple")),
1010        default,
1011    })
1012}
1013
1014/// JS `String(v)` for the values settings defaults take.
1015fn value_text(v: &Value) -> String {
1016    match v {
1017        Value::String(s) => s.clone(),
1018        Value::Null => "null".into(),
1019        other => other.to_string(),
1020    }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026    use serde_json::json;
1027
1028    fn parse_user(v: Value) -> Result<Manifest, String> {
1029        parse_manifest(&v, ParseOptions::default()).map_err(|e| e.to_string())
1030    }
1031
1032    #[test]
1033    fn minimal_manifest_gets_defaults() {
1034        let m = parse_user(json!({"id": "recipe-helper", "name": "Recipe Helper", "extra": {"future": true}})).unwrap();
1035        assert_eq!(m.version, "0.0.0");
1036        assert_eq!(m.icon, "puzzle");
1037        assert!(!m.permissions.network);
1038        assert!(m.tools.is_empty() && m.mcp_servers.is_empty() && m.settings.is_empty());
1039    }
1040
1041    #[test]
1042    fn author_facing_errors() {
1043        let cases = [
1044            (json!([]), "byob-plugin.json: must be a JSON object"),
1045            (json!({"name": "x"}), "byob-plugin.json: id must be text"),
1046            (json!({"id": "Bad_Id", "name": "x"}), "byob-plugin.json: id must be lowercase letters, digits and dashes, like \"trip-planner\""),
1047            (json!({"id": "a", "name": "x", "tools": {}}), "byob-plugin.json: tools must be a list"),
1048            (
1049                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "../escape.py"}]}),
1050                "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
1051            ),
1052            (
1053                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "/abs.py"}]}),
1054                "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
1055            ),
1056            (
1057                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d"}]}),
1058                "byob-plugin.json: tools[0].run must name the Python script that runs this tool",
1059            ),
1060            (
1061                json!({"id": "a", "name": "x", "tools": [{"name": "1t", "description": "d", "run": "t.py"}]}),
1062                "byob-plugin.json: tools[0].name must be letters, digits or _, starting with a letter",
1063            ),
1064            (
1065                json!({"id": "a", "name": "x", "artifact_types": [{"type": "csv"}]}),
1066                "byob-plugin.json: artifact_types[0].type must be a content type like \"text/csv\"",
1067            ),
1068            (
1069                json!({"id": "a", "name": "x", "artifact_types": [{"type": "text/csv"}]}),
1070                "byob-plugin.json: artifact_types[0] needs \"native\" (a type built into byob) or \"suffixes\" (the file names it covers)",
1071            ),
1072            (
1073                json!({"id": "a", "name": "x", "renderers": [{"type": "text/csv", "renderer": "wasm"}]}),
1074                "byob-plugin.json: renderers[0].renderer must be \"web\", \"web:<html file in the plugin>\", \"text\", \"native:<id>\" or \"view:<view id>\"",
1075            ),
1076            (
1077                json!({"id": "a", "name": "x", "system_prompt": "../p.md"}),
1078                "byob-plugin.json: system_prompt must be a file inside the plugin folder, like \"prompt.md\"",
1079            ),
1080            (
1081                json!({"id": "a", "name": "x", "settings": [{"key": "api_key", "label": "k"}]}),
1082                "byob-plugin.json: settings[0].key must be UPPER_CASE, like \"API_KEY\"",
1083            ),
1084            (
1085                json!({"id": "a", "name": "x", "settings": [{"key": "K", "label": "k", "type": "color"}]}),
1086                "byob-plugin.json: settings[0].type must be one of text, number, boolean, directory, file",
1087            ),
1088            (json!({"id": "a", "name": "x", "mcpServers": {"s": {"url": "ftp://x"}}}), "byob-plugin.json: mcpServers.s.url must start with https://"),
1089            (
1090                json!({"id": "a", "name": "x", "mcpServers": {"s": {"command": "x", "env": {"A": 1}}}}),
1091                "byob-plugin.json: mcpServers.s.env must map names to text",
1092            ),
1093            (json!({"id": "a", "name": "x", "mcpServers": {"s": {}}}), "byob-plugin.json: mcpServers.s.command must be text"),
1094        ];
1095        for (raw, want) in cases {
1096            assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1097        }
1098    }
1099
1100    #[test]
1101    fn python_tool_and_settings() {
1102        let m = parse_user(json!({
1103            "id": "text-stats", "name": "Text stats", "permissions": {"network": true},
1104            "tools": [{"name": "count_words", "description": "Count words.", "params": {"type": "object", "properties": {"file": {"type": "string"}}}, "run": "tools/count.py", "title": "Counted {file}"}],
1105            "settings": [{"key": "API_KEY", "label": "API key", "secret": true, "type": "directory", "multiple": true, "default": ["/a", "/b"]}],
1106            "starters": [{"title": "Go", "prompt": "/go", "file": true}],
1107            "prompt": "x".repeat(700),
1108        }))
1109        .unwrap();
1110        assert!(m.permissions.network);
1111        assert_eq!(m.tools[0].kind, ToolKind::Script("tools/count.py".into()));
1112        assert_eq!(m.tools[0].title.as_deref(), Some("Counted {file}"));
1113        let s = &m.settings[0];
1114        assert!(s.secret && s.multiple && !s.required);
1115        assert_eq!(s.kind, SettingKind::Directory);
1116        assert_eq!(s.default.as_deref(), Some("/a\n/b"));
1117        assert!(m.starters[0].file);
1118        assert_eq!(m.prompt.map(|p| p.chars().count()), Some(600));
1119    }
1120
1121    #[test]
1122    fn backends_and_requirements() {
1123        let m = parse_user(json!({"id": "a", "name": "x", "backend": "backend.py", "tools": [{"name": "t", "description": "d", "run": "backend"}],
1124            "python": {"requirements": ["requests>=2", "./wheels/w.whl"]}}))
1125        .unwrap();
1126        assert_eq!(m.backend.unwrap().run, BackendRun::Python("backend.py".into()));
1127        assert_eq!(m.tools[0].kind, ToolKind::Backend);
1128        assert_eq!(m.requirements, ["requests>=2", "./wheels/w.whl"]);
1129        let m = parse_user(json!({"id": "a", "name": "x", "backend": {"command": "node", "args": ["s.js"], "events": ["turn_finished"]}})).unwrap();
1130        let b = m.backend.unwrap();
1131        assert_eq!((b.run, b.args, b.events), (BackendRun::Command("node".into()), vec!["s.js".to_string()], vec!["turn_finished".to_string()]));
1132        let cases = [
1133            (
1134                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "backend"}]}),
1135                "byob-plugin.json: tools[0].run is \"backend\" but the plugin has no \"backend\"",
1136            ),
1137            (
1138                json!({"id": "a", "name": "x", "backend": "../b.py"}),
1139                "byob-plugin.json: backend.run must be a path inside the plugin folder, like \"backend.py\"",
1140            ),
1141            (
1142                json!({"id": "a", "name": "x", "backend": {"run": "b.py", "command": "node"}}),
1143                "byob-plugin.json: backend needs \"run\" (a Python script), \"command\" (a program) or \"native\" (a backend built into byob), one of them",
1144            ),
1145            (
1146                json!({"id": "a", "name": "x", "provides": "Spread Sheets"}),
1147                "byob-plugin.json: provides must be lowercase letters, digits and dashes, like \"spreadsheets\"",
1148            ),
1149            (
1150                json!({"id": "a", "name": "x", "backend": {"run": "b.py", "events": ["tick"]}}),
1151                "byob-plugin.json: backend.events: \"tick\" isn't an engine event; use chat_opened, turn_started, turn_finished, step_done, artifact_updated",
1152            ),
1153            (
1154                json!({"id": "a", "name": "x", "python": {"requirements": ["--index-url=http://x"]}}),
1155                "byob-plugin.json: python.requirements[0] must be one package spec like \"requests>=2.31\"",
1156            ),
1157        ];
1158        for (raw, want) in cases {
1159            assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1160        }
1161    }
1162
1163    #[test]
1164    fn native_backends_default_switches_and_provides() {
1165        let m = parse_user(json!({"id": "a", "name": "x", "backend": {"native": "sheets"}, "enabled": false, "provides": "spreadsheets"})).unwrap();
1166        assert_eq!(m.backend.unwrap().run, BackendRun::Native("sheets".into()));
1167        assert!(!m.on_by_default);
1168        assert_eq!(m.provides.as_deref(), Some("spreadsheets"));
1169        let m = parse_user(json!({"id": "a", "name": "x"})).unwrap();
1170        assert!(m.on_by_default && m.provides.is_none());
1171    }
1172
1173    #[test]
1174    fn views_at_render_sites() {
1175        let m = parse_user(json!({"id": "a", "name": "Todo", "backend": "b.py",
1176            "views": [{"site": "pane", "id": "list", "title": "To do", "icon": "list"}, {"site": "status"}]}))
1177        .unwrap();
1178        assert_eq!(m.views[0], ManifestView { id: "list".into(), site: "pane".into(), title: "To do".into(), icon: "list".into(), html: String::new() });
1179        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");
1180        let cases = [
1181            (
1182                json!({"id": "a", "name": "x", "views": [{"site": "pane"}]}),
1183                "byob-plugin.json: views are drawn by the plugin's backend: add \"backend\": \"backend.py\" (or give the view an \"html\" file)",
1184            ),
1185            (
1186                json!({"id": "a", "name": "x", "views": [{"site": "status", "html": "ui/x.html"}]}),
1187                "byob-plugin.json: views[0]: a web view (\"html\") goes in the pane or on a card",
1188            ),
1189            (
1190                json!({"id": "a", "name": "x", "views": [{"site": "pane", "html": "../x.html"}]}),
1191                "byob-plugin.json: views[0].html must be a file inside the plugin folder, like \"ui/index.html\"",
1192            ),
1193            (
1194                json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "sidebar"}]}),
1195                "byob-plugin.json: views[0].site must be one of pane, settings, status, card, artifact",
1196            ),
1197            (
1198                json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "pane", "id": "My View"}]}),
1199                "byob-plugin.json: views[0].id must be lowercase letters, digits, _ or -, like \"todo\"",
1200            ),
1201            (
1202                json!({"id": "a", "name": "x", "backend": "b.py", "views": [{"site": "pane"}, {"site": "pane"}]}),
1203                "byob-plugin.json: views[1].id \"pane\" is used twice",
1204            ),
1205        ];
1206        for (raw, want) in cases {
1207            assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
1208        }
1209        // A web view needs no backend; `web:<file>` renderers name a page of the plugin.
1210        let m = parse_user(json!({"id": "a", "name": "x", "views": [{"site": "pane", "id": "p", "html": "ui/index.html"}],
1211            "renderers": [{"type": "text/csv", "renderer": "web:ui/csv.html"}]}))
1212        .unwrap();
1213        assert_eq!((m.views[0].html.as_str(), m.renderers[0].renderer.as_str()), ("ui/index.html", "web:ui/csv.html"));
1214        assert!(parse_user(json!({"id": "a", "name": "x", "renderers": [{"type": "text/csv", "renderer": "web:/etc/x.html"}]})).is_err());
1215    }
1216
1217    #[test]
1218    fn native_bindings() {
1219        // Any plugin may name in-tree parts (a fork of a bundled plugin keeps them); the
1220        // engine resolves the ids and reports unknown ones as problems.
1221        let raw = json!({"id": "code", "name": "Code", "locked": true,
1222            "tools": [{"native": "run_python"}, {"native": "install_packages", "optional": true}],
1223            "artifact_types": [{"type": "text/html", "native": "html_app", "guidance": "guidance.md"},
1224                               {"type": "Text/CSV", "suffixes": [".CSV"], "label": "table", "pick": "a table → .csv"}],
1225            "renderers": [{"type": "text/html", "renderer": "web"}, {"type": "image/*", "renderer": "native:image"}],
1226            "system_prompt": {"native": "artifacts"}});
1227        let m = parse_user(raw).unwrap();
1228        assert_eq!(m.tools[0].name, "run_python");
1229        assert_eq!(m.tools[0].kind, ToolKind::Native("run_python".into()));
1230        assert!(!m.tools[0].optional && m.tools[1].optional && m.locked);
1231        assert_eq!(m.artifact_types[0].native.as_deref(), Some("html_app"));
1232        assert_eq!(m.artifact_types[0].guidance.as_deref(), Some("guidance.md"));
1233        assert_eq!((m.artifact_types[1].content_type.as_str(), m.artifact_types[1].suffixes.clone()), ("text/csv", Some(vec![".csv".to_string()])));
1234        assert_eq!(m.renderers[1], ManifestRenderer { content_type: "image/*".into(), renderer: "native:image".into() });
1235        assert_eq!(m.system_prompt, Some(PromptSource::Native("artifacts".into())));
1236        let m = parse_user(json!({"id": "a", "name": "x", "content_types": [{"type": "text/x", "native": "text"}], "system_prompt": "prompt.md"})).unwrap();
1237        assert_eq!(m.artifact_types[0].native.as_deref(), Some("text"));
1238        assert_eq!(m.system_prompt, Some(PromptSource::File("prompt.md".into())));
1239    }
1240
1241    #[test]
1242    fn server_configs() {
1243        let m = parse_user(json!({"id": "a", "name": "x", "mcpServers": {
1244            "mem": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"], "env": {"K": "${API_KEY}"}},
1245            "lin": {"url": "https://mcp.linear.app/mcp", "headers": {"Authorization": "Bearer ${API_KEY}"}, "oauth": {"clientId": "c"}},
1246            "old": {"url": "https://example.com/sse", "type": "sse"},
1247        }}))
1248        .unwrap();
1249        assert!(m.mcp_servers["mem"].is_local());
1250        assert!(!m.mcp_servers["lin"].is_local());
1251        assert!(matches!(&m.mcp_servers["old"], McpServerConfig::Url { sse: true, .. }));
1252        let vals = BTreeMap::from([("API_KEY".to_string(), "abc".to_string())]);
1253        match m.mcp_servers["lin"].with_settings(&vals) {
1254            McpServerConfig::Url { headers, oauth, .. } => {
1255                assert_eq!(headers["Authorization"], "Bearer abc");
1256                assert_eq!(oauth.map(|o| o.client_id).as_deref(), Some("c"));
1257            }
1258            other => panic!("{other:?}"),
1259        }
1260    }
1261
1262    #[test]
1263    fn placeholders() {
1264        let vals = BTreeMap::from([("A".to_string(), "1".to_string())]);
1265        assert_eq!(fill_placeholders("${A}-${B}-${A", &vals), "1-${B}-${A");
1266        assert_eq!(fill_placeholders("ünï${A}cødé", &vals), "ünï1cødé");
1267    }
1268
1269    #[test]
1270    fn inside_paths() {
1271        assert!(path_inside("tools/x.py") && path_inside("./a/../b.py"));
1272        assert!(!path_inside("../x") && !path_inside("a/../../x") && !path_inside("/x") && !path_inside("C:\\x") && !path_inside("\\x"));
1273    }
1274
1275    #[test]
1276    fn hooks_and_environments() {
1277        let parse = |extra: serde_json::Value| {
1278            let mut m = serde_json::json!({"id": "p", "name": "P"});
1279            for (k, v) in extra.as_object().unwrap() {
1280                m[k] = v.clone();
1281            }
1282            parse_manifest(&m, ParseOptions::default())
1283        };
1284        let m = parse(serde_json::json!({"backend": "b.py", "hooks": [
1285            {"event": "before_tool_call", "priority": -5, "tools": ["delete_file"], "fail": "closed", "timeout_ms": 500},
1286            {"event": "before_request", "native": "compaction"}
1287        ]}))
1288        .unwrap();
1289        assert_eq!(
1290            m.hooks[0],
1291            ManifestHook {
1292                event: "before_tool_call".into(),
1293                priority: -5,
1294                native: None,
1295                timeout_ms: 500,
1296                fail_closed: true,
1297                tools: vec!["delete_file".into()]
1298            }
1299        );
1300        assert_eq!((m.hooks[1].priority, m.hooks[1].timeout_ms, m.hooks[1].fail_closed), (DEFAULT_HOOK_PRIORITY, HOOK_TIMEOUT_MS, false));
1301        let err = |v| parse(v).unwrap_err().message;
1302        assert!(err(serde_json::json!({"hooks": [{"event": "before_lunch", "native": "x"}]})).contains("event must be one of"));
1303        assert!(err(serde_json::json!({"hooks": [{"event": "on_turn_end"}]})).contains("add \"backend\""));
1304        assert!(err(serde_json::json!({"hooks": [{"event": "before_prompt", "native": "x", "tools": ["a"]}]})).contains("tools only applies"));
1305        assert!(err(serde_json::json!({"backend": "b.py", "hooks": [{"event": "on_turn_end", "timeout_ms": 0}]})).contains("timeout_ms"));
1306        assert!(err(serde_json::json!({"backend": "b.py", "hooks": [{"event": "on_turn_end", "fail": "maybe"}]})).contains("\"open\" or \"closed\""));
1307        let m = parse(serde_json::json!({"environments": [
1308            {"native": "nix"},
1309            {"id": "conda", "detect": ["environment.yml"], "command": "python3", "args": ["env.py"]}
1310        ]}))
1311        .unwrap();
1312        assert_eq!((m.environments[0].id.as_str(), m.environments[0].native.as_deref()), ("nix", Some("nix")));
1313        assert_eq!((m.environments[1].label.as_str(), m.environments[1].command.as_deref()), ("conda environment", Some("python3")));
1314        assert!(err(serde_json::json!({"environments": [{"id": "x", "detect": ["a"]}]})).contains("needs \"native\""));
1315        assert!(err(serde_json::json!({"environments": [{"id": "x", "detect": ["../a"], "command": "c"}]})).contains("inside the workspace"));
1316    }
1317}