Skip to main content

graphrt_plugin/
host.rs

1//! The plugin host: loads manifests and registers plugin nodes and tools.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use graphrt_core::catalog::NodeDescriptor;
9use graphrt_core::node::{NodeFactory, Registry};
10use graphrt_core::tool::{ToolRegistry, ToolRuntime, ToolSpec};
11
12use crate::discover::discover;
13use crate::error::PluginError;
14use crate::manifest::{LoadedManifest, Runtime, manifest_in};
15use crate::node::{PluginShared, PluginTools, build_node};
16use crate::transport::Transport;
17
18/// What a [`PluginLoader`] produces for one plugin.
19#[derive(Default)]
20pub struct LoadedPlugin {
21    /// Node kinds with their factories.
22    pub nodes: Vec<NodeEntry>,
23    /// Tools, registered under the plugin name.
24    pub tools: Option<Arc<dyn ToolRuntime>>,
25}
26
27impl fmt::Debug for LoadedPlugin {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        let kinds: Vec<&str> = self.nodes.iter().map(|(d, _)| d.kind.as_str()).collect();
30        f.debug_struct("LoadedPlugin").field("nodes", &kinds).field("tools", &self.tools.is_some()).finish()
31    }
32}
33
34/// Executes plugins of a custom runtime (e.g. `wasm`).
35pub trait PluginLoader: Send + Sync + fmt::Debug {
36    /// Runtime name handled by this loader, as written in manifests.
37    fn runtime(&self) -> &str;
38    /// Load the plugin described by `plugin`.
39    fn load(&self, plugin: &LoadedManifest) -> Result<LoadedPlugin, PluginError>;
40}
41
42/// Summary of a loaded plugin (for `plugin list` style output).
43#[derive(Clone, Debug, PartialEq, serde::Serialize)]
44pub struct PluginInfo {
45    pub name: String,
46    pub version: String,
47    pub description: String,
48    pub runtime: String,
49    pub dir: PathBuf,
50    pub nodes: Vec<String>,
51    pub tools: Vec<String>,
52    /// Effective permissions (requested permissions the host did not grant are off).
53    pub permissions: crate::manifest::Permissions,
54    /// Whether the operator trusts this plugin (see [`PluginHost::trust`]).
55    pub trusted: bool,
56    /// Requested permissions that were not granted, and similar notes for operators.
57    pub warnings: Vec<String>,
58}
59
60/// A node kind with its factory.
61type NodeEntry = (NodeDescriptor, NodeFactory);
62
63struct Entry {
64    plugin: LoadedManifest,
65    shared: Option<Arc<PluginShared>>,
66    trusted: bool,
67    warnings: Vec<String>,
68}
69
70/// Loads plugins and registers them into a [`Registry`] and [`ToolRegistry`].
71///
72/// Permissions in a manifest are *requests*. Plaintext secrets and HTTP bearer
73/// tokens taken from the host environment are only granted to plugins the
74/// operator trusts by name ([`PluginHost::trust`]); a manifest cannot grant them
75/// to itself.
76#[derive(Default)]
77pub struct PluginHost {
78    entries: Vec<Entry>,
79    loaders: HashMap<String, Arc<dyn PluginLoader>>,
80    trusted: std::collections::HashSet<String>,
81}
82
83impl fmt::Debug for PluginHost {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        let names: Vec<&str> = self.entries.iter().map(|e| e.plugin.manifest.name.as_str()).collect();
86        let loaders: Vec<&String> = self.loaders.keys().collect();
87        f.debug_struct("PluginHost").field("plugins", &names).field("loaders", &loaders).finish()
88    }
89}
90
91impl PluginHost {
92    pub fn new() -> Self {
93        Self::default()
94    }
95
96    /// Add a loader for a custom runtime (e.g. `wasm`).
97    pub fn with_loader(mut self, loader: Arc<dyn PluginLoader>) -> Self {
98        self.loaders.insert(loader.runtime().to_owned(), loader);
99        self
100    }
101
102    /// Trust the plugin named `name`: it may receive plaintext secrets and HTTP
103    /// bearer tokens when its manifest requests them. Call before loading.
104    pub fn trust(mut self, name: impl Into<String>) -> Self {
105        self.trusted.insert(name.into());
106        self
107    }
108
109    /// Trust several plugins by name (see [`PluginHost::trust`]).
110    pub fn with_trusted<I, S>(mut self, names: I) -> Self
111    where
112        I: IntoIterator<Item = S>,
113        S: Into<String>,
114    {
115        self.trusted.extend(names.into_iter().map(Into::into));
116        self
117    }
118
119    /// Apply the host's grants to `plugin`'s requested permissions.
120    fn apply_policy(&self, plugin: &mut LoadedManifest) -> Result<(bool, Vec<String>), PluginError> {
121        let name = plugin.manifest.name.clone();
122        let trusted = self.trusted.contains(&name);
123        let mut warnings = Vec::new();
124        if plugin.manifest.permissions.secrets && !trusted {
125            plugin.manifest.permissions.secrets = false;
126            warnings.push(format!(
127                "plugin `{name}` requests plaintext secrets; they stay masked unless the plugin is trusted \
128                 (e.g. `--trust-plugin {name}`)"
129            ));
130        }
131        if let Runtime::Http(h) = &plugin.manifest.runtime {
132            if let Some(var) = &h.bearer_token_env {
133                if !trusted {
134                    return Err(PluginError::Manifest(format!(
135                        "plugin `{name}`: sending host variable `{var}` as a bearer token requires trusting the \
136                         plugin (e.g. `--trust-plugin {name}`)"
137                    )));
138                }
139            }
140        }
141        Ok((trusted, warnings))
142    }
143
144    /// Load the plugin whose manifest is at `manifest_path`.
145    pub fn load(&mut self, manifest_path: &Path) -> Result<PluginInfo, PluginError> {
146        let plugin = LoadedManifest::from_path(manifest_path)?;
147        self.add(plugin)
148    }
149
150    /// Load a plugin directory, or every plugin directly inside `dir`.
151    pub fn load_dir(&mut self, dir: &Path) -> Result<Vec<PluginInfo>, PluginError> {
152        if let Some(manifest) = manifest_in(dir) {
153            return self.load(&manifest).map(|i| vec![i]);
154        }
155        self.load_dirs(&[dir.to_path_buf()])
156    }
157
158    /// Load every plugin found under `paths` (see [`crate::discover`]).
159    pub fn load_dirs(&mut self, paths: &[PathBuf]) -> Result<Vec<PluginInfo>, PluginError> {
160        discover(paths).iter().map(|m| self.load(m)).collect()
161    }
162
163    /// Add an already-parsed plugin.
164    pub fn add(&mut self, mut plugin: LoadedManifest) -> Result<PluginInfo, PluginError> {
165        let name = plugin.manifest.name.clone();
166        if self.entries.iter().any(|e| e.plugin.manifest.name == name) {
167            return Err(PluginError::DuplicatePlugin(name));
168        }
169        let (trusted, warnings) = self.apply_policy(&mut plugin)?;
170        let transport = make_transport(&plugin)?;
171        let shared = transport.map(|t| Arc::new(PluginShared::new(&plugin.manifest, t)));
172        let entry = Entry { plugin, shared, trusted, warnings };
173        let summary = info(&entry);
174        self.entries.push(entry);
175        Ok(summary)
176    }
177
178    /// Add a plugin reachable over an existing transport (e.g. an in-process
179    /// [`crate::IoTransport`]). `plugin.manifest.runtime` is ignored.
180    pub fn add_with_transport(
181        &mut self,
182        mut plugin: LoadedManifest,
183        transport: Arc<dyn Transport>,
184    ) -> Result<PluginInfo, PluginError> {
185        plugin.manifest.validate()?;
186        let name = plugin.manifest.name.clone();
187        if self.entries.iter().any(|e| e.plugin.manifest.name == name) {
188            return Err(PluginError::DuplicatePlugin(name));
189        }
190        let (trusted, warnings) = self.apply_policy(&mut plugin)?;
191        let shared = Some(Arc::new(PluginShared::new(&plugin.manifest, transport)));
192        let entry = Entry { plugin, shared, trusted, warnings };
193        let summary = info(&entry);
194        self.entries.push(entry);
195        Ok(summary)
196    }
197
198    /// Loaded plugins.
199    pub fn plugins(&self) -> Vec<PluginInfo> {
200        self.entries.iter().map(info).collect()
201    }
202
203    /// Descriptors of every plugin node (for catalogs).
204    pub fn descriptors(&self) -> Vec<NodeDescriptor> {
205        self.entries.iter().flat_map(|e| e.plugin.manifest.nodes.iter().map(|d| described(d, &e.plugin))).collect()
206    }
207
208    /// Start every process/HTTP plugin and apply node and tool lists returned by
209    /// `initialize` (when a plugin returns them). Call before [`PluginHost::register`].
210    pub async fn refresh(&mut self) -> Result<(), PluginError> {
211        let clock = graphrt_core::node::default_clock();
212        for entry in &mut self.entries {
213            let Some(shared) = entry.shared.clone() else { continue };
214            let name = entry.plugin.manifest.name.clone();
215            let init = shared
216                .transport
217                .initialize(&clock)
218                .await
219                .map_err(|e| PluginError::Runtime { plugin: name.clone(), message: e.to_string() })?;
220            let mut manifest = entry.plugin.manifest.clone();
221            if let Some(nodes) = init.get("nodes").filter(|n| !n.is_null()) {
222                manifest.nodes = serde_json::from_value(nodes.clone()).map_err(|e| {
223                    PluginError::Manifest(format!("plugin `{name}`: invalid nodes from initialize: {e}"))
224                })?;
225            }
226            if let Some(tools) = init.get("tools").filter(|t| !t.is_null()) {
227                manifest.tools = serde_json::from_value::<Vec<ToolSpec>>(tools.clone()).map_err(|e| {
228                    PluginError::Manifest(format!("plugin `{name}`: invalid tools from initialize: {e}"))
229                })?;
230            }
231            manifest.validate()?;
232            entry.plugin.manifest = manifest;
233            entry.shared = Some(Arc::new(PluginShared::new(&entry.plugin.manifest, shared.transport.clone())));
234        }
235        Ok(())
236    }
237
238    /// Register every plugin's nodes into `registry` and tools into `tools`.
239    /// Fails on node kinds that are already registered (plugins never replace
240    /// built-in or other plugins' nodes).
241    pub fn register(&self, registry: &mut Registry, tools: &mut ToolRegistry) -> Result<(), PluginError> {
242        for entry in &self.entries {
243            let name = &entry.plugin.manifest.name;
244            let (nodes, tool_runtime): (Vec<NodeEntry>, Option<Arc<dyn ToolRuntime>>) = match &entry.shared {
245                Some(shared) => {
246                    let nodes = entry
247                        .plugin
248                        .manifest
249                        .nodes
250                        .iter()
251                        .map(|d| {
252                            let descriptor = described(d, &entry.plugin);
253                            let shared = shared.clone();
254                            let for_factory = descriptor.clone();
255                            let factory: NodeFactory = Arc::new(move |doc| build_node(&shared, &for_factory, doc));
256                            (descriptor, factory)
257                        })
258                        .collect();
259                    let has_tools = !shared.tools.is_empty();
260                    let tools: Option<Arc<dyn ToolRuntime>> =
261                        has_tools.then(|| Arc::new(PluginTools { shared: shared.clone() }) as Arc<dyn ToolRuntime>);
262                    (nodes, tools)
263                }
264                None => {
265                    let runtime = entry.plugin.manifest.runtime.name();
266                    let loader = self
267                        .loaders
268                        .get(runtime)
269                        .ok_or_else(|| PluginError::NoLoader { plugin: name.clone(), runtime: runtime.to_owned() })?;
270                    let loaded = loader.load(&entry.plugin)?;
271                    check_loader_kinds(&entry.plugin.manifest, &loaded.nodes)?;
272                    let nodes = loaded.nodes.into_iter().map(|(d, f)| (described(&d, &entry.plugin), f)).collect();
273                    (nodes, loaded.tools)
274                }
275            };
276            for (descriptor, _) in &nodes {
277                if registry.contains(&descriptor.kind) {
278                    return Err(PluginError::KindConflict { plugin: name.clone(), kind: descriptor.kind.clone() });
279                }
280            }
281            for (descriptor, factory) in nodes {
282                registry.register_described(descriptor, move |doc| factory(doc));
283            }
284            if let Some(runtime) = tool_runtime {
285                if tools.get(name).is_some() {
286                    return Err(PluginError::Runtime {
287                        plugin: name.clone(),
288                        message: format!("a tool provider named `{name}` is already registered"),
289                    });
290                }
291                tools.add(name.clone(), runtime);
292            }
293        }
294        Ok(())
295    }
296}
297
298fn described(descriptor: &NodeDescriptor, plugin: &LoadedManifest) -> NodeDescriptor {
299    descriptor.clone().source(format!("plugin:{}", plugin.manifest.name))
300}
301
302fn info(entry: &Entry) -> PluginInfo {
303    let plugin = &entry.plugin;
304    let m = &plugin.manifest;
305    PluginInfo {
306        name: m.name.clone(),
307        version: m.version.clone(),
308        description: m.description.clone(),
309        runtime: m.runtime.name().to_owned(),
310        dir: plugin.dir.clone(),
311        nodes: m.nodes.iter().map(|n| n.kind.clone()).collect(),
312        tools: m.tools.iter().map(|t| t.name.clone()).collect(),
313        permissions: m.permissions.clone(),
314        trusted: entry.trusted,
315        warnings: entry.warnings.clone(),
316    }
317}
318
319/// Node kinds produced by a loader get the same namespace rules as manifest kinds:
320/// `<name>.<kind>`, or (with `allow_unprefixed_kinds`) a plain name without `.`.
321fn check_loader_kinds(manifest: &crate::manifest::PluginManifest, nodes: &[NodeEntry]) -> Result<(), PluginError> {
322    let prefix = format!("{}.", manifest.name);
323    let mut seen = std::collections::HashSet::new();
324    for (descriptor, _) in nodes {
325        let kind = descriptor.kind.as_str();
326        let plain = manifest.allow_unprefixed_kinds && !kind.contains('.') && !kind.is_empty();
327        if !kind.starts_with(&prefix) && !plain {
328            return Err(PluginError::Manifest(format!(
329                "plugin `{}`: node kind `{kind}` must start with `{prefix}`",
330                manifest.name
331            )));
332        }
333        if kind.chars().any(char::is_whitespace) || !seen.insert(kind) {
334            return Err(PluginError::Manifest(format!(
335                "plugin `{}`: invalid or duplicate node kind `{kind}`",
336                manifest.name
337            )));
338        }
339    }
340    Ok(())
341}
342
343/// Transport for built-in runtimes; `None` for runtimes handled by a loader.
344fn make_transport(plugin: &LoadedManifest) -> Result<Option<Arc<dyn Transport>>, PluginError> {
345    let name = plugin.manifest.name.clone();
346    match &plugin.manifest.runtime {
347        #[cfg(feature = "process")]
348        Runtime::Process(p) => Ok(Some(Arc::new(crate::process::ProcessTransport::new(plugin.clone(), p.clone())))),
349        #[cfg(not(feature = "process"))]
350        Runtime::Process(_) => Err(PluginError::RuntimeDisabled { plugin: name, runtime: "process".into() }),
351        #[cfg(feature = "http")]
352        Runtime::Http(h) => crate::http::HttpTransport::new(plugin, h.clone())
353            .map(|t| Some(Arc::new(t) as Arc<dyn Transport>))
354            .map_err(|e| PluginError::Runtime { plugin: name, message: e.to_string() }),
355        #[cfg(not(feature = "http"))]
356        Runtime::Http(_) => Err(PluginError::RuntimeDisabled { plugin: name, runtime: "http".into() }),
357        _ => Ok(None),
358    }
359}