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