Skip to main content

eclipse_core/
plugins.rs

1//! Plugins: how the agent is extended without editing it.
2//!
3//! A plugin is a **directory** named after the plugin, containing `plugin.toml`. Nothing
4//! is compiled, loaded as a shared library or interpreted in-process: a plugin declares
5//! its tools, prompt fragments, provider profiles and hooks in that one manifest, and the
6//! only thing that ever executes is a process the manifest names. That keeps the agent a
7//! single static binary, keeps a panic in a plugin out of the agent, and makes a plugin
8//! reviewable by reading two files.
9//!
10//! What a plugin can add:
11//!
12//! | Section | Adds |
13//! |---------|------|
14//! | `[[tool]]` | a model-callable tool: a JSON Schema for its arguments plus a command to run |
15//! | `[[prompt]]` | text appended to the system prompt (inline or from a file) |
16//! | `[[provider_profile]]` | an OpenAI-compatible wire profile, overriding a built-in of the same name |
17//! | `[[hook]]` | `before_tool` (may refuse a tool call) or `after_tool` (may rewrite its output) |
18//! | `[[mcp]]` | every tool an MCP server offers, from one stdio JSON-RPC process (see [`crate::mcp`]) |
19//!
20//! What it deliberately cannot do: replace a built-in tool without saying `override = true`
21//! on that tool, and run without being listed in `[plugins] enabled`. An MCP server is declared
22//! once per server in `[[mcp]]` and contributes all of its tools from there (see [`crate::mcp`]);
23//! `kind = "mcp"` on a single `[[tool]]` is refused with a pointer to it.
24//!
25//! See `docs/USER.md` for the file format and `docs/TECHNICAL.md` for the execution and
26//! trust model.
27
28use crate::config::Policy;
29use crate::mcp;
30use crate::provider::ProviderProfile;
31use crate::tools::{read_capped, Tool, ToolError, ToolOutcome, ToolSource};
32use async_trait::async_trait;
33use serde::Deserialize;
34use serde_json::{json, Value};
35use std::collections::BTreeMap;
36use std::path::{Path, PathBuf};
37use std::sync::{Arc, Mutex};
38use std::time::Duration;
39
40/// Manifest API version this build speaks. A plugin asking for a newer one is not loaded.
41pub const API: u32 = 1;
42
43/// Manifest file name inside a plugin directory.
44pub const MANIFEST: &str = "plugin.toml";
45
46/// How much of the call payload may be duplicated into `ECLIPSE_ARGS`. One environment string is
47/// capped at `MAX_ARG_STRLEN` (131072 bytes, name and `=` included) and `spawn` fails with `E2BIG`
48/// past it; half the ceiling leaves room for the name and for the rest of the environment.
49const ARGS_ENV_MAX: usize = 64 * 1024;
50
51/// Default timeout for a plugin tool or hook; a manifest may lower it.
52pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// Hard ceiling: no manifest may make the agent wait longer than this.
55pub const MAX_TIMEOUT: Duration = Duration::from_secs(600);
56
57/// How a plugin tool gets its arguments, and what runs it.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
59#[serde(rename_all = "lowercase")]
60pub enum Kind {
61    /// Run `command` and return its stdout.
62    #[default]
63    Command,
64    /// Reserved: an MCP stdio server. Parsed, reported as unsupported.
65    Mcp,
66}
67
68/// Working directory for a plugin command, and for an MCP server `config.toml` declares — which
69/// is why it serializes: the spec carrying it round-trips through `config show` (`#352`).
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, serde::Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum Cwd {
73    /// The configured workspace (default): a plugin tool sees what the agent sees.
74    #[default]
75    Workspace,
76    /// The plugin's own directory, for plugins that ship scripts.
77    Plugin,
78}
79
80/// Where a tool's JSON Schema comes from.
81#[derive(Debug, Clone, Deserialize)]
82#[serde(untagged)]
83pub enum Parameters {
84    /// A path relative to the plugin directory, e.g. `tools/git_status.json`.
85    File(String),
86    /// An inline TOML table (fine for small schemas).
87    Inline(Box<toml::Value>),
88}
89
90#[derive(Debug, Clone, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct ToolDef {
93    pub name: String,
94    pub description: String,
95    #[serde(default)]
96    pub parameters: Option<Parameters>,
97    #[serde(default)]
98    pub kind: Kind,
99    /// argv, run without a shell. `sh -c '...'` is allowed but then the quoting is yours.
100    #[serde(default)]
101    pub command: Vec<String>,
102    #[serde(default)]
103    pub cwd: Cwd,
104    #[serde(default)]
105    pub timeout_secs: Option<u64>,
106    /// Default `ask`. `allow` means this tool runs without a prompt.
107    #[serde(default)]
108    pub policy: Option<Policy>,
109    /// Names copied from the agent's environment into the command's (nothing else is).
110    #[serde(default)]
111    pub env: Vec<String>,
112    /// Replace the tool of the same name (built-in or from an earlier plugin). Required.
113    #[serde(default, rename = "override")]
114    pub override_builtin: bool,
115}
116
117#[derive(Debug, Clone, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct PromptDef {
120    #[serde(default)]
121    pub text: Option<String>,
122    /// A file relative to the plugin directory; read at load time.
123    #[serde(default)]
124    pub file: Option<String>,
125}
126
127#[derive(Debug, Clone, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct ProfileDef {
130    pub name: String,
131    /// Send `tool_choice: "auto"` with tool calls.
132    #[serde(default = "yes")]
133    pub tool_choice: bool,
134    /// Ask the server to report token usage on the final stream chunk.
135    #[serde(default = "yes")]
136    pub stream_usage: bool,
137    /// Field name for the reply cap (`max_tokens` or `max_completion_tokens`).
138    #[serde(default)]
139    pub max_tokens_field: Option<String>,
140    /// Advertise tools at all (some local backends break on `tools`).
141    #[serde(default = "yes")]
142    pub supports_tools: bool,
143    /// Merged into every request body; anything here wins, so a backend quirk needs no
144    /// code change (e.g. `chat_template_kwargs` or `reasoning_effort`).
145    #[serde(default)]
146    pub body: Option<toml::Value>,
147    /// How this backend takes a reasoning effort — the field, the levels it has, what turns it off
148    /// and any vendor renames. Declared here and not in code: a new backend quirk is a manifest
149    /// edit, and a model that differs is one entry in `models` below.
150    #[serde(default)]
151    pub reasoning: Option<crate::reasoning::Policy>,
152    /// Per-model overrides, keyed by the model id this profile serves.
153    #[serde(default)]
154    pub models: BTreeMap<String, ModelReasoningDef>,
155    /// Standing request policy: context size, reply cap, temperature, formats it rejects, aux model.
156    #[serde(default)]
157    pub request: Option<RequestDef>,
158    /// Can this route see an image? Reported, not inferred: nothing here sends one yet, but the
159    /// answer belongs beside the profile rather than in somebody's memory.
160    #[serde(default)]
161    pub vision: Option<bool>,
162}
163
164/// `[provider_profile.request]`: what this backend wants on every request, whatever the turn asks.
165#[derive(Debug, Clone, Deserialize, Default)]
166#[serde(deny_unknown_fields)]
167pub struct RequestDef {
168    /// Context window to ask for.
169    #[serde(default)]
170    pub num_ctx: Option<u32>,
171    /// Where it goes: `options.num_ctx` (Ollama native), `n_ctx` (llama.cpp), else that default.
172    #[serde(default)]
173    pub num_ctx_field: Option<String>,
174    /// Hard ceiling on reply tokens.
175    #[serde(default)]
176    pub max_output: Option<u32>,
177    /// `"omit"`, `{ fixed = 0.2 }`, or absent to send what the config says.
178    #[serde(default)]
179    pub temperature: Option<TemperatureDef>,
180    /// `response_format` types this route rejects; one is dropped instead of being sent.
181    #[serde(default)]
182    pub reject_response_formats: Vec<String>,
183    /// The cheap model this provider publishes for titles, compaction and judging.
184    #[serde(default)]
185    pub aux_model: Option<String>,
186    /// Per-model limits.
187    #[serde(default)]
188    pub models: BTreeMap<String, LimitDef>,
189}
190
191/// `temperature = "omit"` or `temperature = { fixed = 0.2 }`.
192#[derive(Debug, Clone, Deserialize)]
193#[serde(untagged)]
194pub enum TemperatureDef {
195    Mode(String),
196    Fixed { fixed: f32 },
197}
198
199/// One model's limits.
200#[derive(Debug, Clone, Deserialize, Default)]
201#[serde(deny_unknown_fields)]
202pub struct LimitDef {
203    #[serde(default)]
204    pub num_ctx: Option<u32>,
205    #[serde(default)]
206    pub max_output: Option<u32>,
207}
208
209impl From<&RequestDef> for crate::provider::RequestPolicy {
210    fn from(def: &RequestDef) -> Self {
211        Self {
212            num_ctx: def.num_ctx,
213            num_ctx_field: def.num_ctx_field.clone(),
214            max_output: def.max_output,
215            temperature: def.temperature.as_ref().map(|t| match t {
216                TemperatureDef::Fixed { fixed } => crate::provider::Temperature::Fixed(*fixed),
217                TemperatureDef::Mode(mode) if mode.eq_ignore_ascii_case("omit") => {
218                    crate::provider::Temperature::Omit
219                }
220                TemperatureDef::Mode(_) => crate::provider::Temperature::Default,
221            }),
222            reject_response_formats: def.reject_response_formats.clone(),
223            aux_model: def.aux_model.clone(),
224            models: def
225                .models
226                .iter()
227                .map(|(id, limit)| {
228                    (
229                        id.clone(),
230                        crate::provider::ModelLimits {
231                            num_ctx: limit.num_ctx,
232                            max_output: limit.max_output,
233                        },
234                    )
235                })
236                .collect(),
237        }
238    }
239}
240
241/// A model's own reasoning entry: `reasoning = false` (it does not think), or a policy of its own.
242#[derive(Debug, Clone, Deserialize)]
243#[serde(untagged)]
244pub enum ModelReasoningDef {
245    Toggle(bool),
246    Policy(crate::reasoning::Policy),
247}
248
249fn yes() -> bool {
250    true
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
254#[serde(rename_all = "snake_case")]
255pub enum Event {
256    BeforeTool,
257    AfterTool,
258}
259
260#[derive(Debug, Clone, Deserialize)]
261#[serde(deny_unknown_fields)]
262pub struct HookDef {
263    pub event: Event,
264    /// Tool name to match; `*` or absent means every tool.
265    #[serde(default)]
266    pub tool: Option<String>,
267    #[serde(default)]
268    pub command: Vec<String>,
269    #[serde(default)]
270    pub timeout_secs: Option<u64>,
271    #[serde(default)]
272    pub cwd: Cwd,
273    #[serde(default)]
274    pub env: Vec<String>,
275}
276
277#[derive(Debug, Clone, Deserialize)]
278#[serde(deny_unknown_fields)]
279pub struct Manifest {
280    pub name: String,
281    #[serde(default)]
282    pub version: String,
283    #[serde(default)]
284    pub description: String,
285    /// Manifest API version; defaults to the current one for hand-written plugins.
286    #[serde(default = "current_api")]
287    pub api: u32,
288    #[serde(default, rename = "tool")]
289    pub tools: Vec<ToolDef>,
290    #[serde(default, rename = "prompt")]
291    pub prompts: Vec<PromptDef>,
292    #[serde(default, rename = "provider_profile")]
293    pub provider_profiles: Vec<ProfileDef>,
294    #[serde(default, rename = "hook")]
295    pub hooks: Vec<HookDef>,
296    /// MCP servers this plugin adds tools from. Each is one long-lived process (see
297    /// [`crate::mcp`]); unlike `[[tool]]`, one entry can contribute many tools.
298    #[serde(default, rename = "mcp")]
299    pub mcp: Vec<crate::mcp::Spec>,
300}
301
302fn current_api() -> u32 {
303    API
304}
305
306/// A plugin that loaded: its manifest plus where it lives.
307#[derive(Debug, Clone)]
308pub struct Plugin {
309    pub name: String,
310    pub version: String,
311    pub description: String,
312    /// The plugin's directory; also its identity for `[plugins] enabled`.
313    pub dir: PathBuf,
314    pub manifest: Manifest,
315    /// Whether `[plugins] enabled` lists it (`#419`). A manifest that declares nothing but
316    /// provider profiles is loaded when it is *not* enabled, so its wire settings exist — but it is
317    /// not enabled, and nothing it ships on disk (a `skills/` directory, say) may be exposed. The
318    /// two used to be the same list; they are not the same question.
319    pub enabled: bool,
320}
321
322/// What [`Plugins::tools`] produces: tools to register, and the reasons some were rejected.
323/// One tool a plugin offers, with the policy it asked for and the plugin to blame or credit.
324#[derive(Clone)]
325pub struct PluginTool {
326    pub tool: Arc<dyn Tool>,
327    pub policy: Policy,
328    /// Where the tool came from, as `tools list` prints it: `plugin:<name>` for a plugin's own
329    /// tool, `plugin:mcp:<server>` for one an MCP server listed, `config:mcp:<server>` for a
330    /// server `config.toml` declares (`#352`).
331    pub source: ToolSource,
332}
333
334pub type ToolsAndProblems = (Vec<PluginTool>, Vec<String>);
335
336/// One `[[mcp]]` server as it will be started, with where it resolves from and what its tools
337/// will be reported as (`#352`). Built by [`Plugins::servers`] from both providers.
338struct ServerRef<'a> {
339    spec: &'a mcp::Spec,
340    /// The plugin's directory, or the workspace for a server `config.toml` declares.
341    base: PathBuf,
342    /// `plugin `<name>`` or `config` — what a message calls whoever declared it.
343    owner: String,
344    source: ToolSource,
345}
346
347/// What `mcp list` prints for one server: the declaration, and what it actually did.
348#[derive(Debug, Clone)]
349pub struct McpServerState {
350    pub name: String,
351    pub source: ToolSource,
352    pub owner: String,
353    /// `command arg arg`, or `http <url>` — the one line a reader needs to recognise the entry.
354    pub command: String,
355    /// The entry's own fields, for a surface that *edits* rather than reads it (`#517`): a form
356    /// that opens with what the file says cannot be built from the display line above.
357    pub transport: crate::mcp::Transport,
358    pub program: String,
359    pub args: Vec<String>,
360    pub url: Option<String>,
361    pub policy: Policy,
362    pub prefix: String,
363    pub timeout_secs: u64,
364    pub disabled: bool,
365    /// Tools the server listed. Zero with an `error` is a server that did not start; zero without
366    /// one is a server that started and offers nothing.
367    pub tools: usize,
368    pub error: Option<String>,
369    /// The variable `token_env` names, when the entry asks for a bearer token. A name, never a
370    /// value; a listing prints it beside the word for whether it resolves (`#517`).
371    pub token_env: Option<String>,
372    /// Whether that variable resolves now — `none`, `env`, `.env` or `unset` — so a server that
373    /// cannot authenticate says so *where it is listed*, not only when somebody presses *test*.
374    pub token: crate::mcp::TokenSource,
375    /// What the server answered `initialize` with: the protocol version it speaks, and its own
376    /// name and version. `None` when it never got that far.
377    pub protocol: Option<String>,
378    pub server_name: Option<String>,
379    pub server_version: Option<String>,
380}
381
382/// `command arg arg` for a stdio server, `http <url>` for one reached over HTTP — the shape of the
383/// entry in one line, for `mcp list`.
384fn describe_command(spec: &mcp::Spec) -> String {
385    match spec.transport {
386        crate::mcp::Transport::Stdio => {
387            let mut out = spec.command.clone();
388            for arg in &spec.args {
389                out.push(' ');
390                out.push_str(arg);
391            }
392            out
393        }
394        crate::mcp::Transport::Http => {
395            // The same scrubbing `config show` gives an endpoint (`#539`): this line is what `mcp
396            // list` and the dashboard show, and `https://user:pw@host/mcp` is exactly as much of a
397            // secret here as it is in a printout.
398            let url = spec.url.as_deref().unwrap_or("(no url declared)");
399            format!(
400                "http {}",
401                crate::config::redact_url(url).unwrap_or_else(|| url.to_string())
402            )
403        }
404    }
405}
406
407/// A started MCP server and the tools it listed, or why it would not start. Cached so the two
408/// `tools()` calls a CLI process makes share one process; the reason is cached too, so a broken
409/// manifest is reported once rather than retried behind every command.
410type StartedServer = Result<(Arc<crate::mcp::Server>, Vec<crate::mcp::RemoteTool>), String>;
411
412/// Everything that loaded, and everything that did not (with the reason).
413#[derive(Debug, Clone, Default)]
414pub struct Plugins {
415    pub plugins: Vec<Plugin>,
416    /// Why a plugin or part of one was rejected. Never fatal: a broken plugin must not lock
417    /// you out of your own agent.
418    pub problems: Vec<String>,
419    /// The scripts directory handed to every plugin process as `ECLIPSE_SCRIPTS_DIR`; `None`
420    /// leaves the variable unset.
421    scripts_dir: Option<PathBuf>,
422    /// The ceiling for a `[[mcp]]` entry that states no `timeout_secs`, or `None` when MCP is off
423    /// for this process (`--no-mcp`). Off means no server is ever started, not merely hidden.
424    mcp: Option<Duration>,
425    /// Servers `config.toml` declares under `[[mcp]]` (`#352`). A second provider for the same
426    /// thing a manifest declares, merged by [`Plugins::servers`]; the config wins a name clash.
427    config_mcp: Vec<mcp::Spec>,
428    /// The `.env` values that config loaded, so a `token_env` naming a variable stored there
429    /// resolves (`#516`). Carried beside `config_mcp` because it is only ever a server from
430    /// `config.toml` that can point at that file.
431    secrets: crate::mcp::Secrets,
432    /// MCP servers already started, by `plugin/server`. `tools()` is called more than once in a
433    /// process (the startup warnings ask, then the registry asks), and starting a second copy of a
434    /// server would double its processes and its memory for nothing.
435    servers: Arc<Mutex<BTreeMap<String, StartedServer>>>,
436}
437
438impl Plugins {
439    /// These plugins' processes will be told where the agent's scripts live. Set after
440    /// [`load`], before [`Self::tools`] and [`Self::hooks`] copy it into what they build.
441    pub fn with_scripts_dir(mut self, dir: Option<PathBuf>) -> Self {
442        self.scripts_dir = dir;
443        self
444    }
445
446    /// Say how MCP servers should be started: a default ceiling, or none at all (`--no-mcp`).
447    /// Left unset, a server that states no timeout gets [`DEFAULT_TIMEOUT`].
448    pub fn with_mcp(mut self, settings: McpSettings) -> Self {
449        self.mcp = settings.0;
450        self
451    }
452
453    /// Add the servers `config.toml` declares under `[[mcp]]` (`#352`), and the `.env` values their
454    /// `token_env` variables resolve against (`#516`). Call after [`load`]: the manifests are read
455    /// from disk, the config is already in memory.
456    ///
457    /// One call rather than two, because a server handed its spec without the values is exactly the
458    /// bug `#516` was: the entry says which variable, and only the config says whether it resolves.
459    pub fn with_config_mcp(mut self, cfg: &crate::config::Config) -> Self {
460        self.config_mcp = cfg.mcp.clone();
461        self.secrets = cfg.dotenv.values.clone();
462        self
463    }
464
465    pub fn get(&self, name: &str) -> Option<&Plugin> {
466        self.plugins.iter().find(|p| p.name == name)
467    }
468
469    /// Every prompt fragment, in load order (earlier directories first, then manifest
470    /// order), so a profile plugin's wording can precede a shared one.
471    pub fn prompts(&self) -> Vec<String> {
472        self.plugins
473            .iter()
474            .flat_map(|p| p.manifest.prompts.iter())
475            .filter_map(|d| d.text.clone())
476            .collect()
477    }
478
479    /// Provider profiles declared by plugins, in load order: a later one with the same name
480    /// replaces an earlier one, and either replaces the built-in.
481    pub fn provider_profiles(&self) -> Vec<ProviderProfile> {
482        let mut out: Vec<ProviderProfile> = Vec::new();
483        for plugin in &self.plugins {
484            for def in &plugin.manifest.provider_profiles {
485                let profile = profile_from_def(def);
486                match out.iter_mut().find(|p| p.name == profile.name) {
487                    Some(slot) => *slot = profile,
488                    None => out.push(profile),
489                }
490            }
491        }
492        out
493    }
494
495    /// Tools to register, each with the policy it should get and the plugin that offers it,
496    /// so the registry can say where a tool came from. `builtin` is the set of names the
497    /// registry already has. Rejections come back as problems.
498    pub fn tools(
499        &self,
500        workspace: &Path,
501        max_bytes: usize,
502        builtin: &[String],
503    ) -> ToolsAndProblems {
504        let mut out: Vec<PluginTool> = Vec::new();
505        let mut problems = Vec::new();
506        for plugin in &self.plugins {
507            for def in &plugin.manifest.tools {
508                let mut problem = |why: String| {
509                    problems.push(format!(
510                        "plugin `{}`: tool `{}`: {why}",
511                        plugin.name, def.name
512                    ));
513                };
514                if def.kind == Kind::Mcp {
515                    // A server offers many tools, so it is declared once per server (`[[mcp]]`) and
516                    // not once per tool. Saying which is the whole of this message.
517                    problem(
518                        concat!(
519                            "kind = \"mcp\" belongs on a `[[mcp]]` section, not on one tool: ",
520                            "an MCP server contributes all of its tools from a single entry"
521                        )
522                        .to_string(),
523                    );
524                    continue;
525                }
526                if def.command.is_empty() {
527                    problem("no `command` given".into());
528                    continue;
529                }
530                let taken = builtin.iter().any(|b| b == &def.name)
531                    || out.iter().any(|t| t.tool.name() == def.name);
532                if taken && !def.override_builtin {
533                    problem(
534                        "collides with a tool that already exists; set `override = true` on it \
535                         to replace it"
536                            .into(),
537                    );
538                    continue;
539                }
540                let parameters = match &def.parameters {
541                    None => json!({"type": "object", "properties": {}}),
542                    Some(Parameters::Inline(v)) => match serde_json::to_value(v) {
543                        Ok(v) => v,
544                        Err(e) => {
545                            problem(format!("inline parameters are not valid JSON: {e}"));
546                            continue;
547                        }
548                    },
549                    Some(Parameters::File(rel)) => {
550                        let path = match manifest_path(&plugin.dir, rel) {
551                            Ok(path) => path,
552                            Err(why) => {
553                                problem(why);
554                                continue;
555                            }
556                        };
557                        match read_data_file(&path) {
558                            Ok(text) => match serde_json::from_str::<Value>(&text) {
559                                Ok(v) => v,
560                                Err(e) => {
561                                    problem(format!("{}: {e}", path.display()));
562                                    continue;
563                                }
564                            },
565                            Err(e) => {
566                                problem(format!("{}: {e}", path.display()));
567                                continue;
568                            }
569                        }
570                    }
571                };
572                let policy = def.policy.unwrap_or(Policy::Ask);
573                let tool = CommandTool {
574                    name: def.name.clone(),
575                    description: def.description.clone(),
576                    parameters,
577                    command: def.command.clone(),
578                    plugin: plugin.name.clone(),
579                    plugin_dir: plugin.dir.clone(),
580                    workspace: workspace.to_path_buf(),
581                    cwd: def.cwd,
582                    timeout: clamp_timeout(def.timeout_secs),
583                    env: def.env.clone(),
584                    max_bytes,
585                    scripts_dir: self.scripts_dir.clone(),
586                };
587                out.push(PluginTool {
588                    tool: Arc::new(tool) as Arc<dyn Tool>,
589                    policy,
590                    source: ToolSource::Plugin(plugin.name.clone()),
591                });
592            }
593        }
594        // Servers are started once for the whole load, not per plugin: a `[[mcp]]` in
595        // `config.toml` has no plugin to belong to (`#352`).
596        self.mcp_tools(workspace, builtin, &mut out, &mut problems);
597        (out, problems)
598    }
599
600    /// Every `[[mcp]]` server this process knows about, in the order they are started: the
601    /// manifests' servers, then the ones `config.toml` declares.
602    ///
603    /// **A name clash is the config's** (`#352`): a `[[mcp]]` in `config.toml` is somebody's
604    /// decision about *this* machine, and a manifest is a file a plugin shipped, so the config
605    /// wins and the shadowed manifest entry is reported rather than silently started as well —
606    /// two servers answering to one name would collide on every tool name anyway.
607    fn servers(&self, workspace: &Path) -> (Vec<ServerRef<'_>>, Vec<String>) {
608        let mut problems = Vec::new();
609        let mut out: Vec<ServerRef> = Vec::new();
610        for plugin in &self.plugins {
611            for spec in &plugin.manifest.mcp {
612                out.push(ServerRef {
613                    spec,
614                    base: plugin.dir.clone(),
615                    owner: format!("plugin `{}`", plugin.name),
616                    source: ToolSource::Plugin(format!("mcp:{}", spec.name)),
617                });
618            }
619        }
620        for spec in &self.config_mcp {
621            // Drop the manifest entry this shadows, and say so: a server that was configured twice
622            // and started once is exactly the confusion this verb exists to remove.
623            if let Some(pos) = out.iter().position(|s| s.spec.name == spec.name) {
624                let shadowed = out.remove(pos);
625                problems.push(format!(
626                    "{}: mcp `{}` is also declared in config.toml, which wins; the manifest entry is ignored",
627                    shadowed.owner, spec.name
628                ));
629            }
630            out.push(ServerRef {
631                spec,
632                base: workspace.to_path_buf(),
633                owner: "config".to_string(),
634                source: ToolSource::Config(format!("mcp:{}", spec.name)),
635            });
636        }
637        (out, problems)
638    }
639
640    /// The servers as `mcp list` reports them, with the tool counts already resolved. Cheap to
641    /// call: the servers are cached per process, so listing does not start a second copy.
642    pub fn mcp_report(&self, workspace: &Path) -> (Vec<McpServerState>, Vec<String>) {
643        let (servers, shadowed) = self.servers(workspace);
644        // A shadowed manifest entry is the only problem listing can find: a server that will not
645        // start is reported per row (with the reason), not thrown away into a list.
646        let problems = shadowed;
647        let mut out = Vec::new();
648        for server in servers {
649            // A disabled entry is not started — by the agent or by `mcp list`. Describing a server
650            // is not a reason to run it, and a server that would fail is a `failed` row that says
651            // nothing about the entry being switched off.
652            let started = if server.spec.disabled {
653                None
654            } else {
655                Some(self.start(server.spec, &server.base, workspace))
656            };
657            let (tools, error, handshake) = match &started {
658                None => (0, None, None),
659                Some(Ok((session, tools))) => (tools.len(), None, session.handshake()),
660                Some(Err(why)) => (0, Some(why.clone()), None),
661            };
662            let field = |key: &str| {
663                handshake
664                    .as_ref()
665                    .and_then(|h| h.get(key))
666                    .and_then(|v| v.as_str())
667                    .map(str::to_string)
668            };
669            // `serverInfo` is `{ name, version }`; both are optional in practice because not every
670            // server fills them in, and a missing one is not an error.
671            let info = |key: &str| {
672                handshake
673                    .as_ref()
674                    .and_then(|h| h.get("serverInfo"))
675                    .and_then(|i| i.get(key))
676                    .and_then(|v| v.as_str())
677                    .map(str::to_string)
678            };
679            out.push(McpServerState {
680                name: server.spec.name.clone(),
681                source: server.source,
682                owner: server.owner,
683                command: describe_command(server.spec),
684                transport: server.spec.transport,
685                program: server.spec.command.clone(),
686                args: server.spec.args.clone(),
687                url: server.spec.url.clone(),
688                policy: server.spec.policy,
689                prefix: server.spec.prefix.clone(),
690                timeout_secs: server
691                    .spec
692                    .timeout_secs
693                    .or_else(|| self.mcp.map(|d| d.as_secs()))
694                    .unwrap_or(0),
695                disabled: server.spec.disabled,
696                token_env: server.spec.token_env.clone(),
697                token: server.spec.token_source(&self.secrets),
698                tools,
699                error,
700                protocol: field("protocolVersion"),
701                server_name: info("name"),
702                server_version: info("version"),
703            });
704        }
705        (out, problems)
706    }
707
708    /// Register the tools of every `[[mcp]]` server. A server that will not start is one problem
709    /// and no tools: a broken plugin must not stop the agent from running.
710    fn mcp_tools(
711        &self,
712        workspace: &Path,
713        builtin: &[String],
714        out: &mut Vec<PluginTool>,
715        problems: &mut Vec<String>,
716    ) {
717        if self.mcp.is_none() {
718            return;
719        }
720        let (servers, shadowed) = self.servers(workspace);
721        problems.extend(shadowed);
722        for server in servers {
723            if server.spec.disabled {
724                continue;
725            }
726            // `#502`: the entry is checked once, here, for the transport it names *and* for the
727            // fields that belong to the other one. One place, so a manifest cannot be half-checked.
728            if let Err(why) = server.spec.validate() {
729                problems.push(format!(
730                    "{}: mcp `{}`: {why}",
731                    server.owner, server.spec.name
732                ));
733                continue;
734            }
735            let (session, tools) = match self.start(server.spec, &server.base, workspace) {
736                Ok(started) => started,
737                Err(why) => {
738                    problems.push(why);
739                    continue;
740                }
741            };
742            for remote in tools {
743                let tool = crate::mcp::McpTool::new(Arc::clone(&session), &remote);
744                let name = tool.name().to_string();
745                // `#373`: a name the alphabet or the length ceiling forced to change is said out
746                // loud. The model calls the sanitised name, and it looks nothing like the one the
747                // server published — silence here would send someone reading the server's docs
748                // looking for a tool the agent does not have.
749                let published = format!("{}{}", session.prefix(), remote.name);
750                if name != published {
751                    problems.push(format!(
752                        "{}: mcp `{}`: tool {:?} is called as `{}` (a name must be [A-Za-z0-9_-], at most {} characters)",
753                        server.owner,
754                        server.spec.name,
755                        remote.name,
756                        name.trim_start_matches(session.prefix()),
757                        crate::mcp::TOOL_NAME_MAX
758                    ));
759                }
760                // The same rule as a command tool: a name that is already taken is refused unless
761                // the manifest says to replace it. A server's `read_file` must not quietly become
762                // the agent's `read_file`.
763                let taken =
764                    builtin.iter().any(|b| b == &name) || out.iter().any(|t| t.tool.name() == name);
765                if taken && !session.override_builtin() {
766                    problems.push(format!(
767                        concat!(
768                            "{}: mcp `{}`: tool `{}` collides with a tool that ",
769                            "already exists; set `override = true` on the server entry to replace it"
770                        ),
771                        server.owner, server.spec.name, name
772                    ));
773                    continue;
774                }
775                let policy = session.policy_for(&remote.name);
776                out.push(PluginTool {
777                    tool: Arc::new(tool) as Arc<dyn Tool>,
778                    policy,
779                    source: server.source.clone(),
780                });
781            }
782        }
783    }
784
785    /// Start one server, or hand back why it would not start. Cached per process: `tools()` is
786    /// called more than once (the startup warnings ask, then the registry asks) and starting a
787    /// second copy would double its processes for nothing.
788    fn start(&self, spec: &mcp::Spec, base: &Path, workspace: &Path) -> StartedServer {
789        let Some(default_timeout) = self.mcp else {
790            return Err("MCP is off for this process (`--no-mcp`)".to_string());
791        };
792        let key = format!("{}:{}", base.display(), spec.name);
793        let mut cache = self.servers.lock().unwrap_or_else(|e| e.into_inner());
794        cache
795            .entry(key)
796            .or_insert_with(|| {
797                crate::mcp::Server::start(spec, base, workspace, default_timeout, &self.secrets)
798                    .map_err(|e| format!("mcp `{}`: {e}", spec.name))
799            })
800            .clone()
801    }
802
803    /// Hooks in load order: every plugin's `before_tool` hooks run before any tool.
804    pub fn hooks(&self) -> Vec<Arc<Hook>> {
805        self.plugins
806            .iter()
807            .flat_map(|p| {
808                p.manifest.hooks.iter().map(move |def| {
809                    Arc::new(Hook {
810                        event: def.event,
811                        tool: def.tool.clone(),
812                        command: def.command.clone(),
813                        timeout: clamp_timeout(def.timeout_secs),
814                        cwd: def.cwd,
815                        env: def.env.clone(),
816                        plugin_dir: p.dir.clone(),
817                        plugin: p.name.clone(),
818                        max_bytes: 64 * 1024,
819                        scripts_dir: self.scripts_dir.clone(),
820                    })
821                })
822            })
823            .collect()
824    }
825}
826
827/// One manifest entry as the profile the provider runs on. Public because the tests that check what
828/// the shipped manifests promise read them from `plugins/` and must go through the same conversion —
829/// a test that reimplements it would be testing itself.
830pub fn profile_from_def(def: &ProfileDef) -> ProviderProfile {
831    ProviderProfile {
832        name: def.name.clone(),
833        tool_choice: def.tool_choice,
834        stream_usage: def.stream_usage,
835        max_tokens_field: def.max_tokens_field.clone(),
836        supports_tools: def.supports_tools,
837        send_reasoning: false,
838        body: def
839            .body
840            .as_ref()
841            .and_then(|v| serde_json::to_value(v).ok())
842            .unwrap_or_else(|| serde_json::json!({})),
843        reasoning: def.reasoning.clone(),
844        request: def
845            .request
846            .as_ref()
847            .map(crate::provider::RequestPolicy::from)
848            .unwrap_or_default(),
849        vision: def.vision,
850        models: def
851            .models
852            .iter()
853            .map(|(id, entry)| {
854                let mapped = match entry {
855                    ModelReasoningDef::Toggle(on) => crate::provider::ModelReasoning::Toggle(*on),
856                    ModelReasoningDef::Policy(policy) => {
857                        crate::provider::ModelReasoning::Policy(policy.clone())
858                    }
859                };
860                (id.clone(), mapped)
861            })
862            .collect(),
863    }
864}
865
866pub(crate) fn clamp_timeout(secs: Option<u64>) -> Duration {
867    Duration::from_secs(secs.unwrap_or(DEFAULT_TIMEOUT.as_secs()))
868        .clamp(Duration::from_secs(1), MAX_TIMEOUT)
869}
870
871/// The ceiling for an MCP server that states no `timeout_secs` of its own. `[plugins]
872/// mcp_timeout_secs` is the machine-wide answer; the plugin default (and its clamp) applies when
873/// the config says nothing.
874pub fn mcp_timeout(cfg: &crate::config::Config) -> Duration {
875    clamp_timeout(cfg.plugins.mcp_timeout_secs)
876}
877
878/// How MCP servers are started in this process, when `[[mcp]]` entries do not say. `None` —
879/// `--no-mcp` — starts none of them at all: no process, no tools, and no problem entries for
880/// servers that would have failed anyway.
881#[derive(Debug, Clone, Copy)]
882pub struct McpSettings(pub Option<Duration>);
883
884impl McpSettings {
885    pub fn from_config(cfg: &crate::config::Config) -> Self {
886        Self(if cfg.no_mcp {
887            None
888        } else {
889            Some(mcp_timeout(cfg))
890        })
891    }
892}
893
894/// A manifest that declares provider profiles and nothing that *does* anything.
895///
896/// A profile is configuration — a wire shape and a reasoning vocabulary — and declares no tool,
897/// prompt, hook or server, so it cannot run, read or send anything on its own. The reason it
898/// loads without being listed is that a shipped profile nobody remembered to enable is a profile
899/// that silently does not exist, and the symptom is a `/reasoning` that says "no control on this
900/// backend" about a backend somebody already described.
901fn declares_only_profiles(manifest: &Manifest) -> bool {
902    !manifest.provider_profiles.is_empty()
903        && manifest.tools.is_empty()
904        && manifest.prompts.is_empty()
905        && manifest.hooks.is_empty()
906        && manifest.mcp.is_empty()
907}
908
909/// Discover and load plugins from `dirs`, in order: the first plugin with a given name wins
910/// (so a profile's copy shadows the shared one). Only names in `enabled` are considered, except a
911/// manifest that declares nothing but provider profiles (see [`declares_only_profiles`]).
912/// A missing manifest, a manifest that does not parse, a name that does not match its
913/// directory, or a newer `api` becomes a problem entry, never an error.
914pub fn load(dirs: &[PathBuf], enabled: &[String]) -> Plugins {
915    let mut out = Plugins {
916        // A server that says nothing gets the plugin default; a caller that wants another
917        // ceiling (or none) says so with `with_mcp`.
918        mcp: Some(DEFAULT_TIMEOUT),
919        ..Default::default()
920    };
921    let mut loaded: Vec<String> = Vec::new();
922    let mut failed: Vec<String> = Vec::new();
923    for dir in dirs {
924        let Ok(entries) = std::fs::read_dir(dir) else {
925            continue;
926        };
927        let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
928        paths.sort();
929        for path in paths {
930            if !path.join(MANIFEST).is_file() {
931                continue;
932            }
933            let dir_name = path
934                .file_name()
935                .map(|n| n.to_string_lossy().to_string())
936                .unwrap_or_default();
937            let listed = enabled.contains(&dir_name);
938            if loaded.contains(&dir_name) {
939                continue;
940            }
941            if !listed {
942                // Not enabled: it still loads when it is nothing but a wire profile, and a manifest
943                // that fails to parse here stays quiet — an unenabled plugin is not the user's
944                // problem until they enable it.
945                match read_manifest(&path, &dir_name) {
946                    Ok(mut plugin) if declares_only_profiles(&plugin.manifest) => {
947                        loaded.push(dir_name);
948                        // Loaded for its provider profiles, not enabled by the user: `#419`.
949                        plugin.enabled = false;
950                        out.plugins.push(plugin);
951                    }
952                    _ => continue,
953                }
954                continue;
955            }
956            match read_manifest(&path, &dir_name) {
957                Ok(plugin) => {
958                    loaded.push(dir_name);
959                    out.plugins.push(plugin);
960                }
961                Err(why) => {
962                    failed.push(dir_name);
963                    out.problems.push(why);
964                }
965            }
966        }
967    }
968    for name in enabled {
969        if !loaded.contains(name) && !failed.contains(name) {
970            out.problems.push(format!(
971                "plugin `{name}` is enabled but was not found in any plugin directory"
972            ));
973        }
974    }
975    // Prompt fragments may point at files; read them here so a missing file is a load-time
976    // problem rather than a quietly shorter prompt.
977    for plugin in &mut out.plugins {
978        let mut resolved = Vec::new();
979        let mut problems = Vec::new();
980        for def in &plugin.manifest.prompts {
981            match (&def.text, &def.file) {
982                (Some(text), None) => resolved.push(PromptDef {
983                    text: Some(text.clone()),
984                    file: None,
985                }),
986                (None, Some(rel)) => {
987                    let path = match manifest_path(&plugin.dir, rel) {
988                        Ok(path) => path,
989                        Err(why) => {
990                            problems.push(format!("plugin `{}`: prompt file {why}", plugin.name));
991                            continue;
992                        }
993                    };
994                    match read_prompt_file(&path) {
995                        Ok((text, cut)) => {
996                            if cut {
997                                problems.push(format!(
998                                    "plugin `{}`: prompt file {} is over {MAX_MANIFEST_FILE_BYTES} bytes and was truncated",
999                                    plugin.name,
1000                                    path.display()
1001                                ));
1002                            }
1003                            resolved.push(PromptDef {
1004                                text: Some(text),
1005                                file: None,
1006                            })
1007                        }
1008                        Err(e) => problems.push(format!(
1009                            "plugin `{}`: prompt file {}: {e}",
1010                            plugin.name,
1011                            path.display()
1012                        )),
1013                    }
1014                }
1015                (Some(_), Some(_)) => problems.push(format!(
1016                    "plugin `{}`: a prompt must have either `text` or `file`, not both",
1017                    plugin.name
1018                )),
1019                (None, None) => problems.push(format!(
1020                    "plugin `{}`: a prompt needs `text` or `file`",
1021                    plugin.name
1022                )),
1023            }
1024        }
1025        plugin.manifest.prompts = resolved;
1026        out.problems.extend(problems);
1027    }
1028    out
1029}
1030
1031/// The largest a plugin-authored file may be, matching the line `skills.rs` draws for `SKILL.md`:
1032/// a prompt is paid for on every request, so a 5 MB `prompts/*.md` crowds out the conversation it
1033/// was meant to steer.
1034pub const MAX_MANIFEST_FILE_BYTES: u64 = 256 * 1024;
1035
1036/// A manifest's own path, resolved inside the plugin's directory (`#560`).
1037///
1038/// A manifest is a file a plugin author writes, and `dir.join(rel)` is not a confinement:
1039/// `Path::join` discards the base for an absolute path and does nothing about `..` or a symlink. So
1040/// `file = "/home/user/.ssh/id_rsa"` put a host secret into every system prompt, and the same field
1041/// on a `[[tool]]` put it into a tool's schema — with no tool call for a hook or a redaction rule to
1042/// see. A manifest path is a path inside its own plugin, and that is the only thing it may name.
1043///
1044/// The target is resolved before it is checked, so a symlink inside the directory is followed only
1045/// when it stays inside it and a `..` component cannot walk out. It must be a regular file too:
1046/// `read_data_file` decides by length, and a FIFO's length is 0, so the length check alone left the
1047/// loader hanging on `mkfifo fixture.json`.
1048fn manifest_path(dir: &Path, rel: &str) -> std::result::Result<PathBuf, String> {
1049    if rel.trim().is_empty() {
1050        return Err("names no file".into());
1051    }
1052    let base = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
1053    let path = dir.join(rel);
1054    let resolved = std::fs::canonicalize(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1055    if !resolved.starts_with(&base) {
1056        return Err(format!(
1057            "{} points outside the plugin ({}); a manifest path has to stay inside its own \
1058             directory",
1059            path.display(),
1060            resolved.display()
1061        ));
1062    }
1063    match std::fs::metadata(&resolved) {
1064        Ok(meta) if meta.is_file() => Ok(resolved),
1065        Ok(_) => Err(format!("{} is not a regular file", resolved.display())),
1066        Err(e) => Err(format!("{}: {e}", resolved.display())),
1067    }
1068}
1069
1070/// Read a prompt file, cutting it at [`MAX_MANIFEST_FILE_BYTES`] and marking the cut in the text.
1071///
1072/// `read_skill` refuses an oversized file: a skill that big is a mistake and the author should see
1073/// the error. A prompt is different — the model reads it, so the part that arrived still steers the
1074/// run, and refusing would disable the whole plugin over one long file. The note is what keeps that
1075/// honest: the model is told the text is incomplete, and the caller records a problem so the human
1076/// is told too.
1077///
1078/// Returns the text and whether it was cut.
1079fn read_prompt_file(path: &Path) -> Result<(String, bool), String> {
1080    use std::io::Read as _;
1081    let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
1082    let mut bytes = Vec::new();
1083    file.take(MAX_MANIFEST_FILE_BYTES + 1)
1084        .read_to_end(&mut bytes)
1085        .map_err(|e| e.to_string())?;
1086    let cut = bytes.len() as u64 > MAX_MANIFEST_FILE_BYTES;
1087    if !cut {
1088        let text = String::from_utf8(bytes).map_err(|e| {
1089            format!(
1090                "not valid UTF-8 (first bad byte at offset {})",
1091                e.utf8_error().valid_up_to()
1092            )
1093        })?;
1094        return Ok((text, false));
1095    }
1096    // The cut can land inside a character. Lossy is right here and only here: the file is already
1097    // being handed to the model incomplete, and a single replacement character at the seam says
1098    // "there is more" better than an error that throws the readable part away.
1099    let mut text = String::from_utf8_lossy(&bytes[..MAX_MANIFEST_FILE_BYTES as usize]).into_owned();
1100    text.push_str(&format!(
1101        "\n\n… (prompt file truncated at {MAX_MANIFEST_FILE_BYTES} bytes)"
1102    ));
1103    Ok((text, true))
1104}
1105
1106/// Read a manifest-referenced data file (JSON), refusing anything over the limit: truncated JSON is
1107/// not JSON, so a cut would only turn a size problem into a parse error.
1108fn read_data_file(path: &Path) -> Result<String, String> {
1109    let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
1110    if meta.len() > MAX_MANIFEST_FILE_BYTES {
1111        return Err(format!(
1112            "is {} bytes; the limit is {MAX_MANIFEST_FILE_BYTES}",
1113            meta.len()
1114        ));
1115    }
1116    std::fs::read_to_string(path).map_err(|e| e.to_string())
1117}
1118
1119fn read_manifest(dir: &Path, dir_name: &str) -> Result<Plugin, String> {
1120    let path = dir.join(MANIFEST);
1121    let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1122    let manifest: Manifest =
1123        toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
1124    if manifest.name != dir_name {
1125        return Err(format!(
1126            "{}: name {:?} does not match its directory {:?}",
1127            path.display(),
1128            manifest.name,
1129            dir_name
1130        ));
1131    }
1132    if manifest.api > API {
1133        return Err(format!(
1134            "{}: needs plugin api {}, this build speaks {API}",
1135            path.display(),
1136            manifest.api
1137        ));
1138    }
1139    for tool in &manifest.tools {
1140        let ok = !tool.name.trim().is_empty()
1141            && tool
1142                .name
1143                .chars()
1144                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
1145        if !ok {
1146            return Err(format!(
1147                "{}: tool name {:?} must be [A-Za-z0-9_-]",
1148                path.display(),
1149                tool.name
1150            ));
1151        }
1152    }
1153    Ok(Plugin {
1154        name: manifest.name.clone(),
1155        version: manifest.version.clone(),
1156        description: manifest.description.clone(),
1157        dir: dir.to_path_buf(),
1158        manifest,
1159        // A manifest that parses is loaded and active; the one caller that loads a plugin without
1160        // it being enabled says so explicitly, right below.
1161        enabled: true,
1162    })
1163}
1164
1165/// Environment a plugin process gets: never the agent's whole environment (which can hold
1166/// the API key), only these, plus the `ECLIPSE_*` context (including `ECLIPSE_SCRIPTS_DIR`
1167/// when there is a scripts directory) and any name the manifest lists. `PATH` is passed as it
1168/// is: the scripts directory is not put on it, so a script cannot take the place of a program
1169/// a plugin relies on.
1170pub(crate) const INHERITED_ENV: [&str; 4] = ["PATH", "HOME", "LANG", "TZ"];
1171
1172struct Context<'a> {
1173    plugin_dir: &'a Path,
1174    workspace: &'a Path,
1175    extra_env: &'a [String],
1176    scripts_dir: Option<&'a Path>,
1177    max_bytes: usize,
1178}
1179
1180struct Output {
1181    stdout: String,
1182    stderr: String,
1183    code: Option<i32>,
1184    stdout_cut: bool,
1185}
1186
1187/// Run one plugin process: no shell, reduced environment, killed on timeout and on drop.
1188async fn run_command(
1189    command: &[String],
1190    cwd: &Path,
1191    timeout: Duration,
1192    ctx: Context<'_>,
1193    stdin_json: Value,
1194) -> Result<Output, String> {
1195    let Some(bin) = command.first() else {
1196        return Err("no command".into());
1197    };
1198    let mut cmd = tokio::process::Command::new(bin);
1199    cmd.args(&command[1..])
1200        .current_dir(cwd)
1201        .env_clear()
1202        .stdin(std::process::Stdio::piped())
1203        .stdout(std::process::Stdio::piped())
1204        .stderr(std::process::Stdio::piped())
1205        .kill_on_drop(true);
1206    for key in INHERITED_ENV {
1207        if let Ok(v) = std::env::var(key) {
1208            cmd.env(key, v);
1209        }
1210    }
1211    for key in ctx.extra_env {
1212        if let Ok(v) = std::env::var(key) {
1213            cmd.env(key, v);
1214        }
1215    }
1216    if let Some(dir) = ctx.scripts_dir {
1217        cmd.env("ECLIPSE_SCRIPTS_DIR", dir);
1218    }
1219    cmd.env("ECLIPSE_PLUGIN_DIR", ctx.plugin_dir)
1220        .env("ECLIPSE_WORKSPACE", ctx.workspace);
1221    // `#371`: one environment string is capped at `MAX_ARG_STRLEN` (131072 bytes) and `spawn` fails
1222    // with `E2BIG` past it — which a `before` hook reports as "could not run", i.e. deny, so a
1223    // large `write_file` was refused by every guard with a message that never mentioned size. Above
1224    // the safe half of that ceiling the variable is not set at all: stdin carries the same payload
1225    // and is the authoritative copy, and the size is left behind so a plugin can tell "empty" from
1226    // "too big to duplicate into the environment".
1227    let payload = stdin_json.to_string();
1228    if payload.len() <= ARGS_ENV_MAX {
1229        cmd.env("ECLIPSE_ARGS", &payload);
1230    } else {
1231        cmd.env("ECLIPSE_ARGS_BYTES", payload.len().to_string());
1232    }
1233    if let Some(tool) = stdin_json.get("tool").and_then(|t| t.as_str()) {
1234        cmd.env("ECLIPSE_TOOL", tool);
1235    }
1236    #[cfg(unix)]
1237    cmd.process_group(0);
1238    let mut child = cmd
1239        .spawn()
1240        .map_err(|e| format!("failed to start `{bin}`: {e}"))?;
1241    let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1242    let cap = ctx.max_bytes;
1243    let run = async {
1244        // `#371`: the write is inside the timeout. A plugin that never reads stdin and never exits
1245        // blocks here for ever once the payload passes the pipe buffer (64 KiB), and the clock that
1246        // is meant to bound the run used to start *after* this line. Dropping the handle closes the
1247        // pipe, which is how a plugin sees end-of-input.
1248        if let Some(mut stdin) = child.stdin.take() {
1249            use tokio::io::AsyncWriteExt;
1250            let _ = stdin.write_all(payload.as_bytes()).await;
1251        }
1252        let (out, err) = tokio::join!(read_capped(stdout, cap), read_capped(stderr, cap));
1253        (out, err, child.wait().await)
1254    };
1255    let outcome = tokio::time::timeout(timeout, run).await;
1256    if outcome.is_err() {
1257        // `#569`: `process_group(0)` is set at the spawn, so the group is ours to stop — but
1258        // `kill_on_drop` only signals the direct child. A plugin that shells out (`sh -c '… | …'`,
1259        // a wrapper script, an MCP server started by one) left its grandchildren running past the
1260        // timeout, holding the pipes and the machine.
1261        stop_group(&mut child).await;
1262    }
1263    match outcome {
1264        Err(_) => Err(format!("timed out after {}s", timeout.as_secs())),
1265        Ok(((out, out_cut), (err, _), status)) => {
1266            let status = status.map_err(|e| format!("failed to wait: {e}"))?;
1267            Ok(Output {
1268                stdout: out,
1269                stderr: err,
1270                code: status.code(),
1271                stdout_cut: out_cut,
1272            })
1273        }
1274    }
1275}
1276
1277/// Stop a plugin process and everything it started (`#569`).
1278async fn stop_group(child: &mut tokio::process::Child) {
1279    #[cfg(unix)]
1280    if let Some(pid) = child.id() {
1281        // SAFETY: a negative pid names a process *group*, and this is the group the child leads
1282        // (`process_group(0)` at the spawn). Nothing else of ours is in it.
1283        unsafe {
1284            libc::kill(-(pid as i32), libc::SIGKILL);
1285        }
1286    }
1287    let _ = child.start_kill();
1288    let _ = child.wait().await;
1289}
1290
1291/// A tool implemented by a plugin command.
1292struct CommandTool {
1293    name: String,
1294    description: String,
1295    parameters: Value,
1296    command: Vec<String>,
1297    plugin: String,
1298    plugin_dir: PathBuf,
1299    workspace: PathBuf,
1300    cwd: Cwd,
1301    timeout: Duration,
1302    env: Vec<String>,
1303    max_bytes: usize,
1304    scripts_dir: Option<PathBuf>,
1305}
1306
1307#[async_trait]
1308impl Tool for CommandTool {
1309    fn name(&self) -> &str {
1310        &self.name
1311    }
1312    fn description(&self) -> &str {
1313        &self.description
1314    }
1315    fn parameters(&self) -> Value {
1316        self.parameters.clone()
1317    }
1318    fn describe_call(&self, args: &Value) -> String {
1319        format!("run {}({args}) from plugin {}", self.name, self.plugin)
1320    }
1321    async fn call(&self, args: Value) -> Result<String, ToolError> {
1322        let cwd = match self.cwd {
1323            Cwd::Workspace => self.workspace.clone(),
1324            Cwd::Plugin => self.plugin_dir.clone(),
1325        };
1326        let payload = json!({
1327            "tool": self.name,
1328            "arguments": args,
1329            "plugin": self.plugin,
1330            "workspace": self.workspace.display().to_string(),
1331        });
1332        let out = run_command(
1333            &self.command,
1334            &cwd,
1335            self.timeout,
1336            Context {
1337                plugin_dir: &self.plugin_dir,
1338                workspace: &self.workspace,
1339                extra_env: &self.env,
1340                scripts_dir: self.scripts_dir.as_deref(),
1341                max_bytes: self.max_bytes,
1342            },
1343            payload,
1344        )
1345        .await
1346        .map_err(ToolError::Failed)?;
1347        let truncated = if out.stdout_cut { "\n[truncated]" } else { "" };
1348        let stdout = out.stdout.trim_end_matches('\n');
1349        if out.code == Some(0) {
1350            return Ok(format!("{stdout}{truncated}"));
1351        }
1352        let code = out
1353            .code
1354            .map(|c| c.to_string())
1355            .unwrap_or_else(|| "signal".into());
1356        Err(ToolError::Failed(format!(
1357            "exit code {code}\nstdout:\n{stdout}{truncated}\nstderr:\n{}",
1358            out.stderr.trim_end_matches('\n')
1359        )))
1360    }
1361}
1362
1363/// One `[[hook]]`. See [`Hooks`] for when it runs and what it may do.
1364pub struct Hook {
1365    event: Event,
1366    tool: Option<String>,
1367    command: Vec<String>,
1368    timeout: Duration,
1369    cwd: Cwd,
1370    env: Vec<String>,
1371    plugin_dir: PathBuf,
1372    plugin: String,
1373    max_bytes: usize,
1374    scripts_dir: Option<PathBuf>,
1375}
1376
1377impl Hook {
1378    fn matches(&self, tool: &str) -> bool {
1379        match &self.tool {
1380            None => true,
1381            Some(p) if p == "*" => true,
1382            Some(p) => p == tool,
1383        }
1384    }
1385}
1386
1387/// What a `before_tool` hook decided.
1388pub enum Verdict {
1389    Allow,
1390    /// Refuse the call; the reason goes back to the model.
1391    Deny(String),
1392}
1393
1394/// The hooks of every loaded plugin, ready to run around a tool call.
1395#[derive(Default, Clone)]
1396pub struct Hooks {
1397    hooks: Vec<Arc<Hook>>,
1398    workspace: PathBuf,
1399    profile: String,
1400}
1401
1402impl Hooks {
1403    pub fn new(hooks: Vec<Arc<Hook>>, workspace: PathBuf, profile: impl Into<String>) -> Self {
1404        Self {
1405            hooks,
1406            workspace,
1407            profile: profile.into(),
1408        }
1409    }
1410
1411    /// Every `before_tool` hook runs in load order; the first refusal wins. A hook that
1412    /// cannot run (missing file, timeout, crash) refuses too: a guard that silently stops
1413    /// guarding is worse than a stopped tool.
1414    ///
1415    /// `call_id` names the model-issued tool call this is (`None` when the caller is not
1416    /// the loop). With concurrency above 1 the payloads of several calls interleave, so a
1417    /// hook that keeps per-call state keys on it.
1418    pub async fn before(&self, tool: &str, arguments: &Value, call_id: Option<&str>) -> Verdict {
1419        for hook in self.hooks.iter().filter(|h| h.event == Event::BeforeTool) {
1420            if !hook.matches(tool) {
1421                continue;
1422            }
1423            let payload = json!({
1424                "event": "before_tool",
1425                "tool": tool,
1426                "arguments": arguments,
1427                "call_id": call_id,
1428                "plugin": hook.plugin,
1429                "workspace": self.workspace.display().to_string(),
1430                "profile": self.profile,
1431            });
1432            let out = self.run(hook, payload).await;
1433            match out {
1434                Ok(o) if o.code == Some(0) => continue,
1435                Ok(o) => {
1436                    let reason = if !o.stderr.trim().is_empty() {
1437                        o.stderr.trim().to_string()
1438                    } else if !o.stdout.trim().is_empty() {
1439                        o.stdout.trim().to_string()
1440                    } else {
1441                        format!("refused by plugin `{}`", hook.plugin)
1442                    };
1443                    return Verdict::Deny(reason);
1444                }
1445                Err(why) => {
1446                    return Verdict::Deny(format!(
1447                        "refused: the `{}` guard for this tool could not run ({why})",
1448                        hook.plugin
1449                    ))
1450                }
1451            }
1452        }
1453        Verdict::Allow
1454    }
1455
1456    /// Every matching `after_tool` hook sees the outcome; a hook that prints something and
1457    /// exits 0 replaces the output, so one hook can redact what another added. A failing
1458    /// hook leaves the output alone.
1459    pub async fn after(
1460        &self,
1461        tool: &str,
1462        arguments: &Value,
1463        outcome: ToolOutcome,
1464        call_id: Option<&str>,
1465    ) -> ToolOutcome {
1466        let mut outcome = outcome;
1467        for hook in self.hooks.iter().filter(|h| h.event == Event::AfterTool) {
1468            if !hook.matches(tool) {
1469                continue;
1470            }
1471            let payload = json!({
1472                "event": "after_tool",
1473                "tool": tool,
1474                "arguments": arguments,
1475                "output": outcome.output.clone(),
1476                "is_error": outcome.is_error,
1477                "call_id": call_id,
1478                "plugin": hook.plugin,
1479                "workspace": self.workspace.display().to_string(),
1480                "profile": self.profile,
1481            });
1482            if let Ok(o) = self.run(hook, payload).await {
1483                if o.code == Some(0) && !o.stdout.trim().is_empty() {
1484                    outcome.output = o.stdout.trim_end_matches('\n').to_string();
1485                }
1486            }
1487        }
1488        outcome
1489    }
1490
1491    async fn run(&self, hook: &Hook, payload: Value) -> Result<Output, String> {
1492        let cwd = match hook.cwd {
1493            Cwd::Workspace => self.workspace.clone(),
1494            Cwd::Plugin => hook.plugin_dir.clone(),
1495        };
1496        run_command(
1497            &hook.command,
1498            &cwd,
1499            hook.timeout,
1500            Context {
1501                plugin_dir: &hook.plugin_dir,
1502                workspace: &self.workspace,
1503                extra_env: &hook.env,
1504                scripts_dir: hook.scripts_dir.as_deref(),
1505                max_bytes: hook.max_bytes,
1506            },
1507            payload,
1508        )
1509        .await
1510    }
1511}
1512
1513/// Every directory that has a manifest, whether or not it is enabled, in search order. Used
1514/// by `eclipse plugins list` so a plugin you forgot to enable is still visible.
1515pub fn discover_all(dirs: &[PathBuf]) -> Vec<(String, PathBuf)> {
1516    let mut out: Vec<(String, PathBuf)> = Vec::new();
1517    for dir in dirs {
1518        let Ok(entries) = std::fs::read_dir(dir) else {
1519            continue;
1520        };
1521        let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1522        paths.sort();
1523        for path in paths {
1524            if path.join(MANIFEST).is_file() {
1525                let name = path
1526                    .file_name()
1527                    .map(|n| n.to_string_lossy().to_string())
1528                    .unwrap_or_default();
1529                if !out.iter().any(|(n, _)| n == &name) {
1530                    out.push((name, path));
1531                }
1532            }
1533        }
1534    }
1535    out
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use super::*;
1541
1542    /// `#569`: a plugin that times out takes its process group with it. `process_group(0)` was
1543    /// already set and `kill_on_drop` was armed, but drop signals only the direct child — so a
1544    /// plugin that shelled out left its grandchild running past the timeout, holding the pipes and
1545    /// the machine. That is the leak `#418` fixed for MCP stdio, in the other place a plugin runs.
1546    #[tokio::test]
1547    async fn a_timed_out_plugin_takes_its_grandchild_with_it() {
1548        let dir = tempfile::tempdir().unwrap();
1549        let pidfile = dir.path().join("grandchild.pid");
1550        let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
1551        let ctx = Context {
1552            plugin_dir: dir.path(),
1553            workspace: dir.path(),
1554            extra_env: &[],
1555            scripts_dir: None,
1556            max_bytes: 64 * 1024,
1557        };
1558        let out = run_command(
1559            &["sh".into(), "-c".into(), script],
1560            dir.path(),
1561            std::time::Duration::from_millis(400),
1562            ctx,
1563            serde_json::json!({}),
1564        )
1565        .await;
1566        assert!(out.is_err(), "the timeout is the answer");
1567
1568        let pid: i32 = std::fs::read_to_string(&pidfile)
1569            .expect("the grandchild wrote its pid before the timeout")
1570            .trim()
1571            .parse()
1572            .unwrap();
1573        let mut gone = false;
1574        for _ in 0..20 {
1575            // SAFETY: signal 0 asks whether the process exists; nothing is delivered.
1576            if unsafe { libc::kill(pid, 0) } != 0 {
1577                gone = true;
1578                break;
1579            }
1580            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1581        }
1582        assert!(gone, "the grandchild outlived the plugin that started it");
1583    }
1584
1585    /// `#539`: the same endpoint `config show` scrubs was printed verbatim in the one line `mcp list`
1586    /// and the dashboard use — `http https://user:pw@host/mcp` is the password on screen.
1587    #[test]
1588    fn an_mcp_listing_line_does_not_print_the_credentials_in_its_url() {
1589        let spec: mcp::Spec = toml::from_str(
1590            "name = \"gh\"\ntransport = \"http\"\nurl = \"https://user:pw@example.test/mcp?token=abc\"\n",
1591        )
1592        .unwrap();
1593        let line = describe_command(&spec);
1594        assert!(!line.contains("pw"), "{line}");
1595        assert!(!line.contains("abc"), "{line}");
1596        assert!(
1597            line.contains("example.test/mcp"),
1598            "the endpoint is still recognisable: {line}"
1599        );
1600
1601        let plain: mcp::Spec = toml::from_str(
1602            "name = \"plain\"\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n",
1603        )
1604        .unwrap();
1605        assert_eq!(
1606            describe_command(&plain),
1607            "http https://example.test/mcp",
1608            "nothing to hide, nothing changed"
1609        );
1610    }
1611
1612    fn write(dir: &Path, rel: &str, text: &str) {
1613        let p = dir.join(rel);
1614        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1615        std::fs::write(p, text).unwrap();
1616    }
1617
1618    fn manifest(dir: &Path, name: &str) {
1619        write(
1620            dir,
1621            "plugin.toml",
1622            &format!(
1623                "name = \"{name}\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1624                 [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
1625                 command = [\"sh\", \"-c\", \"echo hello $ECLIPSE_ARGS\"]\n\
1626                 policy = \"allow\"\n"
1627            ),
1628        );
1629    }
1630
1631    /// `#517`: the word a listing prints comes from the same lookup the connection uses — so a
1632    /// token kept in `.env` reads `.env`, and one nothing sets reads `unset` beside the entry it
1633    /// will doom, without anybody pressing *test*. Both entries are `disabled`, so no process is
1634    /// started to learn this.
1635    #[test]
1636    fn a_listing_says_where_a_token_env_resolves() {
1637        let tmp = tempfile::tempdir().unwrap();
1638        // Names built at run time, so they stay test details rather than variables the build is
1639        // documented to read (`every_environment_variable_the_build_reads_is_classified`).
1640        let kept = format!("ECLIPSE_TEST_LIST_{}", "TOKEN");
1641        let absent = format!("{kept}_UNSET");
1642        std::env::remove_var(&kept);
1643        std::env::remove_var(&absent);
1644        let mut cfg = crate::config::parse_text(&format!(
1645            "[[mcp]]\nname = \"ha\"\ntransport = \"http\"\n\
1646             url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{kept}\"\ndisabled = true\n\n\
1647             [[mcp]]\nname = \"dead\"\ntransport = \"http\"\n\
1648             url = \"http://127.0.0.1:9/api/mcp\"\ntoken_env = \"{absent}\"\ndisabled = true\n"
1649        ))
1650        .unwrap();
1651        // The config loader's own values, which is where `.env` lands.
1652        cfg.dotenv.values.insert(kept.clone(), "kept".to_string());
1653
1654        let loaded = load(&[], &[]).with_config_mcp(&cfg);
1655        let (rows, _) = loaded.mcp_report(tmp.path());
1656        let row = |name: &str| {
1657            rows.iter()
1658                .find(|r| r.name == name)
1659                .unwrap_or_else(|| panic!("{name} is not listed: {rows:?}"))
1660        };
1661        assert_eq!(row("ha").token_env.as_deref(), Some(kept.as_str()));
1662        assert_eq!(row("ha").token, crate::mcp::TokenSource::Dotenv);
1663        assert_eq!(row("ha").token.as_str(), ".env");
1664        assert_eq!(row("dead").token, crate::mcp::TokenSource::Unset);
1665        assert_eq!(row("dead").token.as_str(), "unset");
1666    }
1667
1668    /// `#352`: the config is a second provider for `[[mcp]]`, and it wins a name clash — a server
1669    /// declared in both places must not be started twice under one name.
1670    #[test]
1671    fn a_config_server_shadows_a_manifest_server_of_the_same_name() {
1672        let tmp = tempfile::tempdir().unwrap();
1673        let dir = tmp.path().join("plugins");
1674        write(
1675            &dir.join("pack"),
1676            "plugin.toml",
1677            r#"name = "pack"
1678version = "0.1.0"
1679
1680[[mcp]]
1681name = "notes"
1682command = "true"
1683policy = "allow"
1684"#,
1685        );
1686        // Through the door the product uses: `with_config_mcp` takes the loaded config, not a
1687        // `Vec<Spec>`, because a server also needs the `.env` values its `token_env` may name
1688        // (`#516`).
1689        let cfg =
1690            crate::config::parse_text("[[mcp]]\nname = \"notes\"\ncommand = \"false\"\n").unwrap();
1691        let loaded = load(&[dir], &["pack".into()]).with_config_mcp(&cfg);
1692        let (servers, problems) = loaded.servers(tmp.path());
1693        assert_eq!(servers.len(), 1, "one server, not two");
1694        assert_eq!(servers[0].source.label(), "config:mcp:notes");
1695        assert_eq!(servers[0].spec.command, "false", "the config's command");
1696        assert!(
1697            problems.iter().any(|p| p.contains("which wins")),
1698            "the shadowed entry is said out loud: {problems:?}"
1699        );
1700
1701        // With no config entry the manifest's own server is the one that runs, and says whose it is.
1702        let alone = load(&[tmp.path().join("plugins")], &["pack".into()]);
1703        let (servers, problems) = alone.servers(tmp.path());
1704        assert_eq!(servers[0].source.label(), "plugin:mcp:notes");
1705        assert!(problems.is_empty(), "{problems:?}");
1706    }
1707
1708    #[test]
1709    fn loads_an_enabled_plugin_and_its_tool() {
1710        let tmp = tempfile::tempdir().unwrap();
1711        let dir = tmp.path().join("plugins");
1712        manifest(&dir.join("greeter"), "greeter");
1713        let loaded = load(&[dir], &["greeter".into()]);
1714        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1715        assert_eq!(loaded.plugins.len(), 1);
1716        assert_eq!(loaded.plugins[0].name, "greeter");
1717        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
1718        assert!(problems.is_empty(), "{problems:?}");
1719        assert_eq!(tools.len(), 1);
1720        assert_eq!(tools[0].tool.name(), "greet");
1721        assert_eq!(tools[0].policy, Policy::Allow);
1722    }
1723
1724    /// `#371`: the whole payload used to be copied into `ECLIPSE_ARGS`, and Linux caps one
1725    /// environment string at 131072 bytes — past it `spawn` fails with `E2BIG`, which a `before`
1726    /// hook reports as "could not run", i.e. deny. Above 64 KiB the variable is not set at all and
1727    /// the size is; stdin still carries the payload.
1728    #[cfg(unix)]
1729    #[tokio::test]
1730    async fn a_payload_too_big_for_the_environment_still_reaches_the_plugin() {
1731        let tmp = tempfile::tempdir().unwrap();
1732        let dir = tmp.path().join("plugins").join("sizer");
1733        write(&dir, "size.sh", "#!/bin/sh\nprintf 'args=%s bytes=%s stdin=%s\\n' \"${ECLIPSE_ARGS:+set}\" \"${ECLIPSE_ARGS_BYTES:-none}\" \"$(wc -c)\"\n");
1734        write(
1735            &dir,
1736            "plugin.toml",
1737            "name = \"sizer\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1738             [[tool]]\nname = \"size\"\ndescription = \"Report what it was given\"\n\
1739             command = [\"sh\", \"size.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\n",
1740        );
1741        let loaded = load(&[tmp.path().join("plugins")], &["sizer".into()]);
1742        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1743        let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1744        assert!(problems.is_empty(), "{problems:?}");
1745
1746        let big = "x".repeat(200 * 1024);
1747        let out = tools[0]
1748            .tool
1749            .call(json!({"body": big}))
1750            .await
1751            .expect("a large payload must not stop the plugin from starting");
1752        assert!(
1753            !out.contains("args=set"),
1754            "the copy does not go into the environment: {out}"
1755        );
1756        assert!(
1757            !out.contains("bytes=none"),
1758            "the size does, so a plugin can tell empty from too big: {out}"
1759        );
1760        assert!(
1761            !out.contains("stdin=0"),
1762            "and the payload itself arrives on stdin: {out}"
1763        );
1764    }
1765
1766    /// `#371`: the stdin write was awaited *outside* the timeout, so a plugin that never reads its
1767    /// input and never exits held the tool call for ever once the payload passed the 64 KiB pipe
1768    /// buffer. The clock covers the write now.
1769    #[cfg(unix)]
1770    #[tokio::test]
1771    async fn a_plugin_that_never_reads_its_input_still_times_out() {
1772        let tmp = tempfile::tempdir().unwrap();
1773        let dir = tmp.path().join("plugins").join("deaf");
1774        write(&dir, "deaf.sh", "#!/bin/sh\nsleep 20\n");
1775        write(
1776            &dir,
1777            "plugin.toml",
1778            "name = \"deaf\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
1779             [[tool]]\nname = \"deaf\"\ndescription = \"Never reads its input\"\n\
1780             command = [\"sh\", \"deaf.sh\"]\ncwd = \"plugin\"\npolicy = \"allow\"\ntimeout_secs = 1\n",
1781        );
1782        let loaded = load(&[tmp.path().join("plugins")], &["deaf".into()]);
1783        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
1784        let (tools, problems) = loaded.tools(tmp.path(), 64 * 1024, &[]);
1785        assert!(problems.is_empty(), "{problems:?}");
1786
1787        let big = "x".repeat(200 * 1024);
1788        let call = tokio::time::timeout(
1789            Duration::from_secs(8),
1790            tools[0].tool.call(json!({"body": big})),
1791        )
1792        .await
1793        .expect("a full pipe must not hold the call");
1794        let err = call.expect_err("it never answered");
1795        assert!(err.to_string().contains("timed out"), "{err}");
1796    }
1797
1798    #[test]
1799    fn a_plugin_that_is_not_enabled_is_ignored_without_noise() {
1800        let tmp = tempfile::tempdir().unwrap();
1801        let dir = tmp.path().join("plugins");
1802        manifest(&dir.join("greeter"), "greeter");
1803        let loaded = load(&[dir], &[]);
1804        assert!(loaded.plugins.is_empty());
1805        assert!(loaded.problems.is_empty());
1806    }
1807
1808    #[test]
1809    fn enabling_a_missing_plugin_is_reported() {
1810        let tmp = tempfile::tempdir().unwrap();
1811        let loaded = load(&[tmp.path().join("plugins")], &["nope".into()]);
1812        assert!(
1813            loaded.problems[0].contains("enabled but was not found"),
1814            "{:?}",
1815            loaded.problems
1816        );
1817    }
1818
1819    #[test]
1820    fn a_name_that_does_not_match_the_directory_is_rejected() {
1821        let tmp = tempfile::tempdir().unwrap();
1822        let dir = tmp.path().join("plugins");
1823        manifest(&dir.join("greeter"), "someone-else");
1824        let loaded = load(&[dir], &["greeter".into()]);
1825        assert!(loaded.plugins.is_empty());
1826        assert!(
1827            loaded.problems[0].contains("does not match"),
1828            "{:?}",
1829            loaded.problems
1830        );
1831    }
1832
1833    #[test]
1834    fn a_newer_api_is_refused() {
1835        let tmp = tempfile::tempdir().unwrap();
1836        let dir = tmp.path().join("plugins");
1837        write(
1838            &dir.join("future"),
1839            "plugin.toml",
1840            "name = \"future\"\napi = 99\n",
1841        );
1842        let loaded = load(&[dir], &["future".into()]);
1843        assert!(
1844            loaded.problems[0].contains("needs plugin api 99"),
1845            "{:?}",
1846            loaded.problems
1847        );
1848    }
1849
1850    #[test]
1851    fn unknown_manifest_keys_are_errors_not_silence() {
1852        let tmp = tempfile::tempdir().unwrap();
1853        let dir = tmp.path().join("plugins");
1854        write(
1855            &dir.join("typo"),
1856            "plugin.toml",
1857            "name = \"typo\"\n[tool]\nname = \"x\"\nemabled = true\n",
1858        );
1859        let loaded = load(&[dir], &["typo".into()]);
1860        assert!(loaded.plugins.is_empty());
1861        assert!(!loaded.problems.is_empty());
1862    }
1863
1864    #[test]
1865    fn a_profile_copy_shadows_the_shared_copy() {
1866        let tmp = tempfile::tempdir().unwrap();
1867        let (shared, profile) = (
1868            tmp.path().join("plugins"),
1869            tmp.path().join("profile-plugins"),
1870        );
1871        for (root, marker) in [(&shared, "shared"), (&profile, "profile")] {
1872            write(
1873                &root.join("greeter"),
1874                "plugin.toml",
1875                &format!("name = \"greeter\"\ndescription = \"{marker}\"\n"),
1876            );
1877        }
1878        let loaded = load(&[profile, shared], &["greeter".into()]);
1879        assert_eq!(loaded.plugins.len(), 1);
1880        assert_eq!(loaded.plugins[0].description, "profile");
1881    }
1882
1883    #[test]
1884    fn replacing_a_tool_needs_an_explicit_override() {
1885        let tmp = tempfile::tempdir().unwrap();
1886        let dir = tmp.path().join("plugins");
1887        write(
1888            &dir.join("shadow"),
1889            "plugin.toml",
1890            "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"nope\"\n\
1891             command = [\"true\"]\n",
1892        );
1893        let builtin = vec!["shell".to_string()];
1894        let loaded = load(std::slice::from_ref(&dir), &["shadow".into()]);
1895        let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1896        assert!(tools.is_empty(), "a silent override must not happen");
1897        assert!(problems[0].contains("override = true"), "{problems:?}");
1898
1899        write(
1900            &dir.join("shadow"),
1901            "plugin.toml",
1902            "name = \"shadow\"\n[[tool]]\nname = \"shell\"\ndescription = \"mine\"\n\
1903             override = true\ncommand = [\"true\"]\n",
1904        );
1905        let loaded = load(&[dir], &["shadow".into()]);
1906        let (tools, problems) = loaded.tools(tmp.path(), 1024, &builtin);
1907        assert!(problems.is_empty(), "{problems:?}");
1908        assert_eq!(tools.len(), 1);
1909    }
1910
1911    #[test]
1912    fn a_tool_without_a_command_or_with_mcp_is_rejected_with_a_reason() {
1913        let tmp = tempfile::tempdir().unwrap();
1914        let dir = tmp.path().join("plugins");
1915        write(
1916            &dir.join("broken"),
1917            "plugin.toml",
1918            "name = \"broken\"\n\
1919             [[tool]]\nname = \"no_cmd\"\ndescription = \"x\"\n\
1920             [[tool]]\nname = \"via_mcp\"\ndescription = \"x\"\nkind = \"mcp\"\n\
1921             command = [\"x\"]\n",
1922        );
1923        let loaded = load(&[dir], &["broken".into()]);
1924        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
1925        assert!(tools.is_empty());
1926        assert_eq!(problems.len(), 2, "{problems:?}");
1927        assert!(problems[0].contains("no `command`"), "{problems:?}");
1928        assert!(
1929            problems[1].contains("belongs on a `[[mcp]]` section"),
1930            "{problems:?}"
1931        );
1932    }
1933
1934    /// A server that offers two tools and answers one of them, so a manifest can be tested end to
1935    /// end: what `tools()` returns, what `source` says, and what each tool may do without asking.
1936    const MCP_FIXTURE: &str = r#"#!/usr/bin/env python3
1937import json, sys
1938
1939def send(obj):
1940    sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1941
1942for line in sys.stdin:
1943    if not line.strip():
1944        continue
1945    msg = json.loads(line)
1946    mid, method = msg.get("id"), msg.get("method")
1947    params = msg.get("params") or {}
1948    if method == "initialize":
1949        send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1950              "capabilities": {"tools": {}}, "serverInfo": {"name": "fixture", "version": "0"}}})
1951    elif method == "notifications/initialized":
1952        pass
1953    elif method == "tools/list":
1954        send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1955            {"name": "read_text_file", "description": "Read a file",
1956             "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}},
1957            {"name": "write_text_file", "description": "Write a file"}]}})
1958    elif method == "tools/call":
1959        send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1960            {"type": "text", "text": "called " + str(params.get("name"))}]}})
1961    elif mid is not None:
1962        send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no"}})
1963"#;
1964
1965    fn mcp_plugin(tmp: &Path, extra: &str) -> PathBuf {
1966        let dir = tmp.join("plugins");
1967        let script = dir.join("fs").join("server.py");
1968        std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1969        std::fs::write(&script, MCP_FIXTURE).unwrap();
1970        let manifest = format!(
1971            "name = \"fs\"\n\n[[mcp]]\nname = \"files\"\ncommand = \"python3\"\n\
1972             args = [\"{}\"]\ncwd = \"plugin\"\ntimeout_secs = 15\n{extra}\n",
1973            script.display()
1974        );
1975        write(&dir.join("fs"), "plugin.toml", &manifest);
1976        dir
1977    }
1978
1979    #[test]
1980    fn mcp_off_starts_no_server_at_all() {
1981        let tmp = tempfile::tempdir().unwrap();
1982        let dir = tmp.path().join("plugins");
1983        // A server whose only job is to leave a mark: if it is ever started, the file exists.
1984        let marker = tmp.path().join("spawned");
1985        let script = dir.join("loud").join("server.sh");
1986        std::fs::create_dir_all(script.parent().unwrap()).unwrap();
1987        std::fs::write(&script, format!("#!/bin/sh\ntouch {}\n", marker.display())).unwrap();
1988        write(
1989            &dir.join("loud"),
1990            "plugin.toml",
1991            &format!(
1992                "name = \"loud\"\n\n[[mcp]]\nname = \"loud\"\ncommand = \"/bin/sh\"\n\
1993                 args = [\"{}\"]\n",
1994                script.display()
1995            ),
1996        );
1997
1998        // With MCP on, the server is started (and is useless: it says nothing back), so the
1999        // plugin is reported as a problem. That is the state `--no-mcp` has to prevent.
2000        let on = load(std::slice::from_ref(&dir), &["loud".into()]);
2001        let (_tools, problems) = on.tools(tmp.path(), 4096, &[]);
2002        assert!(
2003            !problems.is_empty(),
2004            "a bad server is reported when MCP is on"
2005        );
2006        assert!(
2007            marker.exists(),
2008            "when MCP is on, the server process really ran"
2009        );
2010
2011        // With MCP off nothing runs: no process, no problems, no tools.
2012        std::fs::remove_file(&marker).unwrap();
2013        let off = load(&[dir], &["loud".into()]).with_mcp(McpSettings(None));
2014        let (tools, problems) = off.tools(tmp.path(), 4096, &[]);
2015        assert!(
2016            tools.is_empty(),
2017            "no tools from a server that was never asked"
2018        );
2019        assert!(
2020            problems.is_empty(),
2021            "nothing to complain about when nothing ran: {problems:?}"
2022        );
2023        assert!(
2024            !marker.exists(),
2025            "with MCP off, no server process was spawned"
2026        );
2027
2028        // The ceiling a server with no `timeout_secs` gets: `[plugins] mcp_timeout_secs` when it
2029        // says, the plugin default when it does not.
2030        assert_eq!(
2031            mcp_timeout(&crate::config::Config::default()),
2032            DEFAULT_TIMEOUT
2033        );
2034        let mut cfg = crate::config::Config::default();
2035        cfg.plugins.mcp_timeout_secs = Some(5);
2036        assert_eq!(mcp_timeout(&cfg), Duration::from_secs(5));
2037    }
2038
2039    #[test]
2040    fn an_mcp_server_contributes_its_tools_with_their_own_source_and_policies() {
2041        if std::process::Command::new("python3")
2042            .arg("--version")
2043            .output()
2044            .map(|o| !o.status.success())
2045            .unwrap_or(true)
2046        {
2047            return;
2048        }
2049        let tmp = tempfile::tempdir().unwrap();
2050        let dir = mcp_plugin(tmp.path(), "policies = { read_text_file = \"allow\" }");
2051        let loaded = load(&[dir], &["fs".into()]);
2052        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2053        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2054        assert!(problems.is_empty(), "{problems:?}");
2055        let names: Vec<&str> = tools.iter().map(|t| t.tool.name()).collect();
2056        assert_eq!(names, ["read_text_file", "write_text_file"]);
2057        // The source names the server, not just the plugin: two servers in one manifest is normal.
2058        for t in &tools {
2059            assert_eq!(t.source.label(), "plugin:mcp:files", "{}", t.tool.name());
2060        }
2061        // The per-tool override wins; everything else keeps the server's `ask`.
2062        let read = tools
2063            .iter()
2064            .find(|t| t.tool.name() == "read_text_file")
2065            .unwrap();
2066        let write = tools
2067            .iter()
2068            .find(|t| t.tool.name() == "write_text_file")
2069            .unwrap();
2070        assert_eq!(read.policy, Policy::Allow);
2071        assert_eq!(write.policy, Policy::Ask);
2072        // The schema is the server's, passed through untouched.
2073        assert_eq!(
2074            read.tool.parameters()["properties"]["path"]["type"],
2075            "string"
2076        );
2077        // And the call goes over the real pipe.
2078        let out = tokio::runtime::Builder::new_current_thread()
2079            .enable_all()
2080            .build()
2081            .unwrap()
2082            .block_on(read.tool.call(json!({"path": "a.txt"})))
2083            .unwrap();
2084        assert_eq!(out, "called read_text_file");
2085
2086        // A second `tools()` — the startup warnings do exactly this — must not start a second
2087        // server: the cache hands back the same one.
2088        let (again, _) = loaded.tools(tmp.path(), 4096, &[]);
2089        assert_eq!(again.len(), 2);
2090        let out = tokio::runtime::Builder::new_current_thread()
2091            .enable_all()
2092            .build()
2093            .unwrap()
2094            .block_on(again[0].tool.call(json!({"path": "b.txt"})))
2095            .unwrap();
2096        assert_eq!(out, "called read_text_file");
2097    }
2098
2099    #[test]
2100    fn a_server_tool_that_collides_is_refused_unless_the_entry_says_override() {
2101        if std::process::Command::new("python3")
2102            .arg("--version")
2103            .output()
2104            .map(|o| !o.status.success())
2105            .unwrap_or(true)
2106        {
2107            return;
2108        }
2109        let tmp = tempfile::tempdir().unwrap();
2110        let dir = mcp_plugin(tmp.path(), "");
2111        let loaded = load(&[dir], &["fs".into()]);
2112        // `read_text_file` is not a built-in here, so pretend it is: the check is the same one a
2113        // plugin tool faces, and a quiet replacement would be the worst outcome.
2114        let builtin = vec!["read_text_file".to_string()];
2115        let (tools, problems) = loaded.tools(tmp.path(), 4096, &builtin);
2116        assert_eq!(tools.len(), 1, "the other one still loads");
2117        assert_eq!(tools[0].tool.name(), "write_text_file");
2118        assert!(
2119            problems[0].contains("collides") && problems[0].contains("override = true"),
2120            "{problems:?}"
2121        );
2122    }
2123
2124    #[test]
2125    fn a_server_that_will_not_start_is_one_problem_and_no_tools() {
2126        let tmp = tempfile::tempdir().unwrap();
2127        let dir = tmp.path().join("plugins");
2128        write(
2129            &dir.join("dead"),
2130            "plugin.toml",
2131            "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
2132        );
2133        let loaded = load(&[dir], &["dead".into()]);
2134        assert!(loaded.problems.is_empty(), "the manifest itself is fine");
2135        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2136        assert!(tools.is_empty());
2137        assert!(
2138            problems[0].contains("could not start") && problems[0].contains("gone"),
2139            "{problems:?}"
2140        );
2141    }
2142
2143    #[test]
2144    fn inline_parameters_and_a_schema_file_both_work() {
2145        let tmp = tempfile::tempdir().unwrap();
2146        let dir = tmp.path().join("plugins");
2147        write(
2148            &dir.join("p"),
2149            "plugin.toml",
2150            "name = \"p\"\n\
2151             [[tool]]\nname = \"inline\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2152             parameters = { type = \"object\", properties = { n = { type = \"string\" } } }\n\
2153             [[tool]]\nname = \"from_file\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
2154             parameters = \"tools/from_file.json\"\n",
2155        );
2156        write(
2157            &dir.join("p"),
2158            "tools/from_file.json",
2159            "{\"type\":\"object\",\"properties\":{\"n\":{\"type\":\"integer\"}}}",
2160        );
2161        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2162        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2163        assert!(problems.is_empty(), "{problems:?}");
2164        assert_eq!(
2165            tools[0].tool.parameters()["properties"]["n"]["type"],
2166            "string"
2167        );
2168        assert_eq!(
2169            tools[1].tool.parameters()["properties"]["n"]["type"],
2170            "integer"
2171        );
2172
2173        std::fs::remove_file(dir.join("p/tools/from_file.json")).unwrap();
2174        let loaded = load(&[dir], &["p".into()]);
2175        let (tools, problems) = loaded.tools(tmp.path(), 1024, &[]);
2176        assert_eq!(tools.len(), 1);
2177        assert!(problems[0].contains("from_file.json"), "{problems:?}");
2178    }
2179
2180    #[cfg(unix)]
2181    #[tokio::test]
2182    async fn a_command_tool_gets_json_on_stdin_and_returns_stdout() {
2183        let tmp = tempfile::tempdir().unwrap();
2184        let dir = tmp.path().join("plugins");
2185        write(
2186            &dir.join("echoer"),
2187            "plugin.toml",
2188            "name = \"echoer\"\n[[tool]]\nname = \"echo_args\"\n\
2189             description = \"Echo the JSON it was given\"\n\
2190             command = [\"sh\", \"-c\", \"cat\"]\npolicy = \"allow\"\n",
2191        );
2192        let loaded = load(&[dir], &["echoer".into()]);
2193        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2194        let out = tools[0]
2195            .tool
2196            .call(json!({"path": "a.txt"}))
2197            .await
2198            .expect("tool should succeed");
2199        let sent: Value = serde_json::from_str(&out).unwrap();
2200        assert_eq!(sent["arguments"]["path"], "a.txt");
2201        assert_eq!(sent["tool"], "echo_args");
2202    }
2203
2204    #[cfg(unix)]
2205    #[tokio::test]
2206    async fn a_non_zero_exit_is_an_error_that_carries_both_streams() {
2207        let tmp = tempfile::tempdir().unwrap();
2208        let dir = tmp.path().join("plugins");
2209        write(
2210            &dir.join("fail"),
2211            "plugin.toml",
2212            "name = \"fail\"\n[[tool]]\nname = \"boom\"\ndescription = \"x\"\n\
2213             command = [\"sh\", \"-c\", \"echo out; echo bad >&2; exit 3\"]\npolicy = \"allow\"\n",
2214        );
2215        let loaded = load(&[dir], &["fail".into()]);
2216        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2217        let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2218        assert!(err.contains("exit code 3"), "{err}");
2219        assert!(err.contains("out") && err.contains("bad"), "{err}");
2220    }
2221
2222    #[cfg(unix)]
2223    #[tokio::test]
2224    async fn the_command_runs_in_the_workspace_and_only_sees_the_allowed_environment() {
2225        let tmp = tempfile::tempdir().unwrap();
2226        let (dir, ws) = (tmp.path().join("plugins"), tmp.path().join("ws"));
2227        std::fs::create_dir_all(&ws).unwrap();
2228        std::env::set_var("PLUGIN_TEST_SECRET", "leak-me");
2229        std::env::set_var("PLUGIN_TEST_ALLOWED", "ok");
2230        write(
2231            &dir.join("env"),
2232            "plugin.toml",
2233            "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2234             command = [\"sh\", \"-c\", \"pwd; echo secret=[${PLUGIN_TEST_SECRET:-}]; \
2235             echo allowed=[${PLUGIN_TEST_ALLOWED:-}]\"]\n\
2236             env = [\"PLUGIN_TEST_ALLOWED\"]\npolicy = \"allow\"\n",
2237        );
2238        let loaded = load(&[dir], &["env".into()]);
2239        let (tools, _) = loaded.tools(&ws, 4096, &[]);
2240        let out = tools[0].tool.call(json!({})).await.unwrap();
2241        let canonical = std::fs::canonicalize(&ws).unwrap();
2242        assert!(out.contains(&canonical.display().to_string()), "{out}");
2243        assert!(
2244            out.contains("secret=[]"),
2245            "the agent environment must not leak: {out}"
2246        );
2247        assert!(out.contains("allowed=[ok]"), "{out}");
2248        std::env::remove_var("PLUGIN_TEST_SECRET");
2249        std::env::remove_var("PLUGIN_TEST_ALLOWED");
2250    }
2251
2252    #[cfg(unix)]
2253    #[tokio::test]
2254    async fn a_plugin_tool_is_told_where_the_scripts_are_and_its_path_is_left_alone() {
2255        let tmp = tempfile::tempdir().unwrap();
2256        let dir = tmp.path().join("plugins");
2257        let scripts = tmp.path().join("scripts");
2258        write(
2259            &dir.join("env"),
2260            "plugin.toml",
2261            "name = \"env\"\n[[tool]]\nname = \"envdump\"\ndescription = \"x\"\n\
2262             command = [\"sh\", \"-c\", \"echo scripts=[${ECLIPSE_SCRIPTS_DIR:-}]; echo path=[$PATH]\"]\n\
2263             policy = \"allow\"\n",
2264        );
2265        let with = load(std::slice::from_ref(&dir), &["env".into()])
2266            .with_scripts_dir(Some(scripts.clone()));
2267        let (tools, _) = with.tools(tmp.path(), 4096, &[]);
2268        let out = tools[0].tool.call(json!({})).await.unwrap();
2269        assert!(
2270            out.contains(&format!("scripts=[{}]", scripts.display())),
2271            "{out}"
2272        );
2273        let path_line = out.lines().find(|l| l.starts_with("path=")).unwrap();
2274        assert!(
2275            !path_line.contains(&scripts.display().to_string()),
2276            "a plugin's PATH must not gain the scripts directory: {out}"
2277        );
2278
2279        let without = load(&[dir], &["env".into()]);
2280        let (tools, _) = without.tools(tmp.path(), 4096, &[]);
2281        let out = tools[0].tool.call(json!({})).await.unwrap();
2282        assert!(out.contains("scripts=[]"), "{out}");
2283    }
2284
2285    #[cfg(unix)]
2286    #[tokio::test]
2287    async fn a_hook_process_is_told_where_the_scripts_are_too() {
2288        let tmp = tempfile::tempdir().unwrap();
2289        let dir = tmp.path().join("plugins");
2290        write(
2291            &dir.join("guard"),
2292            "plugin.toml",
2293            "name = \"guard\"\n\
2294             [[hook]]\nevent = \"before_tool\"\n\
2295             command = [\"sh\", \"-c\", \"echo $ECLIPSE_SCRIPTS_DIR >&2; exit 2\"]\n",
2296        );
2297        let loaded = load(&[dir], &["guard".into()])
2298            .with_scripts_dir(Some(PathBuf::from("/somewhere/scripts")));
2299        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2300        match hooks.before("shell", &json!({}), None).await {
2301            Verdict::Deny(why) => assert_eq!(why, "/somewhere/scripts"),
2302            Verdict::Allow => panic!("the hook should have refused"),
2303        }
2304    }
2305
2306    #[cfg(unix)]
2307    #[tokio::test]
2308    async fn a_slow_tool_times_out() {
2309        let tmp = tempfile::tempdir().unwrap();
2310        let dir = tmp.path().join("plugins");
2311        write(
2312            &dir.join("slow"),
2313            "plugin.toml",
2314            "name = \"slow\"\n[[tool]]\nname = \"wait\"\ndescription = \"x\"\n\
2315             command = [\"sleep\", \"30\"]\ntimeout_secs = 1\npolicy = \"allow\"\n",
2316        );
2317        let loaded = load(&[dir], &["slow".into()]);
2318        let (tools, _) = loaded.tools(tmp.path(), 4096, &[]);
2319        let started = std::time::Instant::now();
2320        let err = tools[0].tool.call(json!({})).await.unwrap_err().to_string();
2321        assert!(err.contains("timed out after 1s"), "{err}");
2322        assert!(started.elapsed() < Duration::from_secs(10));
2323    }
2324
2325    #[test]
2326    fn prompt_fragments_are_read_in_order_and_a_broken_one_is_a_problem() {
2327        let tmp = tempfile::tempdir().unwrap();
2328        let dir = tmp.path().join("plugins");
2329        write(
2330            &dir.join("p"),
2331            "plugin.toml",
2332            "name = \"p\"\n\
2333             [[prompt]]\ntext = \"first\"\n\
2334             [[prompt]]\nfile = \"prompts/second.md\"\n",
2335        );
2336        write(&dir.join("p"), "prompts/second.md", "second");
2337        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2338        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2339        assert_eq!(loaded.prompts(), ["first", "second"]);
2340
2341        std::fs::remove_file(dir.join("p/prompts/second.md")).unwrap();
2342        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2343        assert_eq!(loaded.prompts(), ["first"]);
2344        assert!(
2345            loaded.problems[0].contains("prompt file"),
2346            "{:?}",
2347            loaded.problems
2348        );
2349
2350        write(
2351            &dir.join("p"),
2352            "plugin.toml",
2353            "name = \"p\"\n[[prompt]]\ntext = \"x\"\nfile = \"y\"\n",
2354        );
2355        let loaded = load(&[dir], &["p".into()]);
2356        assert!(loaded.prompts().is_empty());
2357        assert!(
2358            loaded.problems[0].contains("either `text` or `file`"),
2359            "{:?}",
2360            loaded.problems
2361        );
2362    }
2363
2364    /// A manifest is untrusted input with a filesystem API: `dir.join(rel)` keeps an absolute path
2365    /// and walks out on `..`, so `file = "/home/you/.ssh/id_rsa"` used to land in every system
2366    /// prompt, and the same field on a tool used to land in its schema (`#560`).
2367    #[test]
2368    fn a_manifest_path_that_points_outside_the_plugin_is_refused() {
2369        let tmp = tempfile::tempdir().unwrap();
2370        let dir = tmp.path().join("plugins");
2371        // Outside the plugin `p`, beside it: what `../` names, and what an absolute path names.
2372        let secret = dir.join("id_rsa");
2373        write(&dir, "id_rsa", "-----BEGIN OPENSSH PRIVATE KEY-----\n");
2374
2375        // A prompt fragment, by `..` and by an absolute path.
2376        write(
2377            &dir.join("p"),
2378            "plugin.toml",
2379            "name = \"p\"\n[[prompt]]\nfile = \"../id_rsa\"\n",
2380        );
2381        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2382        assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2383        assert!(
2384            loaded
2385                .problems
2386                .iter()
2387                .any(|p| p.contains("outside the plugin")),
2388            "{:?}",
2389            loaded.problems
2390        );
2391
2392        write(
2393            &dir.join("p"),
2394            "plugin.toml",
2395            &format!("name = \"p\"\n[[prompt]]\nfile = {secret:?}\n"),
2396        );
2397        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2398        assert!(loaded.prompts().is_empty(), "{:?}", loaded.prompts());
2399        assert!(
2400            loaded
2401                .problems
2402                .iter()
2403                .any(|p| p.contains("outside the plugin")),
2404            "{:?}",
2405            loaded.problems
2406        );
2407
2408        // A tool's schema, the other reader of the same field.
2409        write(
2410            &dir.join("p"),
2411            "plugin.toml",
2412            "name = \"p\"\n[[tool]]\nname = \"leak\"\ndescription = \"x\"\n\
2413             command = [\"echo\"]\nparameters = \"../id_rsa\"\npolicy = \"allow\"\n",
2414        );
2415        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2416        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2417        assert!(tools.is_empty(), "no tool was built from the link");
2418        assert!(
2419            problems.iter().any(|p| p.contains("outside the plugin")),
2420            "{:?}",
2421            problems
2422        );
2423    }
2424
2425    /// The rule is the target, not "no paths": a file inside the plugin is what the field is for.
2426    /// A directory is refused with its own sentence rather than read as a zero-length file — a FIFO
2427    /// has length 0 too, and the length check alone hung the loader.
2428    #[test]
2429    fn a_manifest_path_inside_the_plugin_is_read_and_a_directory_is_refused() {
2430        let tmp = tempfile::tempdir().unwrap();
2431        let dir = tmp.path().join("plugins");
2432        write(
2433            &dir.join("p"),
2434            "plugin.toml",
2435            "name = \"p\"\n[[prompt]]\nfile = \"prompts/first.md\"\n",
2436        );
2437        write(&dir.join("p"), "prompts/first.md", "inside");
2438        let loaded = load(std::slice::from_ref(&dir), &["p".into()]);
2439        assert!(loaded.problems.is_empty(), "{:?}", loaded.problems);
2440        assert_eq!(loaded.prompts(), ["inside"]);
2441
2442        std::fs::create_dir_all(dir.join("p/prompts/dir.md")).unwrap();
2443        write(
2444            &dir.join("p"),
2445            "plugin.toml",
2446            "name = \"p\"\n[[prompt]]\nfile = \"prompts/dir.md\"\n",
2447        );
2448        let loaded = load(&[dir], &["p".into()]);
2449        assert!(loaded.prompts().is_empty());
2450        assert!(
2451            loaded
2452                .problems
2453                .iter()
2454                .any(|p| p.contains("not a regular file")),
2455            "{:?}",
2456            loaded.problems
2457        );
2458    }
2459
2460    /// `#419`: a manifest that declares nothing but provider profiles is loaded while *not*
2461    /// enabled — its wire settings are needed before anyone opts in. It used to be pushed into the
2462    /// same list as enabled plugins, and `skills::roots_for` added `<plugin>/skills` for every entry
2463    /// in that list, so an unenabled plugin could expose skills it ships on disk. The two questions
2464    /// ("is it loaded" and "did the user turn it on") were the same field; now they are not.
2465    #[test]
2466    fn a_plugin_loaded_for_its_profiles_is_not_enabled_and_has_no_skills_root() {
2467        let tmp = tempfile::tempdir().unwrap();
2468        let dir = tmp.path().join("plugins");
2469        write(
2470            &dir.join("wire"),
2471            "plugin.toml",
2472            "name = \"wire\"\n\
2473             [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n",
2474        );
2475        // A `skills/` directory the plugin happens to ship, with nothing in the manifest saying so.
2476        write(
2477            &dir.join("wire/skills/sneaky/SKILL.md"),
2478            "SKILL.md",
2479            "---\nname: sneaky\ndescription: not yours\n---\n\nx\n",
2480        );
2481
2482        let loaded = load(std::slice::from_ref(&dir), &[]);
2483        assert_eq!(
2484            loaded.plugins.len(),
2485            1,
2486            "loaded for its profiles: {:?}",
2487            loaded.problems
2488        );
2489        assert!(
2490            !loaded.plugins[0].enabled,
2491            "loaded is not the same as enabled"
2492        );
2493        let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2494        assert!(
2495            !roots.iter().any(|r| r.dir.ends_with("wire/skills")),
2496            "an unenabled plugin's skills are not roots: {roots:?}"
2497        );
2498
2499        // Enabled, it is a normal plugin and its skills are its own to offer.
2500        let loaded = load(&[dir], &["wire".into()]);
2501        assert!(loaded.plugins[0].enabled);
2502        let roots = crate::skills::roots_for(&Default::default(), &|_| None, &loaded, tmp.path());
2503        assert!(roots.iter().any(|r| r.dir.ends_with("wire/skills")));
2504    }
2505
2506    #[test]
2507    fn provider_profiles_override_by_name_and_keep_order() {
2508        let tmp = tempfile::tempdir().unwrap();
2509        let dir = tmp.path().join("plugins");
2510        write(
2511            &dir.join("prov"),
2512            "plugin.toml",
2513            "name = \"prov\"\n\
2514             [[provider_profile]]\nname = \"llamacpp\"\ntool_choice = false\n\
2515             [provider_profile.body]\nchat_template_kwargs = { enable_thinking = false }\n\
2516             [[provider_profile]]\nname = \"acme\"\nsupports_tools = false\n",
2517        );
2518        let loaded = load(&[dir], &["prov".into()]);
2519        let profiles = loaded.provider_profiles();
2520        assert_eq!(profiles.len(), 2);
2521        assert_eq!(profiles[0].name, "llamacpp");
2522        assert!(!profiles[0].tool_choice);
2523        assert_eq!(
2524            profiles[0].body["chat_template_kwargs"]["enable_thinking"],
2525            json!(false)
2526        );
2527        assert!(!profiles[1].supports_tools);
2528    }
2529
2530    #[cfg(unix)]
2531    #[tokio::test]
2532    async fn a_before_tool_hook_can_refuse_with_a_reason() {
2533        let tmp = tempfile::tempdir().unwrap();
2534        let dir = tmp.path().join("plugins");
2535        write(
2536            &dir.join("guard"),
2537            "plugin.toml",
2538            "name = \"guard\"\n\
2539             [[hook]]\nevent = \"before_tool\"\ntool = \"shell\"\n\
2540             command = [\"sh\", \"-c\", \"echo 'no shell in this repo' >&2; exit 2\"]\n",
2541        );
2542        let loaded = load(&[dir], &["guard".into()]);
2543        assert_eq!(loaded.hooks().len(), 1);
2544        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2545        match hooks.before("shell", &json!({"command": "ls"}), None).await {
2546            Verdict::Deny(why) => assert_eq!(why, "no shell in this repo"),
2547            Verdict::Allow => panic!("the hook should have refused"),
2548        }
2549        assert!(matches!(
2550            hooks.before("read_file", &json!({}), None).await,
2551            Verdict::Allow
2552        ));
2553    }
2554
2555    #[cfg(unix)]
2556    #[tokio::test]
2557    async fn a_guard_that_cannot_run_refuses_rather_than_allowing() {
2558        let tmp = tempfile::tempdir().unwrap();
2559        let dir = tmp.path().join("plugins");
2560        write(
2561            &dir.join("broken-guard"),
2562            "plugin.toml",
2563            "name = \"broken-guard\"\n\
2564             [[hook]]\nevent = \"before_tool\"\ncommand = [\"./missing.sh\"]\ncwd = \"plugin\"\n",
2565        );
2566        let loaded = load(&[dir], &["broken-guard".into()]);
2567        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2568        match hooks.before("anything", &json!({}), None).await {
2569            Verdict::Deny(why) => assert!(why.contains("could not run"), "{why}"),
2570            Verdict::Allow => panic!("a guard that cannot run must not silently allow"),
2571        }
2572    }
2573
2574    #[cfg(unix)]
2575    #[tokio::test]
2576    async fn an_after_tool_hook_can_rewrite_the_output() {
2577        let tmp = tempfile::tempdir().unwrap();
2578        let dir = tmp.path().join("plugins");
2579        // stdout is the new output: a redacting hook prints the replacement text. (Reading
2580        // the payload and printing nothing leaves the output untouched, tested below.)
2581        write(
2582            &dir.join("redact"),
2583            "plugin.toml",
2584            "name = \"redact\"\n\
2585             [[hook]]\nevent = \"after_tool\"\n\
2586             command = [\"sh\", \"-c\", \"printf 'the [redacted] is here'\"]\n",
2587        );
2588        let loaded = load(std::slice::from_ref(&dir), &["redact".into()]);
2589        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2590        let out = hooks
2591            .after(
2592                "read_file",
2593                &json!({}),
2594                ToolOutcome {
2595                    output: "the secret is here".into(),
2596                    is_error: false,
2597                    malformed: false,
2598                    deferred: false,
2599                },
2600                None,
2601            )
2602            .await;
2603        assert_eq!(out.output, "the [redacted] is here");
2604        assert!(!out.is_error);
2605
2606        // A hook that prints nothing (or fails) leaves both fields alone.
2607        write(
2608            &dir.join("quiet"),
2609            "plugin.toml",
2610            "name = \"quiet\"\n\
2611             [[hook]]\nevent = \"after_tool\"\ncommand = [\"true\"]\n",
2612        );
2613        let quiet = load(&[dir], &["quiet".into()]);
2614        let hooks = Hooks::new(quiet.hooks(), PathBuf::from("/tmp"), "default");
2615        let out = hooks
2616            .after(
2617                "read_file",
2618                &json!({}),
2619                ToolOutcome {
2620                    output: "unchanged".into(),
2621                    is_error: true,
2622                    malformed: false,
2623                    deferred: false,
2624                },
2625                None,
2626            )
2627            .await;
2628        assert_eq!(out.output, "unchanged");
2629        assert!(out.is_error);
2630    }
2631
2632    #[test]
2633    fn the_shipped_examples_all_load() {
2634        // Keeps `examples/plugins/` honest: a format change that breaks them fails here.
2635        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/plugins");
2636        if !root.is_dir() {
2637            return;
2638        }
2639        let names: Vec<String> = discover_all(std::slice::from_ref(&root))
2640            .into_iter()
2641            .map(|(name, _)| name)
2642            .collect();
2643        assert!(!names.is_empty(), "no examples found in {}", root.display());
2644        let loaded = load(std::slice::from_ref(&root), &names);
2645        assert!(
2646            loaded.problems.is_empty(),
2647            "the shipped examples must load cleanly: {:?}",
2648            loaded.problems
2649        );
2650        let (tools, problems) = loaded.tools(&root, 4096, &[]);
2651        assert!(problems.is_empty(), "{problems:?}");
2652        assert_eq!(tools.len(), 3, "git_status, git_diff, git_log");
2653        assert_eq!(loaded.provider_profiles().len(), 1);
2654        assert_eq!(loaded.hooks().len(), 1);
2655        assert!(!loaded.prompts().is_empty());
2656    }
2657
2658    #[test]
2659    fn discover_all_lists_manifests_whether_enabled_or_not() {
2660        let tmp = tempfile::tempdir().unwrap();
2661        let dir = tmp.path().join("plugins");
2662        manifest(&dir.join("a"), "a");
2663        manifest(&dir.join("b"), "b");
2664        std::fs::create_dir_all(dir.join("not-a-plugin")).unwrap();
2665        let found = discover_all(&[dir]);
2666        assert_eq!(found.len(), 2);
2667    }
2668
2669    #[cfg(unix)]
2670    #[tokio::test]
2671    async fn a_hook_payload_names_the_tool_call_it_is_about() {
2672        // The hook prints its own payload back, so the assertion is about what a plugin
2673        // really receives, not about what we think we send.
2674        let tmp = tempfile::tempdir().unwrap();
2675        let dir = tmp.path().join("plugins");
2676        write(
2677            &dir.join("echo-payload"),
2678            "plugin.toml",
2679            "name = \"echo-payload\"\n\
2680             [[hook]]\nevent = \"after_tool\"\ncommand = [\"sh\", \"-c\", \"cat\"]\n",
2681        );
2682        let loaded = load(&[dir], &["echo-payload".into()]);
2683        let hooks = Hooks::new(loaded.hooks(), PathBuf::from("/tmp"), "default");
2684        let outcome = || ToolOutcome {
2685            output: "x".into(),
2686            is_error: false,
2687            malformed: false,
2688            deferred: false,
2689        };
2690        let named = hooks
2691            .after("read_file", &json!({}), outcome(), Some("c7"))
2692            .await;
2693        assert!(
2694            named.output.contains("\"call_id\":\"c7\""),
2695            "a hook must be able to tell concurrent calls apart: {}",
2696            named.output
2697        );
2698        // A caller that is not the loop has no call to name, and says so rather than lying.
2699        let unnamed = hooks.after("read_file", &json!({}), outcome(), None).await;
2700        assert!(
2701            unnamed.output.contains("\"call_id\":null"),
2702            "{}",
2703            unnamed.output
2704        );
2705    }
2706}
2707
2708#[cfg(test)]
2709mod size_cap_tests {
2710    use super::*;
2711
2712    fn write(dir: &Path, rel: &str, text: &str) {
2713        let p = dir.join(rel);
2714        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
2715        std::fs::write(p, text).unwrap();
2716    }
2717
2718    /// A prompt file goes into the system prompt on every request. Nothing capped it, so one long
2719    /// `prompts/*.md` was paid for on every call and crowded out the conversation.
2720    #[test]
2721    fn an_oversized_prompt_file_is_cut_and_says_so() {
2722        let tmp = tempfile::tempdir().unwrap();
2723        let dir = tmp.path().join("plugins");
2724        write(
2725            &dir.join("longprompt"),
2726            "plugin.toml",
2727            "name = \"longprompt\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2728             [[prompt]]\nfile = \"prompts/rules.md\"\n",
2729        );
2730        // Twice the cap, in a repeated sentence, so the cut is unambiguous.
2731        let line = "keep the answer short and cite the file. ";
2732        let body = line.repeat((MAX_MANIFEST_FILE_BYTES as usize / line.len()) + 10);
2733        write(&dir.join("longprompt"), "prompts/rules.md", &body);
2734
2735        let loaded = load(&[dir], &["longprompt".into()]);
2736        assert!(
2737            loaded
2738                .problems
2739                .iter()
2740                .any(|p| p.contains("truncated") && p.contains("rules.md")),
2741            "the truncation is reported to the human: {:?}",
2742            loaded.problems
2743        );
2744        let text = loaded.plugins[0].manifest.prompts[0]
2745            .text
2746            .as_deref()
2747            .expect("the prompt resolves");
2748        assert!(
2749            text.len() <= MAX_MANIFEST_FILE_BYTES as usize + 128,
2750            "the prompt is capped, not passed through: {} bytes",
2751            text.len()
2752        );
2753        assert!(
2754            text.ends_with("bytes)"),
2755            "and the model is told the text is incomplete: …{}",
2756            &text[text.len().saturating_sub(80)..]
2757        );
2758        assert!(
2759            text.contains(line.trim()),
2760            "the part that arrived is the real text, not a placeholder"
2761        );
2762    }
2763
2764    /// Parameters are JSON: a cut would only turn a size problem into a parse error, so an oversized
2765    /// file is refused with both sizes named and the tool is skipped.
2766    #[test]
2767    fn an_oversized_parameters_file_is_refused_not_truncated() {
2768        let tmp = tempfile::tempdir().unwrap();
2769        let dir = tmp.path().join("plugins");
2770        write(
2771            &dir.join("paramtool"),
2772            "plugin.toml",
2773            "name = \"paramtool\"\nversion = \"0.1.0\"\ndescription = \"test\"\n\
2774             [[tool]]\nname = \"thing\"\ndescription = \"A thing\"\n\
2775             command = [\"sh\", \"-c\", \"echo hi\"]\npolicy = \"allow\"\n\
2776             parameters = \"params.json\"\n",
2777        );
2778        let filler = "x".repeat(MAX_MANIFEST_FILE_BYTES as usize + 1);
2779        write(
2780            &dir.join("paramtool"),
2781            "params.json",
2782            &format!("{{\"type\":\"object\",\"description\":\"{filler}\"}}"),
2783        );
2784
2785        let loaded = load(&[dir], &["paramtool".into()]);
2786        let (tools, problems) = loaded.tools(tmp.path(), 4096, &[]);
2787        assert!(
2788            problems
2789                .iter()
2790                .any(|p| p.contains("limit is") && p.contains("params.json")),
2791            "the refusal names the file and both sizes: {problems:?}"
2792        );
2793        assert!(
2794            tools.is_empty(),
2795            "the tool is not loaded with parameters nobody could read"
2796        );
2797    }
2798}