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