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