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